[贪心算法]kruskal算法求最小生成树

原理图

这里写图片描述

#图片来源http://blog.csdn.net/luoshixian099/article/details/51908175
代码

基于小根堆和并查集。测试是根据图中来的。
代码中含有将有向图化为无向图的部分。

#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int set[100];
int find(int x) {
    if (set[x] == x)
    {
        return x;
    } else {
        int root = find(set[x]);
        set[x] = root;
        return root;
    }
}
void unin(int root1 , int root2) {
    set[root1] = root2;//root2作为根
}
struct Node
{
    int x, y;
    int e;
    Node(int a, int b , int w) {
        x = a;
        y = b;
        e = w;
    }
};
struct cmp
{
    bool operator()(Node& a, Node& b) {
        return a.e > b.e;
    }
};
int main(int argc, char const *argv[])
{
    priority_queue<Node, vector<Node>, cmp> a, con;
    Node x1 = Node(1, 2, 6);
    Node x2 = Node(2, 3, 5);
    Node x3 = Node(1, 3, 1);
    Node x4 = Node(1, 4, 5);
    Node x5 = Node(3, 4, 5);
    Node x6 = Node(2, 5, 3);
    Node x7 = Node(3, 5, 6);
    Node x8 = Node(5, 6, 6);
    Node x9 = Node(3, 6, 4);
    Node x10 = Node(4, 6, 2);
    a.push(x1);
    a.push(x2);
    a.push(x3);
    a.push(x4);
    a.push(x5);
    a.push(x6);
    a.push(x7);
    a.push(x8);
    a.push(x9);
    a.push(x10);
    for (int i = 1; i <= 10; ++i)//有向图变为无向图
    {
        con.push(Node(a.top().x, a.top().y, a.top().e));
        con.push(Node(a.top().y, a.top().x, a.top().e));
        a.pop();
    }
    for (int i = 0; i <= 9; ++i)
    {
        set[i] = i;
    }
    vector<Node> res;
    while (!con.empty() && res.size() <=5) {
        Node a = con.top();
        con.pop();
        int x = find(a.x);
        int y = find(a.y);
        if (x != y)
        {
            unin(x, y);
            res.push_back(a);
        } else {
            continue;
        }
    }
    if (res.size() != 5)
    {
        for (int i = 0; i < res.size(); ++i)
        {

            cout << res[i].x << "--" << res[i].y << "--"
                 << res[i].e<<endl;
        }
        cout << "false" << endl;
    } else {
        cout << "res:"<<endl;
        for (int i = 0; i < res.size(); ++i)
        {

            cout << res[i].x << "--" << res[i].y << "--"
                 << res[i].e<<endl;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值