思路:并查集板子。
#include<cmath> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define MAXN 1001 using namespace std; int n,m; int fa[MAXN]; long double ans; struct nond{ long double x,y,z,r; }v[MAXN]; struct none{ int x,y;long double z; }edge[10010]; int cmp(none a,none b){ return a.z<b.z; } int find(int x){ if(fa[x]==x) return x; else return fa[x]=find(fa[x]); } int main(){ while(scanf("%d",&n)&&n){ for(int i=1;i<=n;i++) cin>>v[i].x>>v[i].y>>v[i].z>>v[i].r; for(int i=1;i<=n;i++){ for(int j=i+1;j<=n;j++){ long double tmp=sqrt((v[i].x-v[j].x)*(v[i].x-v[j].x)+(v[i].y-v[j].y)*(v[i].y-v[j].y)+(v[i].z-v[j].z)*(v[i].z-v[j].z)); tmp-=v[i].r;tmp-=v[j].r; if(tmp<=0){ edge[++m].x=i;edge[m].y=j;edge[m].z=0.0; } else { edge[++m].x=i;edge[m].y=j;edge[m].z=tmp; } } } for(int i=1;i<=n;i++) fa[i]=i; sort(edge+1,edge+1+m,cmp); for(int i=1;i<=m;i++){ int dx=find(edge[i].x); int dy=find(edge[i].y); if(dx==dy) continue; fa[dy]=dx; ans+=edge[i].z; } double bns=double(ans); printf("%.3lf\n",bns);ans=0;m=0; } }