这种n^2的,还是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,z,r; }; double d(node a,node b) { double t=sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)+(a.z-b.z)*(a.z-b.z))-a.r-b.r; return t>0?t:0; } node place[101]; bool vis[101]; double dis[101]; int main() { int n; while(~scanf("%d",&n)&&n) { memset(vis,0,sizeof(vis)); memset(dis,127,sizeof(dis)); int i,j; for(i=0;i<n;i++) scanf("%lf%lf%lf%lf",&place[i].x,&place[i].y,&place[i].z,&place[i].r); 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("%.3f\n",ans); } }