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 @ 2025-02-27 21:18  Marinaco  阅读(12)  评论(0)    收藏  举报
//雪花飘落效果