标签:
3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0
3 5
1 #include<cstdio> 2 #include<algorithm> 3 using namespace std; 4 int fa[100000]; 5 struct stu 6 { 7 int from,to; 8 int al; 9 }st[100000]; 10 int find(int a) 11 { 12 int r=a; 13 while(r != fa[r]) 14 { 15 r=fa[r]; 16 } 17 return r; 18 } 19 bool cmp(stu a,stu b) 20 { 21 return a.al<b.al; 22 } 23 int main() 24 { 25 int n,m,i; 26 while(scanf("%d",&n) && n) 27 { 28 m=n*(n-1)/2; 29 30 for(i = 1 ; i <= n ;i++) 31 { 32 fa[i]=i; 33 } 34 for(i = 0 ; i < m ; i++) 35 { 36 scanf("%d %d %d",&st[i].from,&st[i].to,&st[i].al); 37 } 38 sort(st,st+m,cmp); 39 int k=0; 40 int sum=0; 41 for(i = 0 ; i<m ;i++) 42 { 43 if(k == n-1) break; 44 if(find(st[i].from) != find(st[i].to)) 45 { 46 fa[find(st[i].from)]=find(st[i].to); //根节点相连 47 sum+=st[i].al; 48 ++k; 49 } 50 } 51 printf("%d\n",sum); 52 } 53 }
Huge input, scanf is recommended.
标签:
原文地址:http://www.cnblogs.com/yexiaozi/p/5733644.html