poj 2031 Building a Space Station(最小生成树)
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
struct d
{
int u,v;
double w;
} e[10000+5];
bool cmp(d a,d b)
{
return a.w<b.w;
}
int bin[100+5];
double x[100+5],y[100+5],z[100+5],r[100+5];
int Find(int x)
{
int s;
for(s=x; bin[s]>=0; s=bin[s]);
while(s!=x)
{
int t=bin[x];
bin[x]=s;
x=t;
}
return s;
}
void Union(int x1,int x2)
{
int f1=Find(x1),f2=Find(x2);
int t=bin[f1]+bin[f2];
if(bin[f1]>bin[f2])
{
bin[f1]=f2;
bin[f2]=t;
}
else
{
bin[f2]=f1;
bin[f1]=t;
}
}
int main()
{
int n,m,i,j,u,v;
double ans;
while(~scanf("%d",&n)&&n)
{
for(i=0; i<n; i++)
bin[i]=-1;
for(i=0; i<n; i++)
scanf("%lf%lf%lf%lf",&x[i],&y[i],&z[i],&r[i]);
for(i=0,m=0; i<n; i++)
for(j=i+1; j<n; j++)
{
double t=(x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])+(z[i]-z[j])*(z[i]-z[j]);
t=sqrt(t);
if(t<=r[i]+r[j])
{
if(Find(i)!=Find(j)) Union(i,j);
}
else
{
e[m].u=i;
e[m].v=j;
e[m].w=t-r[i]-r[j];
m++;
}
}
sort(e,e+m,cmp);
for(ans=0,i=0; i<m; i++)
{
u=e[i].u;
v=e[i].v;
if(Find(u)!=Find(v))
{
ans+=e[i].w;
Union(u,v);
}
}
printf("%.3f\n",ans);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/