Kruskal's minimum spanning tree of structure

#include<iostream>
#include<algorithm>
using namespace std;
/* 
1 定义边结构体,定义顶点表  
2 进行边的比较,按从小到大排序
3 查找根结点
4 查看节点是否相同
5 合并边
6  实现kruskal 
*/
int N,M;
struct Edge{
    
    
	int form,to,dis;
}e[128]; 
int n[128]={
    
    0};//用来储存顶点关系 
bool cmp(Edge x1,Edge x2){
    
    //比较大小 
	return x1.dis<x1.dis;
}
int father(int x){
    
    //寻找父节点 
	if(x == n[x]){
    
    
		return x;
	}
	n[x] = father(n[x]);
	return father(n[x]);
}
bool check(int x1,int x2){
    
    //比较是否同一个结点 
	if(father(x1)==father(x2)){
    
    
		return true;
	}
	return false;
}
void merge(int x1,int x2){
    
    //x2 为父节点 
	n[father(x1)] = father(x2);
}
int kruskal(){
    
    
	int sum = 0;//记录距离和 
	int node = 0;//记录顶点个数 
	int t1,t2;
	for(int i =1;i<=M;i++){
    
    
		t1 = father(e[i].form);//寻找父节点 
		t2 = father(e[i].to);//寻找父节点 
		if(!check(t1,t2)){
    
    // 判断父节点是否相同 
			merge(t1,t2);// 节点合并 
			sum = sum +e[i].dis;
			node = node + 1;
		}
	}
	if(node==N-1){
    
    
		return sum; 
	}
}
int main(){
    
    
	cin>>N>>M;//输入点和变个数 
	for(int i=1;i<=N;i++){
    
    
		n[i]=i;
	}
	int x,y,z;
	for(int i=1;i<=M;i++){
    
    //初始边信息 
		cin>>x>>y>>z;
		e[i].form=x;
		e[i].to=y;
		e[i].dis=z;	
	}
 
	sort(e+1,e+M+1,cmp);//简单排序 传入数组首地址 数组最后一个元素地址  默认升序 
	cout<<kruskal();
	return 0;
} 

Refer to the video, if you don’t understand, watch the video explanation
Insert picture description here

Guess you like

Origin blog.csdn.net/NewDay_/article/details/109110357