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

相关推荐
music&movie1 小时前
算法工程师认知水平要求总结
人工智能·算法
laocui12 小时前
Σ∆ 数字滤波
人工智能·算法
yzx9910132 小时前
Linux 系统中的算法技巧与性能优化
linux·算法·性能优化
全栈凯哥2 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥2 小时前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu3 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
Humbunklung3 小时前
机器学习算法分类
算法·机器学习·分类
Ai多利3 小时前
深度学习登上Nature子刊!特征选择创新思路
人工智能·算法·计算机视觉·多模态·特征选择
lyh13443 小时前
【SpringBoot自动化部署方法】
数据结构
MSTcheng.4 小时前
【数据结构】顺序表和链表详解(下)
数据结构·链表