标签:
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1382 Accepted Submission(s): 455
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<cmath> #include<cstdlib> #include<algorithm> #include<queue> #include<vector> #include<set> using namespace std; int n,fa[2000010],sum[2000010]; long long dist[2000010]; struct node { int x,y,w; }e[2000010]; int find(int x) { return x==fa[x]?x:fa[x]=find(fa[x]); } bool cmp(node a,node b) { return a.w>b.w; } void Union(int x,int y,int w) { int fx,fy; fx=find(x),fy=find(y); if(fx!=fy) { long long x1=(long long)(dist[fx]+(long long)sum[fy]*w); long long x2=(long long)(dist[fy]+(long long)sum[fx]*w); if(x1>x2) { fa[fy]=fx; sum[fx]+=sum[fy]; dist[fx]=x1; } else { fa[fx]=fy; sum[fy]+=sum[fx]; dist[fy]=x2; } } } int main() { while(scanf("%d",&n)!=EOF) { for(int i=1;i<=n;i++) fa[i]=i,sum[i]=1,dist[i]=0; for(int i=1;i<n;i++) scanf("%d%d%d",&e[i].x,&e[i].y,&e[i].w); sort(e+1,e+n,cmp); for(int i=1;i<n;i++) Union(e[i].x,e[i].y,e[i].w); cout<<dist[find(1)]<<endl; } return 0; }
标签:
原文地址:http://www.cnblogs.com/water-full/p/4534421.html