7_22_R题 Building a Space Station
题意
给出一些空间站的坐标和半径,求把所有空间站链接起来的最小距离
思路
最小生成树,计算出空间站两两之间的距离,如果距离小于两半径之和,则标记为已连接,生成图之后在跑一次最小生成树即可。
代码
#include <cmath>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxm = 1e6 + 10;
const int maxn = 1e5 + 10;
typedef long long ll;
struct Edges{
int u,v;
double w;
Edges(){};
Edges(int u,int v,double w):u(u),v(v),w(w){};
bool operator < (const Edges & b) const {
return w < b.w;
}
}edge[maxm];
int fa[maxn];
int Find(int x){
return fa[x] == x ? x :fa[x] = Find(fa[x]);
}
bool Union(int x ,int y){
x = Find(x);
y = Find(y);
if(x == y) return false;
fa[x] = y;
return true;
}
double lent = 0;
void init(int n){
for(int i = 0 ; i <= n ; i ++)
fa[i] = i;
lent = 0;
}
struct Point{
double x,y,z,r;
int idx;
Point(){};
Point(double x,double y,double z,double r):x(x),y(y),z(z),r(r){};
}Loc[110];
inline double dis(const Point & a, const Point & b){
return sqrt(pow(a.x-b.x,2.0) + pow(a.y-b.y,2.0) +pow(a.z-b.z,2.0));
}
int main (){
int T;
while (~scanf("%d", &T),T){
init(T);
int cnt = 0;
for(int i = 0 ; i < T ; i ++){
scanf("%lf %lf %lf %lf", &Loc[i].x,&Loc[i].y,&Loc[i].z,&Loc[i].r);
Loc[i].idx = i;
}
for(int i = 0 ; i < T ; i ++){
for(int k = 0 ; k < T ; k ++){
double len = dis(Loc[i],Loc[k]);
if(len > Loc[i].r + Loc[k].r){
edge[cnt++] = Edges(Loc[i].idx,Loc[k].idx,len - Loc[i].r - Loc[k].r);
}
else Union(Loc[i].idx,Loc[k].idx);
}
}
sort(edge,edge+cnt);
for(int i = 0 ; i < cnt ; i ++){
Edges & e = edge[i];
if(Union(e.u,e.v)) {
lent += e.w;
}
}
printf("%.3f\n", lent);
}
}