POJ 2031 BUilding a Space Station 两点间距离 + 最小生成树

没有什么技术含量。

套模板就好了。

#include <cmath>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>

using namespace std;

struct P
{
    double x,y,z,r;
}p[110];

struct E
{
    int u,v;
    double w;
}edge[10010];

double cal(P p1,P p2)
{
    double w;
    w = sqrt( (p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y) + (p1.z-p2.z)*(p1.z-p2.z) );
    w -= (p1.r+p2.r);
    return w > 0 ? w : 0;
}

int fp[110];

bool cmp(E e1,E e2)
{
    return e1.w < e2.w;
}

int find(int x)
{
    int k,j,r;
    r = x;
    while(r != fp[r])
    {
        r = fp[r];
    }

    k = x;

    while(k != r)
    {
        j = fp[k];
        fp[k] = r;
        k = j;
    }
    return r;
}

bool merge(E e)
{
    int fu = find(e.u);
    int fv = find(e.v);

    if(fu == fv)
        return false;
    fp[fu] = fv;
    return true;
}

int main()
{
    int n;

    int i,j,top;

    double sumw;

    while(scanf("%d",&n) && n)
    {
        for(i = 1;i <= n; ++i)
        {
            scanf("%lf %lf %lf %lf",&p[i].x,&p[i].y,&p[i].z,&p[i].r);
        }
        for(i = 1,top = 0;i <= n; ++i)
        {
            for(j = i+1;j <= n; ++j)
            {
                edge[top].u = i;
                edge[top].v = j;
                edge[top++].w = cal(p[i],p[j]);
            }
        }

        sort(edge,edge+top,cmp);



        for(i = 1;i <= n; ++i)
            fp[i] = i;

        for(i = 0,sumw = 0;i < top ; ++i)
        {
            if(merge(edge[i]))
            {
                sumw += edge[i].w;
            }
        }

        printf("%.3f\n",sumw);

    }
    return 0;
}

你可能感兴趣的:(POJ 2031 BUilding a Space Station 两点间距离 + 最小生成树)