贪心算法 Kruskal/最小生成树

关键词并查集/STL排序/贪心

使用并查集Union() & Find()实现节点连接和连通性的判断
使用STL的sort函数对边集进行从小到大排序


并查集:

class FastUnionFind {
    public:
        int a[11];
        FastUnionFind(int n) {
            for(int i = 0; i <= n; i++) a[i] = i;
        }
        int Find(int x) {
            if(a[x] == x) return x;
            else return Find(a[x]);
        }
        void Union(int x, int y) {
            a[Find(y)] = a[Find(x)];
        }
};

边的类

class bian {
    public:
        int node1;
        int node2;
        float weight;
};

sort函数compare判断条件:

bool com(bian a, bian b) {
    return a.weight < b.weight;
}

完整代码

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

class FastUnionFind {
    public:
        int a[11];
        FastUnionFind(int n) {
            for(int i = 0; i <= n; i++) a[i] = i;
        }
        int Find(int x) {
            if(a[x] == x) return x;
            else return Find(a[x]);
        }
        void Union(int x, int y) {
            a[Find(y)] = a[Find(x)];
        }
};

class bian {
    public:
        int node1;
        int node2;
        float weight;
};

bool com(bian a, bian b) {
    return a.weight < b.weight;
}

int main() {
    int biannum = 10;
    bian bianlist[10] = {
        {1, 2, 6},
        {1, 3, 1},
        {1, 4, 5},
        {2, 3, 5},
        {2, 5, 3},
        {3, 4, 5},
        {3, 5, 6},
        {3, 6, 4},
        {4, 6, 2},
        {5, 6, 6}
    };
    vector<bian> selected;
    FastUnionFind UnionList(biannum);
    sort(bianlist, bianlist+10, com);
    for(int i = 0; i < 10; i++) {
        bian demobian = bianlist[i];
        int a = demobian.node1;
        int b = demobian.node2;
        float value = demobian.weight;
        if(UnionList.Find(a) != UnionList.Find(b)) {
            UnionList.Union(a, b);
            selected.push_back(demobian);
        }
    }
    for(int i = 0; i < selected.size(); i++) {
        cout << "NodeA: " << selected[i].node1 << " " << "NodeB: " << selected[i].node2 << " " << "Value: " << selected[i].weight << endl;
    }
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值