acwing搜索与图论(三)kruskal算法

复制代码
#include<iostream>
#include<algorithm>
using namespace std;

const int N=200010;

int n,m;
int p[N];

struct Edge{
	int a,b,w;
	bool operator<(const Edge &W)const
	{
		return w<W.w;
	}
}edges[N];		

int find(int x)
{
	if(p[x]!=x)p[x]=find(p[x]);
	return p[x];
}
int main(){
	cin>>n>>m;
	for(int i=0;i<m;i++){
		int a,b,w;
		cin>>a>>b>>w;
		edges[i]={a,b,w};
	}
	sort(edges,edges+m);
	for(int i=1;i<=n;i++){
		p[i]=i;
	}
	
	int res=0,cnt=0;
	for(int i=0;i<m;i++){
		int a=edges[i].a,b=edges[i].b,w=edges[i].w;
		a=find(a),b=find(b);
		if(a!=b){
			
			p[a]=b;
			res+=w;
			cnt++;
			
		}
	}
	if(cnt<n-1)printf("imp");
	else printf("%d",res);
}

	bool operator<(const Edge &W)const
	{
		return w<W.w;
	}

这一部分是一个重载操作符,对于后面sort排序那里使用的,就是说sort排序将后入结构体的数据,按照从小到大排序,

参考连接

https://cloud.tencent.com/developer/article/1086938https://www.cnblogs.com/ZERO-/p/9347296.html

https://blog.csdn.net/Li5566123/article/details/123611568?fromshare=blogdetail&sharetype=blogdetail&sharerId=123611568&sharerefer=PC&sharesource=kmvmy&sharefrom=from_link

相关推荐
现在,此刻7 小时前
leetcode 11. 盛最多水的容器 -java
java·算法·leetcode
☆璇8 小时前
【C++】哈希的应用:位图和布隆过滤器
算法·哈希算法
码达拉9 小时前
顺序表的总结及模拟实现
数据结构·c++
Boop_wu9 小时前
[ 数据结构 ] 时间和空间复杂度
数据结构
一株月见草哇10 小时前
Matlab(4)
人工智能·算法·matlab
hans汉斯10 小时前
基于深度学习的苹果品质智能检测算法研究
人工智能·深度学习·算法
紫洋葱hh10 小时前
【数据结构】二叉搜索树
数据结构
火车叨位去194910 小时前
力扣top100(day01-05)--矩阵
算法·leetcode·矩阵
mit6.82410 小时前
[Robotics_py] 机器人运动模型 | `update`函数 | 微积分&矩阵
人工智能·python·算法
·白小白11 小时前
【数据结构】——栈(Stack)的原理与实现
c语言·开发语言·数据结构