poj 2031

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#define N 200
double co(double a,double b) {
	return  (a-b)*(a-b);
}
struct node {
	double x,y,z,r;
}a[N];
struct nodee{
	double len;
	int x,y;
}map[N*N];
int pre[N];
int find(int x) {
	if(x!=pre[x])
		pre[x]=find(pre[x]);
	return pre[x];
}
int cmp(const void *b,const void *c) {
	return (*(struct nodee *)b).len>(*(struct nodee *)c).len?1:-1;
}
int main() {
	double r,sum;
	int n,i,j,k,e,w;
	while(scanf("%d",&n),n) {
		for(i=1;i<=n;i++)
			pre[i]=i;
		for(i=1;i<=n;i++) 
			scanf("%lf%lf%lf%lf",&a[i].x,&a[i].y,&a[i].z,&a[i].r);
		k=0;
		for(i=1;i<n;i++) 
			for(j=i+1;j<=n;j++) {
				r=sqrt(co(a[i].x,a[j].x)+co(a[i].y,a[j].y)+co(a[i].z,a[j].z));
				map[k].x=i;
				map[k].y=j;
				if(r<=a[i].r+a[j].r) 
					map[k].len=0;
				else
					map[k].len=r-(a[i].r+a[j].r);
				k++;
			}
			qsort(map,k,sizeof(map[0]),cmp);
			j=1;sum=0;
			for(i=0;i<k&&j<n;i++) {
				e=find(map[i].x);
				w=find(map[i].y);
				if(e!=w) {
					pre[e]=w;
					j++;
					sum+=map[i].len;
				}
			}
			printf("%.3f
",sum);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/thefirstfeeling/p/4410822.html