(最小生成树)POJ2031Building a Space Station

POJ2031Building a Space Station

题意&思路:

给你n个球的球心坐标(x,y,z)和半径r,如果两个球相交则视为连通。问使所有球两两连通(表面接触)的最短道路。
模板题。注意点就是两两连通就是两个球的距离设为0,以及提交时用C++才能交%lf。

代码:

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
#include<ctype.h>
#include<queue>
#include<set>
#include<stack>
#include<cmath>
#include<map>
#define pii pair<int,int>
#define ll long long
#define cl(x) memset(x,0,sizeof(x))
const int N=1e6+10;
const int mod=1e7+9;
const int maxn=0x3f3f3f3f;
const int minn=0xc0c0c0c0;
const int inf=99999999;
using namespace std;
struct space
{
	double x,y,z,r;
}a[110];
struct edge
{
	int u,v;
	double w;
}b[10010];
int fa[110],len;
int cmp(edge x,edge y)
{
	return x.w<y.w;
}
double dis(space t1,space t2)
{
	double d=sqrt((t1.x-t2.x)*(t1.x-t2.x)+(t1.y-t2.y)*(t1.y-t2.y)+(t1.z-t2.z)*(t1.z-t2.z))-t1.r-t2.r;
	if(d<0)
		d=0;
	return d;
}
int find(int x)
{
	if(fa[x]!=x)
		fa[x]=find(fa[x]);
	return fa[x];
}
int judge(int x,int y)
{
	int t1=find(x),t2=find(y);
	if(t1!=t2)
	{
		fa[t1]=t2;
		return 1;
	}
	return 0;
}
int main()
{
	int n;
	while(~scanf("%d",&n) && n)
	{
		int i,j;
		len=0;
		for(i=1;i<=n;i++)
			fa[i]=i;
		for(i=1;i<=n;i++)
			scanf("%lf%lf%lf%lf",&a[i].x,&a[i].y,&a[i].z,&a[i].r);
		for(i=1;i<=n;i++)
			for(j=i+1;j<=n;j++)
			{
				b[++len].w=dis(a[i],a[j]);
				b[len].u=i;
				b[len].v=j;
			}
		sort(b+1,b+len+1,cmp);	
		double ans=0;
		int count=0;
		for(i=1;i<=len;i++)
		{
			if(judge(b[i].u,b[i].v))
			{
				count++;
				ans+=b[i].w;
			}
			if(count==n-1)
				break;
		}
		printf("%.3lf\n",ans);
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值