Kruskal板子

使用并查集的思想求最小生成树
复杂度O(mlogm)

int n,m;
struct edge{
	int u,v,w;
	bool operator<(const edge&t)const{
	return w<t.w;
	}
	edge(int uu,int vv,int weight):u(uu),v(vv),w(weight){
	}
	edge(){
	}
};
vector<edge>e;
int father[maxn];
int ans,cnt;
int find(int x){
	if(x!=father[x]){
		father[x]=find(father[x]);
	}
	return father[x];
}
void merge(int x,int y,int w){
	if(find(x)!=find(y)){
		father[find(x)]=find(y);
		ans+=w;
		cnt++;
	}
}
bool kruskal(){
	sort(e.begin(),e.end());
	rep(i,1,n)father[i]=i;
	
	for(int i=0;i<m;i++){
		merge(e[i].u,e[i].v,e[i].w);		
	}

	return cnt==n-1;
}
posted @   Marinaco  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示