周末牛客挂了个更难的,这个简单一些
#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> #include<vector> #define maxn 200100 using namespace std; typedef long long ll; struct Node { int p; int len; Node(int a, int b) :p(a), len(b) {} }; vector<Node>G[maxn]; void insert(int be, int en, int len) { G[be].push_back(Node(en, len)); } int t; ll list[maxn]; int de[maxn]; int dfs(int x, int fa) { for (int i = 0; i < G[x].size(); i++) { int p = G[x][i].p; ll ln = G[x][i].len; if (p == fa) continue; dfs(p, x); if (de[p] == 1) list[x] += ln; else list[x] += min(ln, list[p]); } return 0; } ll f[maxn]; int dfs1(int x, int fa) { for (int i = 0; i < G[x].size(); i++) { int p = G[x][i].p; ll ln = G[x][i].len; if (p == fa) continue; if (de[x] == 1) f[p] = list[p] + ln; else f[p] = list[p] + min(ln, f[x] - min(ln, list[p])); dfs1(p, x); } return 0; } int main() { int n; scanf("%d", &t); while (t--) { int be, en; scanf("%d", &n); memset(list, 0, sizeof(list)); memset(de, 0, sizeof(de)); memset(f, 0, sizeof(f)); for (int i = 0; i <= n; i++) G[i].clear(); int len; for (int i = 1; i < n; i++) { scanf("%d %d %d", &be, &en, &len); insert(be, en, len); insert(en, be, len); de[be]++; de[en]++; } dfs(2, -1); f[2] = list[2]; dfs1(2, -1); ll ans = 0; for (int i = 1; i <= n; i++) { ans = max(ans, f[i]); } printf("%d ", ans); } return 0; }