您的位置:首页 > 产品设计 > UI/UE

【POJ 2031】 Building a Space Station (三维坐标求距离+最小生成树)

2015-08-24 17:47 471 查看
【POJ 2031】 Building a Space Station

n个空间球 可能存在包含或者覆盖的状况 想要让所有球都联通 每个球有坐标x,y,z和半径 问还需要搭建最少多长的路

存储所有需要搭建的路 跑一遍最小生成树即可 注意原本就重叠的球距离0直接加入

代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define esp 1e-5

using namespace std;

typedef struct Point//三维坐标
{
    double x,y,z,r;
}Point;

typedef struct Edge//边
{
    int u,v;
    double w;
    bool operator <(const struct Edge a)const
    {
        return w - a.w < -esp;
    }
}Edge;

Point pt[100];//点
int pre[100];//Kruskal并查集
Edge eg[10000];
int tp;

void Init(int x)//初始化并查集
{
    for(int i = 0; i < x; ++i) pre[i] = i;
}

int Find(int x)
{
    return pre[x] == x? pre[x]: (pre[x] = Find(pre[x]));
}

int main()
{
    int n,i,j,k,r,cnt;
    double dis,sum;
    while(~scanf("%d",&n) && n)
    {
        Init(n);
        cnt = tp = 0;
        for(i = 0; i < n; ++i)
        {
            scanf("%lf %lf %lf %lf",&pt[i].x,&pt[i].y,&pt[i].z,&pt[i].r);
            for(j = 0; j < i; ++j)
            {
                dis = sqrt((pt[i].x-pt[j].x)*(pt[i].x-pt[j].x)+(pt[i].y-pt[j].y)*(pt[i].y-pt[j].y)+(pt[i].z-pt[j].z)*(pt[i].z-pt[j].z));//两点距离
                if(dis - pt[i].r - pt[j].r  > esp)//如果距离减两半径为正 则需要加边
                {
                    eg[tp].u = i;
                    eg[tp].v = j;
                    eg[tp++].w = dis - pt[i].r - pt[j].r;
                }
                else//否则距离零 直接加入一个集合
                {
                    k = Find(i);
                    r = Find(j);
                    if(k != r)
                    {
                        pre[k] = r;
                        cnt++;
                    }
                }
            }
        }
        sort(eg,eg+tp);

        sum = 0;
        for(i = 0; i < tp; ++i)//Kruskal
        {
            k = Find(eg[i].u);
            r = Find(eg[i].v);

            if(k != r)
            {
                pre[k] = r;
                sum += eg[i].w;
                cnt++;
            }

            if(cnt == n-1) break;
        }
        printf("%.3f\n",sum);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: