zoj2048//POJ 1751 最小生成树Prim算法实现

View Code
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 #define N 760
 5 #define Maxint 99999999
 6 
 7 double lowcost[N], c[N][N];
 8 double x[N], y[N];
 9 int towns, m, s[N], closest[N],path[N][N];
10 
11 double distance(int i,int  j)//用double为了防止int数据存不下
12 {
13    return (x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]);     
14 }
15 
16 void Prim()
17 {
18      int i,j,k;
19      double min;
20      for(i=2; i<=towns; i++)
21      {
22        lowcost[i] = c[1][i];
23        closest[i] = 1;
24      }
25      for(i=1; i<towns; i++)
26      {  
27          min = Maxint;
28          j = 1;
29          for(k=2; k<=towns; k++)
30          {
31             if((lowcost[k]<min) && (!s[k]))
32             {
33                min = lowcost[k];
34                j = k;
35             }  
36          } 
37          s[j] = 1; 
38          lowcost[j] = min;//这个一开始忘了加WA了几次,将lowcost最小值更新为已求出的min
39          for(k=2; k<=towns; k++)
40          {
41             if((c[j][k] < lowcost[k]) && (!s[k]))       
42             {     
43                lowcost[k] = c[j][k];     
44                closest[k] = j;   
45             }     
46          }        
47       }          
48 }                  
49                        
50 int main()
51 {
52     int i, j, a, b, k,ncases;
53     
54    scanf("%d",&ncases);
55    while( ncases-- )
56    { 
57     scanf("%d",&towns);
58     for(i=1; i<=towns; i++)
59     {
60        scanf("%lf%lf",&x[i],&y[i]);
61     } 
62     memset(s,0,sizeof(s));
63     for(i=1; i<=towns; i++)
64      for(j=1; j<=towns; j++)
65      {
66        c[i][j] =  distance(i,j);//求出任意两点间的距离
67      }
68     
69     scanf("%d",&m);
70     for(i=1; i<=m; i++)     
71     {
72        scanf("%d%d",&a,&b);   
73        c[a][b] = c[b][a] = 0;//设置成0为了下面查找时方便排除
74     } 
75     Prim();
76     for(i=1; i<=towns; i++)
77     {
78        if( c[i][closest[i]] )       
79          printf("%d %d\n",i,closest[i]);     
80     }
81     if(ncases) printf("\n"); 
82    }      
83    // system("pause");        
84     return 0;         
85 }             
86 
87     

你可能感兴趣的:(最小生成树)