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

相关推荐
数模竞赛Paid answer1 小时前
2025年中青杯数学建模A题康养城市建设求解全过程论文及程序
算法·数学建模·数据分析·中青杯
网安蟹佬霸1 小时前
密码学安全实战:从加密原理到哈希破解的完整攻防指南
网络·算法·安全·web安全·开源·密码学·哈希算法
yangmu32031 小时前
深度解析:短视频是如何通过“算法+神经机制”劫持用户时间的?
算法
LuminousCPP1 小时前
栈和队列专题(四):LeetCode 232. 用栈实现队列|双栈分工 + 按需迁移 + 摊还 O(1)
c语言·数据结构·笔记·算法·leetcode
纪念 2291 小时前
二叉树排序讲解(一)
数据结构
tudousisi2222 小时前
01背包8.21
数据结构·算法
ZJU_统一阿萨姆2 小时前
【算子开发】Reduction算子完全指南
人工智能·算法·语言模型
鹿角片ljp11 小时前
LeetCode 46. 全排列|吃透回溯
算法·leetcode·职场和发展
鼎艺创新科技11 小时前
不依赖 UE/Unity:我们如何从零搭建一套国产三维 GIS 渲染引擎
人工智能·算法·unity·游戏引擎·三维电子沙盘
石头猫灯11 小时前
WordPress wp2shell 漏洞链完整拆解流程
网络·数据结构·安全·web安全