标签:
1 #include <stdio.h> 2 #include <algorithm> 3 using namespace std; 4 int father[1010] ; 5 6 struct rode 7 { 8 int a, b ,c; 9 }; 10 rode num[10010]; 11 12 bool cmp(rode a, rode b) 13 { 14 return a.c < b.c ; 15 } 16 17 int find(int a) 18 { 19 while(a != father[a]) 20 a = father[a]; 21 return a; 22 } 23 24 void mercy(int a, int b) 25 { 26 int q = find(a); 27 int p = find(b); 28 if(q != p) 29 father[q] = p; 30 31 } 32 33 int main() 34 { 35 int i, n, m; 36 while(~scanf("%d %d", &n, &m)) 37 { 38 for(i=0; i<n; i++) 39 father[i] = i; 40 for(i=0; i<m; i++) 41 scanf("%d %d %d",&num[i].a, &num[i].b, &num[i].c); 42 sort(num, num+m, cmp); 43 int total = 0; 44 for(i=0; i<m; i++) 45 { 46 //mercy(num[i].a, num[i].b); 47 if(find(num[i].a) == find(num[i].b)) 48 continue; 49 else 50 { 51 //printf("1\n"); 52 total += num[i].c; 53 mercy(num[i].a, num[i].b) ; 54 } 55 } 56 int ac = 0; 57 for(i=0; i<n; i++) 58 { 59 if(father[i] == i) 60 ac++; 61 } 62 if(ac == 1) 63 printf("%d\n\n", total); 64 else 65 printf("impossible\n\n"); 66 } 67 }
标签:
原文地址:http://www.cnblogs.com/fengshun/p/4680450.html