链接三维空间中n个点的最短距离 最小生成树(krukal算法)

来源:互联网 发布:怎样手机做淘宝客赚钱 编辑:程序博客网 时间:2024/05/22 22:15

DESCRIPTION

Spoon Devil build a 3-D matrix, and he(orshe) wants to know if he builds some bases what's the shortest distance toconnect all of them.

INPUT

There are multiple test cases. The firstline of input contains an integer T, indicating the number of test cases. Foreach test case:

The first line contains one integern (0<n<50), indicating the number of all points. Then the next nlines, each lines contains three numbers xi,yi,zi indicating the position ofi-th point.

OUTPUT

For each test case, output a line, whichshould accurately rounded to two decimals.

SAMPLE INPUT

2

2

1 1 0

2 2 0

3

1 2 3

0 0 0

1 1 1

SAMPLE OUTPUT

1.41

3.97

 题意

求连n个点(三维坐标),所需要的最短距离。(最小生成树)

1.首先对点做预处理2.用krukal算法进行求解。

#include <stdio.h>#include <string.h>#include <math.h>int n,m;double s;int p[1005];struct ed{int u;int v;double w;};struct asd{int x;int y;int z;};struct ed e[5000];int find (int x){return p[x]==x?x:p[x]=find(p[x]);}void kru(){int i,j,x,y;for(i=1;i<=m;i++){x=find(e[i].u);y=find(e[i].v);if(x!=y){p[x]=y;s=s+e[i].w;}}}void sort(){int i,j,k;struct ed t;for(i=1;i<=m-1;i++){k=i;for(j=i+1;j<=m;j++)if(e[j].w<e[k].w)k=j;t=e[k];e[k]=e[i];e[i]=t;}}int main(){int T;scanf("%d",&T);while(T--){s=0;scanf("%d",&n);int i,j,x,y,z,k;m=(n*(n-1))/2;asd b[51];for(i=1;i<=n;i++){scanf("%d %d %d",&b[i].x,&b[i].y,&b[i].z);}k=1;for(i=1;i<n;i++){for(j=i+1;j<=n;j++){e[k].w=sqrt((b[i].x-b[j].x)*(b[i].x-b[j].x)+(b[i].y-b[j].y)*(b[i].y-b[j].y)+(b[i].z-b[j].z)*(b[i].z-b[j].z));e[k].u=i;e[k].v=j;k++;}} for(i=1;i<=n;i++)p[i]=i;sort();kru();printf("%.2f\n",s);}}



0 0