计蒜客 穿越雷区

本文介绍了一种使用并查集优化的算法,通过比较边权值实现图中节点间的最小代价连接。通过多次合并操作,求解了带有权重的边的图中,将所有节点连接起来所需的总最小代价。核心代码展示了如何利用C++实现并查集及其在解决实际问题中的应用。
摘要由CSDN通过智能技术生成
#include<bits/stdc++.h>
using namespace std;
int n,m;
const int maxn=1e5+7;
int father[maxn];
struct edge{
	int u,v,w;
}e[maxn];
bool cmp(edge a,edge b){
	return a.w<b.w;
}
int get(int a){
	if(father[a]==a) return a;
	else return father[a]=get(father[a]);
}
void merge(int a,int b){
	a=get(a);
	b=get(b);
	if(a!=b) father[a]=b;
}
int main(){
	cin>>n>>m;
	for(int i=1;i<=m;i++){
		cin>>e[i].u>>e[i].v>>e[i].w;
	}
	for(int i=1;i<=n;i++) father[i]=i;
	sort(e+1,e+1+m,cmp);
	int ans=0;
	int res=n;
	for(int i=1;i<=m&&res>1;i++){
		int u=get(e[i].u);
		int v=get(e[i].v);
		if(u!=v){
			res--;
			merge(e[i].u,e[i].v);
			ans+=e[i].w;
		}
	}
	cout<<ans;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值