10.7 关键路径
10.7 关键路径
http://codeup.hustoj.com/contest.php?cid=100000627
A 关键路径

题目解析
这道题用了dp做,书p439页有讲解
PS:个人觉得这里输入给出的各顶点abcde没啥用,但有可能不是按照26个英文字母顺序给出的顶点
(我默认顶点是顺序给出的AC了)
用拓扑排序的代码可参考:https://blog.csdn.net/morizunzhu/article/details/96652800
代码
#include <cstdio>
#include <algorithm>
#include <iostream>
using namespace std;
#define maxn 20
#define INF 0x3fffffff
int n, G[maxn][maxn]; //存图
int dp[maxn]; //dp[i]表示以i为起点的能得到的最长路径长度
int choose[maxn];
int DP(int i) {
if (dp[i] > 0) return dp[i];
for (int j = 0; j < n; j++) {
if (G[i][j] != INF) {
int temp = DP(j) + G[i][j];
if (temp > dp[i]) {
dp[i] = temp;
choose[i] = j;
}
}
}
return dp[i];
}
void printPath(int i) {
while (choose[i] != -1) {
printf("(%c,%c) ", i + 97, choose[i] + 97);
i = choose[i];
}
}
int main() {
int t, m, w;
char a, b;
scanf("%d", &t);
while (t--) {
fill(G[0], G[0] + maxn * maxn, INF);
fill(dp, dp + maxn, 0);
fill(choose, choose + maxn, -1);
scanf("%d%d", &n, &m);
char temp;
for (int i = 0; i < n; i++) {
cin >> temp;
}
for (int i = 0; i < m; i++) {
cin >> a >> b >> w;
G[a - 97][b - 97] = w;
}
int ans = 0, k,tt;
for (int i = 0; i < n; i++) {
tt = DP(i);
if (tt > ans) {
ans = tt;
k=i;
}
}
printPath(k);
printf("%d\n",ans);
}
return 0;
}
本文作者:Joey-Wang
本文链接:https://www.cnblogs.com/joey-wang/p/14541194.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步