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

来源:互联网 发布:群邑管培生待遇 知乎 编辑:程序博客网 时间:2024/04/24 15:02

题目链接: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;}
0 0