【并查集】【Kruskal】剑鱼行动

L i n k Link Link

SSL 1618

D e s c r i p t i o n Description Description

给出N个点的坐标,对它们建立一个最小生成树,代价就是连接它们的路径的长度,现要求总长度最小。N的值在100以内,坐标值在[-10000,10000].结果保留二位小数

I n p u t Input Input

5 
0 0  
0 1 
1 1 
1 0 
0.5 0.5 

O u t p u t Output Output

2.83

T r a i n Train Train o f of of T h o u g h t Thought Thought

K r u s k a l Kruskal Kruskal算法做,首先先用勾股定理求出点之间的距离,再做算法运算就可以了
不懂 K r u s k a l Kruskal Kruskal算法的可以看一下我之前的 b l o g blog blog

C o d e Code Code

#include<cmath>
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int father[101],n;
double x,y,a[10001][10001];
struct node
{
	double from,now,time;
}f[10001];
bool cmp(node xx,node yy)
{
	return xx.time<yy.time;
}
int find(int x)
{
	if (father[x]==x) return x;
	 else return father[x]=find(father[x]);
}//寻找父节点
void merge(int x,int y)
{
	int xx=find(x);
	int yy=find(y);
	if (xx<yy) father[xx]=father[yy];
	 else father[yy]=father[xx];
}//合并
int main()
{
	int t=0;
	scanf("%d",&n);
	for (int i=1; i<=n; ++i) father[i]=i;
	for (int i=1; i<=n; ++i)
	 scanf("%lf%lf",&x,&y),a[i][0]=x,a[i][1]=y;
	for (int i=1; i<=n; ++i)
	 for (int j=1; j<i; ++j)
	  {
		double xx=(double)(a[i][0]-a[j][0]);
		double yy=(double)(a[i][1]-a[j][1]);
		double ll=(double)sqrt(xx*xx+yy*yy);
		f[++t]=(node){i,j,ll};//记录连边
   	  }
   	int k=0;
   	double ans=0;
   	sort(f+1,f+t+1,cmp);
   	for (int i=1; i<=t; ++i)
   	{
   		if (find(f[i].from)!=find(f[i].now)) {
   			merge(f[i].from,f[i].now);
   			ans+=(double)f[i].time;
  			++k;
   		}
  	    if (k==n-1) break;
   	}
   	printf("%.2lf",ans);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值