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