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

相关推荐
Kiling_07045 分钟前
Java集合进阶:Set与Collections详解
算法·哈希算法
智者知已应修善业27 分钟前
【51单片机89C51及74LS273、74LS244组成】2022-5-28
c++·经验分享·笔记·算法·51单片机
洛水水1 小时前
【力扣100题】33.验证二叉搜索树
算法·leetcode·职场和发展
SimpleLearingAI1 小时前
聚类算法详解
算法·数据挖掘·聚类
刀法如飞2 小时前
Go 字符串查找的 20 种实现方式,用不同思路解决问题
算法·面试·程序员
Dlrb12114 小时前
C语言-指针数组与数组指针
c语言·数据结构·算法·指针·数组指针·指针数组·二级指针
WL_Aurora4 小时前
Python 算法基础篇之集合
python·算法
平行侠4 小时前
A15 工业路由器IP前缀高速检索与内存压缩系统
网络·tcp/ip·算法
阿旭超级学得完5 小时前
C++11包装器(function和bind)
java·开发语言·c++·算法·哈希算法·散列表
li星野5 小时前
位运算 & 数学 & 高频进阶九题通关(Python + C++)
c++·python·学习·算法