题意
传送门 POJ 2031
题解
设圆 i , j i,j i,j 的圆心距离为 d i j d_{ij} dij,若 d i j ≤ r i + r j d_{ij}\leq r_i+r_j dij≤ri+rj,则圆 i , j i,j i,j 相交或包含,预先用并查集处理,将连通分量看做一个点;对于权值 ( d i j − r i − r j ) (d_{ij}-r_i-r_j) (dij−ri−rj) 为正的边, K r u s k a l Kruskal Kruskal 求最小生成树即可。
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;
#define maxn 105
int n, e, par[maxn], rnk[maxn];
double x[maxn], y[maxn], z[maxn], r[maxn];
void init(int n)
{
for (int i = 0; i < n; i++)
{
par[i] = i, rnk[i] = 0;
}
}
int find(int x)
{
return par[x] == x ? x : (par[x] = find(par[x]));
}
bool same(int x, int y)
{
return find(x) == find(y);
}
void unite(int x, int y)
{
x = find(x), y = find(y);
if (x == y) return;
if (rnk[x] > rnk[y]) par[y] = x;
else
{
par[x] = y;
if (rnk[x] == rnk[y]) ++rnk[y];
}
}
struct edge
{
int u, v;
double cost;
bool operator<(const edge &e2) const
{
return cost < e2.cost;
}
} es[maxn * maxn];
double kruskal()
{
sort(es, es + e);
double res = 0.0;
for (int i = 0; i < e; i++)
{
edge &eg = es[i];
if (!same(eg.u, eg.v))
{
unite(eg.u, eg.v);
res += eg.cost;
}
}
return res;
}
double dis(int i, int j)
{
double dx = x[i] - x[j], dy = y[i] - y[j], dz = z[i] - z[j];
return sqrt(dx * dx + dy * dy + dz * dz);
}
int main()
{
while (~scanf("%d", &n) && n)
{
init(n);
e = 0;
for (int i = 0; i < n; i++)
{
scanf("%lf%lf%lf%lf", x + i, y + i, z + i, r + i);
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
double d = dis(i, j) - r[i] - r[j];
if (d <= 0)
{
unite(i, j);
}
else
{
es[e].u = i, es[e].v = j, es[e].cost = d;
++e;
}
}
}
printf("%.3f\n", kruskal());
}
}