1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #include <iostream> #include <algorithm> #include <math.h> using namespace std; const int maxn = 1e4;
int n,m; struct edge { double x,y,z,r; edge(){} edge(double a,double b,double c,double d) { x = a; y = b; z = c; r = d; } } edges[maxn]; struct node { int from,to; double div; node () {} node (int u,int v,double w) { from = u; to = v; div = w; } bool operator<(const node& temp)const { return this->div < temp.div; } }e[maxn]; int pre[maxn];
int find(int x) { if (x == pre[x]) return x; else return pre[x] = find(pre[x]); } double Distance(edge& a,edge& b) { double dx = (a.x-b.x)*(a.x-b.x); double dy = (a.y-b.y)*(a.y-b.y); double dz = (a.z-b.z)*(a.z-b.z); return sqrt(dx+dy+dz); } int main() {
while (scanf("%d",&n) && n) { double x,y,z,r; for (int i=0; i<n; i++) { cin >> x >> y >> z >> r; edges[i] = edge(x,y,z,r); } int cnt = 0; for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { double dis = Distance(edges[i],edges[j]); if (dis <= edges[i].r + edges[j].r) { e[cnt++] = node(i,j,0); } else { e[cnt++] = node(i,j,dis - edges[i].r - edges[j].r); } } } for (int i=0; i<n; i++) pre[i] = i; sort(e,e+cnt); double ans = 0; for (int i=0; i<cnt; i++) { int a = e[i].from; int b = e[i].to; if (find(a) != find(b)) { ans += e[i].div; pre[find(a)] = find(b); } } printf("%.3lf\n",ans); } return 0; }
|