标签:
Description
Input
Output
Sample Input
3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100
Sample Output
3 ?
1 #include<cstdio> 2 #include<algorithm> 3 using namespace std; 4 int n,m,per[105]; 5 struct node{ 6 int a,b; 7 int dis; 8 }x[5005]; 9 bool cmp(node a,node b) 10 { 11 return a.dis<b.dis; 12 } 13 void init() 14 { 15 for(int i=1;i<=m;i++) 16 { 17 per[i]=i; 18 } 19 } 20 int find(int x) 21 { 22 if(x!=per[x]) 23 { 24 per[x]=find(per[x]); 25 } 26 return per[x]; 27 } 28 bool join(int a,int b) 29 { 30 int x=find(a),y=find(b); 31 if(x!=y) 32 { 33 per[y]=x; 34 return 1; 35 } 36 return 0; 37 } 38 int main() 39 { 40 int a,b,c; 41 while(scanf("%d %d",&n,&m),n) 42 { 43 init(); 44 for(int i = 0;i < n;i++) 45 { 46 scanf("%d %d %d",&a,&b,&c); 47 x[i].a=a; 48 x[i].b=b; 49 x[i].dis=c; 50 } 51 sort(x,x+n,cmp); 52 int sum = 0,cnt = 0; 53 for(int i = 0,j = 0;cnt < m-1,j<n;i++,j++) 54 { 55 if(join(x[i].a,x[i].b)) 56 { 57 sum+=x[i].dis; 58 cnt ++; 59 } 60 } 61 if(cnt!=m-1) 62 printf("?\n"); 63 else 64 printf("%d\n",sum); 65 } 66 return 0; 67 }
标签:
原文地址:http://www.cnblogs.com/llal/p/5734297.html