并查集 HDU-4424
代码:
#include <iostream> #include <cstring> #include <iostream> #include <cstdio> #include <algorithm> using namespace std; #define maxn 200005 struct Node { int x; int y; long long val; Node(int a = 0, int b = 0, long long c = 0):x(a), y(b), val(c){} }; Node no[maxn]; bool cmp(const Node &A, const Node &B) { return A.val > B.val; } int fur[maxn]; int cnt[maxn]; long long sum[maxn]; int Find(int x) { if(fur[x] == x) return x; return fur[x] = Find(fur[x]); } int main() { int n; while(scanf("%d", &n) != EOF) { ///初始化数值 for(int i = 1; i <= n; i++) { cnt[i] = 1; sum[i] = 0; fur[i] = i; } /// for(int i = 1; i <= n - 1; i++) { scanf("%d%d%d", &no[i].x, &no[i].y, &no[i].val); } sort(no + 1, no + n, cmp); for(int i = 1; i <= n - 1; i++) { int fu = Find(no[i].x); int fv = Find(no[i].y); long long x1 = no[i].val * cnt[fv] + sum[fu]; long long x2 = no[i].val * cnt[fu] + sum[fv]; if(x1 > x2) { fur[fv] = fu; cnt[fu] += cnt[fv]; sum[fu] = x1; } else { fur[fu] = fv; cnt[fv] += cnt[fu]; sum[fv] = x2; } } cout << sum[Find(1)] << endl; } return 0; }
print “ 欢迎来到渣小狼的博客,这既是博客,也是日记,里面记录了小狼的学习经历还有一些小狼的见解,非常希望每一个来到这里的人能够留下只言片语,更加的希望留下的是对于小狼的不足的补充,谢谢(*^__^*) 嘻嘻……”