计算各球心的距离,小于半径之和的算0,简单的几何计算+kruskal
注意double的快排调用时 wa了n次
#include<stdio.h>
#include<stdlib.h>
#include <cmath>
#include <iostream>
#include <cstdlib>
using namespace std;
int parent[10000];
int k;
struct edge
{
int u,v;
double w;
} edges[10000];
struct ball
{
double x,y,z,r;
} balls[101];
int compare(const void *a, const void *b)
{
return (*(edge *)a).w > (*(edge *)b).w ? 1 : -1;
}
int findset(int x)
{
int tmp,s;
s=x;
while (parent[s]>=0) s=parent[s];
while (s!=x)
{
tmp=parent[x];
parent[x]=s;
x=tmp;
}
return s;
}
void unionset(int r1,int r2)
{
int rr1,rr2;
rr1=findset(r1);
rr2=findset(r2);
int tmp=parent[rr1]+parent[rr2];
if (rr1==rr2) return;
if (parent[rr1]>parent[rr2]) {
parent[rr1]=rr2;
parent[rr2]=tmp;
}
else {
parent[rr2]=rr1;
parent[rr1]=tmp;
}
}
int main()
{
int a,b,n,m;
scanf("%d",&n);
while (n!=0)
{
for (int i=0;i<=n;i++) parent[i]=-1;
m=0;
for (int i=0;i<n;i++)
{
scanf("%lf%lf%lf%lf",&balls[i].x,&balls[i].y,&balls[i].z,&balls[i].r);
}
double t=0;
for (int i=0;i<n-1;i++)
for (int k=i+1;k<n;k++)
{
t=sqrt((balls[i].y-balls[k].y)*(balls[i].y-balls[k].y)+(balls[i].z-balls[k].z)*(balls[i].z-balls[k].z)+(balls[i].x-balls[k].x)*(balls[i].x-balls[k].x))-balls[k].r-balls[i].r;
edges[m].u=i; edges[m].v=k;
if (t<0.000001) edges[m].w=0; else edges[m].w=t;
m++;
}
qsort(edges,m,sizeof(edges[0]),compare);
int num=0;
double ans=0;
for (int i=0;i<m;i++)
{
if (findset(edges[i].u)!=findset(edges[i].v))
{
num++;
ans=ans+edges[i].w;
unionset(edges[i].u,edges[i].v);
}
if (num>=n-1) break;
}
printf("%0.3lf\n",ans);
scanf("%d",&n);
}
}