JZOJ 1244. 修建道路【最小生成树】


题目:

传送门


题意:

给出 n n n个点和已经建好的 m m m条边,求我们需要修建的最小代价使得 n n n个点可以互相到达


分析:

正常最小生成树随便跑,对于已经修好的边就直接在开始就放在一个块里


代码:

#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cmath>
#include<vector>
#define LL long long
using namespace std;
inline LL read() {
    LL d=0,f=1;char s=getchar();
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
    return d*f;
}
LL x[1000005],y[1000005];
struct node{
	LL x,y;
	double w;
}e[1000005];
double get(LL a,LL b)
{
	return sqrt((double)(x[a]-x[b])*(x[a]-x[b])+(double)(y[a]-y[b])*(y[a]-y[b]));
}
bool cmp(node a,node b) {return a.w<b.w;}
LL f[1000005];
LL find(LL i) {return f[i]==i?i:f[i]=find(f[i]);}
int main()
{
	LL n=read(),m=read();
	for(LL i=1;i<=n;i++) x[i]=read(),y[i]=read();
	for(LL i=1;i<=n;i++) f[i]=i;
	for(LL i=1;i<=m;i++)
	{
		LL xx=read(),yy=read();
		f[find(xx)]=find(yy);
	}
	LL mm=0;
	for(LL i=1;i<n;i++)
	  for(LL j=i+1;j<=n;j++)
	  {
		e[++mm].x=i;e[mm].y=j;e[mm].w=get(i,j);
	  }
	sort(e+1,e+1+mm,cmp);
	double ans=0;
	for(LL i=1;i<=mm;i++)
	{
		LL xx=e[i].x,yy=e[i].y;
		if(find(xx)==find(yy)) continue;
		f[find(xx)]=find(yy);
		ans+=e[i].w;
	}
	printf("%.2lf",ans);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值