ZOJ 1203Kruskal也许用Prim算法跟简单一些吧,下次用Prim算法试试
PE了几次,还好及时地发现,最后一句话没好好理解,原来空行还可以这么弄
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<math.h> 4 #include<string.h> 5 #define N 101 6 7 int father[N], citys; 8 double x[N], y[N], dis_sum; 9 typedef struct 10 { 11 int x,y; 12 double w; 13 }edge; 14 edge e[N*N+1]; 15 16 int cmp(const void *a,const void *b) 17 { 18 return (*(edge *)a).w > (*(edge *)b).w ? 1 : -1; 19 } 20 21 double distance(int i, int j) 22 { 23 return sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])); 24 } 25 26 void Make_set(int x) 27 { 28 father[x] = x; 29 } 30 31 int Find_set(int x) 32 { 33 if(x != father[x]) 34 father[x] = Find_set(father[x]); 35 return father[x]; 36 } 37 38 void Kruskal(int m) 39 { 40 int i, a, b; 41 for(i=1; i<=citys; i++) 42 Make_set(i); 43 qsort(e,m,sizeof(edge),cmp); 44 dis_sum = 0.0; 45 for(i=1; i<=m; i++) 46 { 47 a = Find_set(e[i].x); 48 b = Find_set(e[i].y); 49 if(a != b) 50 { 51 dis_sum += e[i].w; 52 father[b] = a; 53 } 54 } 55 } 56 57 int main() 58 { 59 int cases=1,i,j,k,flag=1; 60 61 while( scanf("%d",&citys) && citys) 62 { 63 for(i=1; i<=citys; i++) 64 { 65 scanf("%lf%lf",&x[i],&y[i]); 66 } 67 k = 1; 68 for(i=1; i<=citys; i++) 69 for(j=1; j<=citys; j++) 70 { 71 e[k].x = i; 72 e[k].y = j; 73 e[k].w = distance(i,j); 74 k++; 75 } 76 if(flag==1) flag=0;//最后加上对空行的处理原文的最后一句话 77 else printf("\n"); 78 Kruskal(k-1); 79 printf("Case #%d:\n",cases++); 80 printf("The minimal distance is: %.2lf\n",dis_sum); 81 82 } 83 return 0; 84 } 85 86