每日一题 No.54 最小生成树问题(Kruskal算法)

本题要求:

给出一个有向图,让你求出这个图的最小生成树

输入格式:

第一行输入V,E分别代表顶点数和边数
接下来E行,每行输入from to cost 代表从from到to的距离为cost

输出格式:

输出最小消耗

输入样例:

3 3
0 1 2
1 2 3
0 2 4

输出样例:

5

解题思路 :

按照边的权值的顺序从大到小查看一遍。

代码 :

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;  

class Edge {
    public:
        int u;
        int v;
        int cost;
        Edge(int u, int v, int cost) {
            this->u = u;
            this->v = v;
            this->cost = cost;
        }
        Edge() {
        }
};
using namespace std;  

int par[1001];
int rank[1001];

void init(int n) {
    for (int i = 0; i < n; i++) {
        par[i] = i;
        rank[i] = 0;
    }
}

int find(int x) {
    if (par[x] == x) {
        return x;
    } else {
        return par[x] = find(par[x]);
    }
}

void unite(int x, int y) {
    x = find(x);
    y = find(y);
    if (x == y) {
        return;
    } else if (rank[x] < rank[y]){
        par[x] = y;
    } else {
        par[y] = x;
        if (rank[x] == rank[y]) {
            rank[x]++;
        }
    }
}

bool same(int x, int y) {
    return find(x) == find(y); 
} 

bool comp(const Edge& e1, const Edge& e2) {
    return e1.cost < e2.cost;
}
vector<Edge> es;
int V, E;

int kruskal() {
    sort(es.begin(), es.end(), comp);
    init(V);
    int res = 0;
    for (int i = 0; i < E; i++) {
        Edge e = es[i];
        if (!same(e.u, e.v)) {
            unite(e.u, e.v);
            res += e.cost;
        }
    }
    return res;
}
int main() {
    bool used[101];
    cin >> V >> E;
    for (int i = 0; i < E; i++) {
        int f, t, c;
        cin >> f >> t >> c;
        es.push_back(Edge(f, t ,c));
    }
    cout << kruskal();
    return 0; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值