畅通工程
http://acm.hdu.edu.cn/showproblem.php?pid=1863
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<cstring> 2 #include<iostream> 3 #include<cstdio> 4 #include<algorithm> 5 using namespace std; 6 struct road 7 { 8 int x,y,l; 9 }ht[10010]; 10 int set[105]; 11 int find(int x) 12 { 13 if(set[x]!=x) 14 set[x]=find(set[x]); 15 return set[x]; 16 } 17 int merge(int x,int y) 18 { 19 x=find(x); 20 y=find(y); 21 if(x==y) 22 return 0; 23 set[x]=y; 24 return 1; 25 } 26 int cmp(road a,road b) 27 { 28 return a.l<b.l; 29 } 30 int main() 31 { 32 int m,n,i,num,k; 33 while(~scanf("%d%d",&m,&n)) 34 { 35 if(m==0) 36 break; 37 for(i=1;i<=n;i++) 38 set[i]=i; 39 for(i=0;i<m;i++) 40 { 41 scanf("%d%d%d",&ht[i].x,&ht[i].y,&ht[i].l); 42 } 43 if(m<n-1) 44 { 45 printf("?\n"); 46 continue; 47 } 48 sort(ht,ht+m,cmp); 49 num=0; 50 k=1; 51 i=0; 52 while(k<n) 53 { 54 if(i>=m) 55 break; 56 if(merge(ht[i].x,ht[i].y)) 57 { 58 num+=ht[i].l; 59 k++; 60 } 61 i++; 62 } 63 if(k<n) 64 printf("?\n"); 65 else 66 printf("%d\n", num) ; 67 } 68 return 0; 69 }