标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 645 Accepted Submission(s): 216
#include <iostream> #include <cstdio> #include <cstring> #include <queue> #include <algorithm> #include <math.h> using namespace std; typedef unsigned long long LL; const int N = 150005; struct Edge { LL u,v; LL w; } edge[N]; LL father[N]; LL cnt[N]; LL MAX,MIN; LL _find(LL x) { if(x!=father[x]){ father[x] = _find(father[x]); } return father[x]; } void init(int n) { for(int i=1; i<=n; i++) { father[i] = i; cnt[i] = 1; } } void Union(LL a,LL b,LL w,int flag) { LL x = _find(a); LL y = _find(b); if(flag) { MAX+=cnt[x]*cnt[y]*w; } else { MIN+=cnt[x]*cnt[y]*w; } father[x] = y; cnt[y]+=cnt[x]; } int cmp(Edge a,Edge b) { return a.w<b.w; } int main() { int n; int t = 1; while(scanf("%d",&n)!=EOF) { init(n); for(int i=1; i<n; i++) { scanf("%I64u%I64u%I64u",&edge[i].u,&edge[i].v,&edge[i].w); } MAX = 0,MIN = 0; sort(edge+1,edge+n,cmp); for(int i=1; i<n; i++) { Union(edge[i].u,edge[i].v,edge[i].w,1); } init(n); for(int i=n-1; i>=1; i--) { Union(edge[i].u,edge[i].v,edge[i].w,0); } printf("Case #%d: ",t++); printf("%I64u\n",MAX-MIN); } return 0; }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5685645.html