C - Building a Space Station POJ - 2031
题意:
要你建空间站的最小生成树;
- 当两个星球相交或者相切时,他们的距离为0,即不用建站。
- 否则,两个星球的距离 = 等于球心(三维里的距离)-r1-r2
思路:
- 建边
- 之后跑生成树
反思:
- G++ 中不支持%lf(提交要用%f)
AC(prim)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define For(i,x,y) for(register int i=(x); i<=(y); i++)
#define mst(x,a) memset(x,a,sizeof(x))
#define fzhead EDGE(int _from, int _to, double _val, int _next)
#define fzbody from(_from), to(_to), val(_val), next(_next)
using namespace std;
const int maxn=1e2+10;
const int maxm=1e4+10;
const int INF=0x3f3f3f3f;
typedef pair<double,int>pa;
struct point
{
double x,y,z,r;
} p[maxn];
struct EDGE
{
int from,to,next;
double val;
EDGE(){}
fzhead:fzbody{}
} e[maxm];
double dis[maxn],sum;
int cnt,head[maxn],vis[maxn];
int n,m;
void add(int bg, int to, double val)
{
e[++cnt]=EDGE(bg,to,val,head[bg]);
head[bg]=cnt;
}
void prim(int s)
{
For(i,1,n)
{
dis[i]=INF;
vis[i]=0;
}
dis[s]=0;
priority_queue<pa>q;
q.push(mp(0,1));
int time=0;
while(!q.empty()&&time<n)
{
double d=q.top().fi;
int u=q.top().se;
q.pop();
if(vis[u])continue;
time++;
//cout<<d<<endl;
sum+=(-d);
vis[u]=1;
for(int i=head[u]; i!=-1; i=e[i].next)
{
if(e[i].val<dis[e[i].to])
dis[e[i].to]=e[i].val,q.push(mp(-dis[e[i].to],e[i].to));
}
}
}
double get_dis(point a, point b)
{
double dis=(a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)+(a.z-b.z)*(a.z-b.z);
return sqrt(dis);
}
int main()
{
while(~scanf("%d", &n)&&n)
{
mst(e,0);mst(head,-1);mst(p,0);//mst(vis,0);
cnt=0;
sum=0;
double dis1=0;
For(i,1,n)scanf("%lf%lf%lf%lf", &p[i].x,&p[i].y, &p[i].z,&p[i].r);
For(i,1,n)
{
For(j,1,n)
{
if(i==j)continue;
dis1=get_dis(p[i],p[j]);
//cout<<dis1<<endl;
if(dis1<=(p[i].r+p[j].r))add(i,j,0);//add(j,i,0);}
else add(i,j,dis1-p[i].r-p[j].r);//;add(j,i,dis1);}
}
}
prim(1);
printf("%.3f\n",sum);
}
return 0;
}