题目链接:http://acm.hrbeu.edu.cn/index.php?act=problem&id=1223
1 #include <cstdio> 2 #include <cmath> 3 #include <algorithm> 4 #include <iostream> 5 #include <cstring> 6 #include <queue> 7 #include <vector> 8 9 #define maxn 115 10 using namespace std; 11 12 const int INF = 0x3f3f3f; 13 14 struct Point{ 15 double x,y; 16 bool operator < (const Point & rh) const{ 17 return y < rh.y || (y == rh.y && x < rh.x); 18 } 19 }p[maxn]; 20 int n; 21 double ans; 22 double G[maxn][maxn]; 23 24 double calculate(int i,int j){ 25 double xx = p[j].x - p[i].x; 26 double yy = p[j].y - p[i].y; 27 return sqrt(xx*xx + yy*yy); 28 } 29 30 void prim(){ 31 bool vis[maxn]; 32 double lowdist[maxn]; 33 double mindist; 34 memset(vis,0,sizeof(vis)); 35 for(int i=1;i<=n;i++) lowdist[i]=INF; 36 int point; 37 int s=1; 38 vis[s] =true; 39 int num=1; 40 while(true){ 41 if(num == n) break; 42 vis[s]=true; 43 mindist = INF; 44 for(int i=1;i<=n;i++){ 45 if(!vis[i] && lowdist[i] > G[s][i]){ 46 lowdist[i] = G[s][i]; 47 } 48 if(!vis[i] && mindist > lowdist[i]){ 49 mindist=lowdist[i]; 50 point = i; 51 } 52 } 53 s = point; 54 ans += mindist; 55 num++; 56 } 57 return; 58 } 59 int main() 60 { 61 // if(freopen("input.txt","r",stdin)== NULL) {printf("Error "); exit(0);} 62 63 while(scanf("%d",&n)==1 && n){ 64 for(int i=1;i<=n;i++){ 65 scanf("%lf%lf",&p[i].x,&p[i].y); 66 } 67 for(int i=1;i<=n;i++) 68 for(int j=i+1;j<=n;j++){ 69 G[i][j] = G[j][i] = calculate(i,j); 70 } 71 ans = 0; 72 //print(); 73 prim(); 74 printf("%.2lf ",ans); 75 } 76 }