标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 29762 Accepted Submission(s):
13297
#include<stdio.h> #include<algorithm> int set[110]; using namespace std; struct record { int beg; int end; int ju; //两村庄之间距离 }s[10000]; int find(int fa) //寻找根节点 { int ch=fa; int t; while(fa!=set[fa]) fa=set[fa]; while(ch!=fa) { t=set[ch]; set[ch]=fa; ch=t; } return fa; } void mix(int x,int y) //合并已有村庄 { int fx,fy; fx=find(x); fy=find(y); if(fx!=fy) set[fx]=fy; } bool cmp(record a,record b) { return a.ju<b.ju; //将两村庄之间距离从小到大排列 } int main() { int n,m,j,i,sum,l; while(scanf("%d",&n)&&n!=0) { for(j=1;j<=n;j++) { set[j]=j; } m=n*(n-1)/2; for(i=0;i<m;i++) { scanf("%d%d%d",&s[i].beg,&s[i].end,&s[i].ju); } sort(s,s+m,cmp); sum=0; for(i=0;i<m;i++) { if(find(s[i].beg)!=find(s[i].end)) //选择最短路径 { mix(s[i].beg,s[i].end); sum+=s[i].ju; } } printf("%d\n",sum); } return 0; }
标签:
原文地址:http://www.cnblogs.com/tonghao/p/4466942.html