最小堆+并查集实现最小生成树的kursutra算法

8 篇文章 0 订阅
4 篇文章 0 订阅
本文详细介绍了如何利用最小堆和并查集数据结构来实现Kruskal算法,以构造给定图的最小生成树。通过避免环路的形成,确保了边的选择是最优的。这种方法结合了两种高效的数据结构,提高了算法的效率。
摘要由CSDN通过智能技术生成

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值