题目意思很简单计算出所修电线的最小值,很明显Kruskal算法比Prim算法要简单。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<math.h> 4 #include<string.h> 5 #define N 505 6 7 int father[N],n,row,dis_sum; 8 typedef struct 9 { 10 int x,y; 11 int w; 12 }edge; 13 edge e[N*N/2]; 14 int cmp(const void *a,const void *b) 15 { 16 return (*(edge *)a).w > (*(edge *)b).w ? 1 : -1; 17 } 18 19 void Make_set(int x) 20 { 21 father[x] = x; 22 } 23 24 int Find_set(int x) 25 { 26 if(x != father[x]) 27 father[x] = Find_set(father[x]); 28 return father[x]; 29 } 30 31 void Kruskal(int m) 32 { 33 int i, a, b; 34 for(i=0; i<n; i++) 35 Make_set(i); 36 qsort(e,m,sizeof(edge),cmp); 37 dis_sum = 0; 38 for(i=0; i<m; i++) 39 { 40 a = Find_set(e[i].x); 41 b = Find_set(e[i].y); 42 if(a != b) 43 { 44 dis_sum += e[i].w; 45 father[a] = b; 46 } 47 } 48 } 49 50 int main() 51 { 52 int i,tcases,a,b,k; 53 54 scanf("%d",&tcases); 55 while( tcases-- ) 56 { 57 scanf("%d%d",&n,&row); 58 for(i=0; i<row; i++) 59 { 60 scanf("%d%d%d",&a,&b,&k); 61 e[i].x = a; 62 e[i].y = b; 63 e[i].w = k; 64 } 65 Kruskal(row); 66 printf("%d\n",dis_sum); 67 } 68 //system("pause"); 69 return 0; 70 }