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

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);
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值