标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 34391 Accepted Submission(s): 15542
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 using namespace std; 5 #define Max 100000 6 int par[Max]; 7 int n; 8 struct edge 9 { 10 int v,u,cost; 11 }es[10000]; 12 void init() 13 { 14 for(int i=0;i<Max;i++) 15 par[i]=i; //每个节点的根节点都是自己本身 16 } 17 int find(int x) 18 { 19 if(par[x]==x) 20 return x; 21 else 22 return par[x]=find(par[x]); //找父节点 23 } 24 void unite(int x,int y) 25 { 26 int x0=find(x); 27 int y0=find(y); 28 if(x0==y0) 29 return; 30 else 31 par[x0]=y0; 32 } 33 bool same(int x,int y) 34 { 35 return find(x)==find(y); 36 } 37 bool cmp(edge a,edge b) 38 { 39 return a.cost<=b.cost; 40 } 41 int main() 42 { 43 int i,j; 44 freopen("in.txt","r",stdin); 45 while(scanf("%d",&n)&&n) 46 { 47 init(); 48 int sum=0; 49 for(i=0;i<n*(n-1)/2;i++) 50 scanf("%d%d%d",&es[i].v,&es[i].u,&es[i].cost); 51 sort(es,es+n*(n-1)/2,cmp); 52 for(i=0;i<n*(n-1)/2;i++) 53 { 54 edge e=es[i]; 55 if(!same(e.v,e.u)) 56 { 57 sum+=e.cost; 58 unite(e.v,e.u); 59 } 60 } 61 printf("%d\n",sum); 62 } 63 64 }
标签:
原文地址:http://www.cnblogs.com/a1225234/p/5041160.html