ZOJ 1914最小生成树
View Code
1 #include<stdio.h>//求出最小生成树之后,再求出第n-m大的值就行了 2 #include<stdlib.h> 3 #include<math.h> 4 #include<string.h> 5 #define N 501 6 #define Maxint 9999999 7 8 double c[N][N],x[N],y[N],dist[N]; 9 int s[N], closest[N],n; 10 11 int cmp(const void *a,const void *b) 12 { 13 return *(double *)a > *(double *)b ? 1 : -1; 14 } 15 16 void Prim(int v) 17 { 18 int i,j,k; 19 double min,lowcost[N]; 20 s[v] = 1; 21 for(i=1; i<n; i++) 22 { 23 lowcost[i] = c[v][i]; 24 closest[i] = v; 25 s[i] = 0; 26 } 27 for(i=1; i<n; i++) 28 { 29 min = Maxint; 30 j = 1; 31 for(k=1; k<n; k++) 32 { 33 if((lowcost[k]<min)&&(!s[k])) 34 { 35 min = lowcost[k]; 36 j = k; 37 } 38 } 39 s[j] = 1; 40 lowcost[j] = min; 41 dist[i-1] = min;//存放最小生成树的值,将每个最小的边都存起来 42 for(k = 0; k<n; k++) 43 { 44 if((c[j][k]<lowcost[k])&&(!s[k])) 45 { 46 lowcost[k] = c[j][k]; 47 closest[k] = j; 48 } 49 } 50 } 51 } 52 53 int main() 54 { 55 int i,j,m,ncases; 56 57 scanf("%d",&ncases); 58 while( ncases-- ) 59 { 60 scanf("%d%d",&m,&n); 61 for(i=0; i<n; i++) 62 { 63 scanf("%lf%lf",&x[i],&y[i]); 64 for(j=0; j<=i; j++) 65 { 66 c[i][j] = sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])); 67 c[j][i] = c[i][j]; 68 } 69 } 70 Prim(0); 71 qsort(dist,n-1,sizeof(dist[0]),cmp); 72 printf("%.2lf\n",dist[n-m-1]); 73 } 74 // system("pause"); 75 return 0; 76 }