Building a Space Station POJ - 2031 三维最小生成树,其实就是板子题
#include<iostream> #include<cmath> #include<algorithm> #include<cstdio> using namespace std; const int N=1e5; struct edge{ int a,b; double w; }e[N]; double x[N],y[N],z[N],r[N]; int n,tot,p[N]; bool cmp(edge a,edge b) { return a.w<b.w; } int find(int x) { if(p[x]!=x) p[x]=find(p[x]); return p[x]; } void kruskal() { double sum=0; for(int i=0;i<tot;i++) { int a=find(e[i].a); int b=find(e[i].b); double w=e[i].w; if(a!=b) { sum+=w; p[a]=b; } } printf("%.3f\n",sum); } int main() { while(cin>>n&&n) { for(int i=0;i<n;i++) cin>>x[i]>>y[i]>>z[i]>>r[i]; for(int i=0;i<=n;i++) p[i]=i; tot=0; for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) { double t=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])+(z[i]-z[j])*(z[i]-z[j])); if(r[i]+r[j]>=t) e[tot++]={i,j,0}; else e[tot++]={i,j,t-r[i]-r[j]}; } sort(e,e+tot,cmp); kruskal(); } return 0; }