building roads【最小生成树】

题目链接
最小生成树,只需把原本就有的路的长度看作 0 ,跑一遍模板即可。

code

#include<bits/stdc++.h>
using namespace std;
int fa[1005],n,m,tot,cnt;
int x[1005],y[1005];
double ans;
struct node {double v; int s,t;}e[800005];

inline int read() {
	int x=0,f=1; char c=getchar();
	while(c<'0'||c>'9') {if(c=='-')f=-1; c=getchar();}
	while(c>='0'&&c<='9') x=(x<<3)+(x<<1)+c-'0',c=getchar();
	return x*f;
}
double dist(int x1,int y1,int x2,int y2) {return (double)sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));}
int cmp(node x1,node x2) {return x1.v<x2.v;}

int getfa(int x) {
	if(fa[x]!=x) return fa[x]=getfa(fa[x]);
	return x;
}
void hebing(int x,int y) {
	int xx=getfa(x),yy=getfa(y);
	if(xx!=yy) fa[xx]=yy,tot++;
}

int main() {
	freopen("roads.in","r",stdin);
	freopen("roads.out","w",stdout);
	n=read(); m=read();
	for(int i=1;i<=n;i++) fa[i]=i;
	for(int i=1;i<=n;i++) 
	 x[i]=read(),y[i]=read();
	for(int i=1;i<=m;i++) {
		int hx=read(),hy=read();
		e[++cnt].v=0.0;
	  	e[cnt].s=hx; e[cnt].t=hy;
	}
	for(int i=1;i<n;i++)
	 for(int j=i+1;j<=n;j++) {
	  	e[++cnt].v=dist(x[i],y[i],x[j],y[j]);
	  	e[cnt].s=i; e[cnt].t=j;
	 }
	sort(e+1,e+cnt+1,cmp);
    for(int i=1;tot<n;i++) {
    	hebing(e[i].s,e[i].t);
    	ans+=e[i].v;
	}
	printf("%.2llf",ans);
	return 0; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值