POJ 2031 Building a Space Station 最小生成树

题意:有n个太空舱,给出每个太空舱球心坐标与球的半径,若两太空舱相邻或重叠则表示两太空舱相接,宇航员可以从A走到B当且仅当A、B直接或间接相接或者建造一条走廊将A、B直接或间接连接在一起,求将所有太空舱连接在一起的最短走廊长度
思路:若两太空舱直接相接则将其并到一个集合里,最小生成树边加一,否则将其距离作为权值放到边集里,注意给的坐标是球心坐标,故距离为两球心坐标距离减去两球半径,之后根据没连接的点继续求最小生成树即可

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 10005;
int n, u[maxn];
struct node {
	double x, y, z, r;
	node(double x = 0, double y = 0, double z = 0, double r = 0) : x(x), y(y), z(z), r(r) {}
}a[maxn];
struct edge {
	int u, v;
	double w;
	edge(int u = 0, int v = 0, double w = 0) : u(u), v(v), w(w) {}
}b[maxn];
bool cmp(edge x, edge y)
{
	return x.w < y.w;
}
bool isConn(node x, node y)
{
	double nx = x.x - y.x;
	double ny = x.y - y.y;
	double nz = x.z - y.z;
 	double dis = sqrt(nx*nx + ny*ny + nz*nz);
 	if (dis <= x.r + y.r)
 		return true;
 	return false;
}
double getDis(node x, node y)
{
	double nx = x.x - y.x;
	double ny = x.y - y.y;
	double nz = x.z - y.z;
 	return sqrt(nx*nx + ny*ny + nz*nz)-x.r-y.r;
}
int ufind(int x)
{
	if (u[x] != x)
		u[x] = ufind(u[x]);
	return u[x];
}
void unite(int x, int y)
{
	u[ufind(x)] = ufind(y);
}
int main()
{
	while (cin >> n && n) {
		for (int i = 0; i < n; i++) {
			double x, y, z, r;
			cin >> x >> y >> z >> r;
			a[i] = node(x, y, z, r);
			u[i] = i;
		}
		double ans = 0;
		int cnt = 0, k = 0;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < i; j++) {
				if (isConn(a[i], a[j]) && ufind(i) != ufind(j)) {
					unite(i, j);
					k++;
				}
				else if (ufind(i) != ufind(j)) {
					double dis = getDis(a[i], a[j]);
					b[cnt++] = edge(i, j, dis);
				}
			}
		}
		sort(b, b+cnt, cmp);
		for (int i = 0; i < cnt; i++) {
			int x = b[i].u, y = b[i].v;
			if (ufind(x) != ufind(y)) {
				ans += b[i].w;
				unite(x, y);
				k++;
			}
			if (k == n-1)
				break;
		}
		printf("%.3f\n", ans);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值