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

相关推荐
星空露珠14 小时前
28种颜色对应名称,
开发语言·数据库·算法·游戏·lua
QXWZ_IA15 小时前
桥梁数字孪生怎么落地?
人工智能·科技·算法·智能硬件·政务
Kel15 小时前
输出层与反分词(Output Layer & Detokenization)
人工智能·算法·架构
陕西企来客15 小时前
2026年7月技术好GEO优化方案:算法适配与内容策略
人工智能·算法·机器学习·技术好geo优化
风栖柳白杨16 小时前
【面试】AI算法工程师_空白自测版本
人工智能·算法·面试
闪电悠米17 小时前
力扣hot100-73.矩阵置零-标记数组详解
算法·leetcode·矩阵
栋***t17 小时前
从“纸质试卷”到“AI智能组卷”,麦塔在线考试系统如何重构出题逻辑?
java·大数据·人工智能·算法·重构
wabs66617 小时前
关于图论【卡码网100.最大岛屿的面积的思考】
数据结构·算法·图论
CHANG_THE_WORLD17 小时前
深入理解递归:从函数调用到调用栈的完整执行过程
java·开发语言·算法
geovindu19 小时前
go:Backtracking Algorithm
开发语言·后端·算法·golang·回溯算法