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

相关推荐
我是苏苏1 天前
C#高级:程序查询写法性能优化提升策略(附带Gzip算法示例)
开发语言·算法·c#
sali-tec1 天前
C# 基于halcon的视觉工作流-章56-彩图转云图
人工智能·算法·计算机视觉·c#
黑岚樱梦1 天前
代码随想录打卡day23:435.无重叠区间
算法
Kuo-Teng1 天前
Leetcode438. 找到字符串中所有字母异位词
java·算法·leetcode
gihigo19981 天前
MATLAB使用遗传算法解决车间资源分配动态调度问题
算法·matlab
墨染点香1 天前
LeetCode 刷题【138. 随机链表的复制】
算法·leetcode·链表
却道天凉_好个秋1 天前
目标检测算法与原理(一):迁移学习
算法·目标检测·迁移学习
兮山与1 天前
算法24.0
算法
晓北斗NorSnow1 天前
机器学习核心算法与学习资源解析
学习·算法·机器学习