#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int N,M;
int father[105];
int MST;
struct edage
{
int source,End,length;
edage(int ss,int ee,int ll):source(ss),End(ee),length(ll) {};
edage() {}
friend bool operator <(const edage &a,const edage &b)
{
return a.length > b.length;
}
};
priority_queue <edage> edages;
int findfather(int i)
{
return i==father[i]? i:findfather(father[i]);
}//寻找父亲结点
int krustral()
{
MST = 0;
for(int i=1; i<=N; i++)
father[i] = i;//初始化并查集
int num = 0;
while(!edages.empty() && num!=N-1)
{
edage now = edages.top();
edages.pop();
int father_x = findfather(now.source);
int father_y = findfather(now.End);
if(father_x !=father_y)
{
MST+=now.length;
father[father_x] = findfather(father_y);
num++;
}
}
return MST;
for(int i=1; i<=N; i++)
father[i] = findfather(i);
}
bool judge()//判断是否是连通图
{
int flag=father[1];
for(int i=1; i<=N; i++)
if(father[i]!=flag)
{
return false;
}
return true;
}
int main()
{
cin >> M >> N;
while(M--)
{
int source,End,length;
cin >> source >> End >> length;
edages.push(edage(source,End,length));
}
int mst = krustral();
if(judge)
cout << mst<<endl;
return 0;
}
最小堆+并查集实现最小生成树的kursutra算法
最新推荐文章于 2020-12-26 21:16:34 发布
本文详细介绍了如何利用最小堆和并查集数据结构来实现Kruskal算法,以构造给定图的最小生成树。通过避免环路的形成,确保了边的选择是最优的。这种方法结合了两种高效的数据结构,提高了算法的效率。
摘要由CSDN通过智能技术生成