玲珑学院OJ 1000 - Spoon Devil's 3-D Matrix(3维最小生成树)

题目链接:http://www.ifrog.cc/acm/problem/1000
1000 - Spoon Devil’s 3-D Matrix
Time Limit:1s Memory Limit:32MByte

Submissions:151Solved:53

DESCRIPTION
Spoon Devil build a 3-D matrix, and he(or she) wants to know if he builds some bases what’s the shortest distance to connect all of them.

INPUT
There are multiple test cases. The first line of input contains an integer
T
T, indicating the number of test cases. For each test case:
The first line contains one integer
n

(
0
<
n
<
50
)
n (0

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;

int pre[55];
struct node
{
    double x,y,z;
} p[55];

struct edge
{
    int u,v;
    double cost;
} e[2505];

int fin(int x)
{
    if(x==pre[x])
    {
        return x;
    }
    else
    {
        return pre[x]=fin(pre[x]);
    }
}

void join(int x,int y)
{
    int t1=fin(x);
    int t2=fin(y);
    if(t1!=t2)
    {
        pre[t1]=t2;
    }
}

double dist(node a,node b)
{
    return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)+(a.z-b.z)*(a.z-b.z));
}

bool cmp(edge a,edge b)
{
    return a.cost<b.cost;
}

int main()
{
    int n,t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        for(int i=0; i<n; i++)
        {
            scanf("%lf%lf%lf",&p[i].x,&p[i].y,&p[i].z);
        }
        if(n==1)
        {
            printf("0.00\n");
            continue;
        }
        for(int i=0;i<n;i++)
        {
            pre[i]=i;
        }
        int s=0;
        for(int i=0; i<n; i++)
        {
            for(int j=i+1; j<n; j++)
            {
                e[s].u=i;
                e[s].v=j;
                e[s++].cost=dist(p[i],p[j]);
            }
        }
        sort(e,e+s,cmp);
        double sum=0;
        int ss=0;
        for(int i=0;i<s;i++)
        {
            if(fin(e[i].u)!=fin(e[i].v))
            {
                join(e[i].u,e[i].v);
                sum+=e[i].cost;
                ss++;
            }
            if(ss==n-1)
            {
                break;
            }
        }
        printf("%.2lf\n",sum);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值