http://swjtuoj.cn/problem/2387/
设dp[cur]表示以cur这个节点为起点的时候,能走的最大贡献。
题目保证没环,也就是没回路。
感觉和树dp差不多了。
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <algorithm> #include <assert.h> #define IOS ios::sync_with_stdio(false) using namespace std; #define inf (0x3f3f3f3f) typedef long long int LL; #include <iostream> #include <sstream> #include <vector> #include <set> #include <map> #include <queue> #include <string> #include <bitset> const int maxn = 2000 + 20; struct Node { int u, v, w; int tonext; }e[maxn * maxn]; int first[maxn], num; void add(int u, int v, int w) { ++num; e[num].u = u, e[num].v = v, e[num].w = w; e[num].tonext = first[u]; first[u] = num; } int vis[maxn], dp[maxn], DFN; int dfs(int cur) { if (vis[cur] == DFN) return dp[cur]; vis[cur] = DFN; int res = 0; for (int i = first[cur]; i; i = e[i].tonext) { int v = e[i].v; res = max(res, dfs(v) + e[i].w); } return dp[cur] = res; } void work() { memset(first, 0, sizeof first); int n, m; scanf("%d%d", &n, &m); for (int i = 1; i <= m; ++i) { int u, v, w; scanf("%d%d%d", &u, &v, &w); u++; v++; add(u, v, w); } ++DFN; int ans = 0; memset(dp, 0, sizeof dp); for (int i = 1; i <= n; ++i) { if (vis[i] == DFN) continue; dp[i] = dfs(i); } for (int i = 1; i <= n; ++i) ans = max(ans, dp[i]); printf("%d ", ans); } int main() { #ifdef local freopen("data.txt", "r", stdin); // freopen("data.txt", "w", stdout); #endif int t; scanf("%d", &t); while (t--) work(); return 0; }