Kruskal算法代碼

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int n,m,tot=0,k=0;//n端點總數,m邊數,tot記錄最終答案,k已經連接了多少邊 
int fat[200010];//記錄集體老大 
struct node
{
	int from,to,dis;//結構體儲存邊 
}edge[200010];
bool cmp(const node &a,const node &b)//sort排序(當然你也可以快排) 
{
	return a.dis<b.dis;
}
int father(int x)//找集體老大,並查集的一部分 
{
	if(fat[x]!=x)
	return father(fat[x]);
	else return x;
}
void unionn(int x,int y)//加入團體,並查集的一部分 
{
	fat[father(y)]=father(x);
}
int main()
{
	scanf("%d%d",&n,&m);//輸入點數,邊數 
	for(int i=1;i<=m;i++)
	{
		scanf("%d%d%d",&edge[i].from,&edge[i].to,&edge[i].dis);//輸入邊的信息 
	}
	for(int i=1;i<=n;i++) fat[i]=i;//自己最開始就是自己的老大 (初始化) 
	sort(edge+1,edge+1+m,cmp);//按權值排序(kruskal的體現) 
	for(int i=1;i<=m;i++)//從小到大遍歷 
	{
		if(k==n-1) break;//n個點需要n-1條邊連接 
		if(father(edge[i].from)!=father(edge[i].to))//假如不在一個團體 
		{
			unionn(edge[i].from,edge[i].to);//加入 
			tot+=edge[i].dis;//記錄邊權 
			k++;//已連接邊數+1 
		}
	}
	printf("%d",tot);
	return 0;
}


原文:https://blog.csdn.net/qq_41754350/article/details/81460643

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章