Minimum Spanning Tree (Kruskal's Algorithm)

concept

A spanning tree of a connected graph with n nodes is a minimal connected subgraph of the original graph, and contains all n nodes in the original graph, and has the fewest edges that keep the graph connected

template questions

insert image description here
insert image description here

Kruskal's algorithm

First sort the edges according to their weights, and use the greedy idea to select the edges with smaller weights first, and connect them in turn. If there is a loop, skip this edge (use the union check set to judge whether there is a loop) and continue to search until it has been The number of edges used is one less than the total number of points.

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
long long n,m;
struct node{
    
    
	int start,end,v;
};
node edge[2000005];
int parent[5005],rank[5005];
//并查集路径压缩 
int find(int x){
    
    
	if(x==parent[x])return x;
	return parent[x]=find(parent[x]);
}
//秩优化 
void unio(int x,int y){
    
    
	int x_root=find(x);
	int y_root=find(y);
	if(x_root==y_root)return;
	if(rank[x_root]>rank[y_root]){
    
    
		parent[y_root]=x_root;
	}else{
    
    
		parent[x_root]=y_root;
		if(rank[x_root]==rank[y_root]){
    
    
			rank[y_root]++;
		}
	}
}
bool cmp(node a,node b){
    
    
	return a.v<b.v;
}
int main(){
    
    
	scanf("%lld%lld",&n,&m);
	//初始化并查集 
	for(int i=0;i<=n;i++){
    
    
		parent[i]=i;
		rank[i]=0;
	}
	for(int i=0;i<m;i++){
    
    
		scanf("%d %d %d",&edge[i].start,&edge[i].end,&edge[i].v);
	}
	//排序 
	sort(edge,edge+m,cmp);
	long long ans=0,con=0;
	//扫描边 
	for(int i=0;i<m;i++){
    
    
		//把祖宗都提前求出来减少复杂度 
		int eu=find(edge[i].start); 
		int ev=find(edge[i].end);
		if(eu!=ev){
    
    //不在同一个集合 
			ans+=edge[i].v;
			unio(eu,ev);//加入集合 
			con++;
			if(con==n-1)break;//n个顶点的最小生成树有n-1条边 
		}
	}
	if(con<n-1){
    
    
		cout<<"orz"<<endl;
	}else{
    
    
		printf("%lld\n",ans);
	}
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324938609&siteId=291194637
Recommended