很简单的MST,用prim写的,把初始化和维护写在了一起。
/* author:jxy lang:C/C++ university:China,Xidian University **If you need to reprint,please indicate the source** */ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #define INF 1E9 using namespace std; struct node { double x,y; }; double d(node a,node b) { return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); } node place[101]; bool vis[101]; double dis[101]; int main() { int n,C=0; while(~scanf("%d",&n)&&n) { if(C)puts(""); C++; memset(vis,0,sizeof(vis)); memset(dis,127,sizeof(dis)); int i,j; for(i=0;i<n;i++) scanf("%lf%lf",&place[i].x,&place[i].y); double ans=0,Min,t; int now=0; for(i=0;i<n;i++) { Min=INF; for(j=0;j<n;j++) { if(dis[j]>=Min||vis[j])continue; Min=dis[j];now=j; } vis[now]=1; if(now)ans+=Min; for(j=0;j<n;j++) { if(vis[j])continue; dis[j]=min(dis[j],d(place[now],place[j])); } } printf("Case #%d:\nThe minimal distance is: %.2f\n",C,ans); } }