曾经沧海难为水,除却巫山不是云。|

Joey-Wang

园龄:4年3个月粉丝:17关注:0

10.7 关键路径

10.7 关键路径

http://codeup.hustoj.com/contest.php?cid=100000627

A 关键路径

image-20200901020549631

题目解析

这道题用了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 中国大陆许可协议进行许可。

posted @   Joey-Wang  阅读(52)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
展开