POJ 2377 Bad Cowtractors [圖論.最小生成樹] 《挑戰程序設計競賽》2.5

2017-05-23
題目鏈接:POJ 2377 Bad Cowtractors
題目大意:

求費用最大的生成樹。

題解:

kruskal算法,sort排序時降序排序。

代碼:

#include <iostream>
#include <algorithm>
#define MAXN 1010
#define MAXM 20010
using namespace std;

struct Edge {
    int from, to, cost;
}edge[MAXM];
int N, M;
int f[MAXN];

bool cmp(const Edge &a, const Edge &b) {
    return a.cost > b.cost;
}

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

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

void unite(int x, int y) {
    int fx = find(x);
    int fy = find(y);
    if (fx != fy) {
        f[fx] = fy;
    }
}

int kruskal() {
    sort(edge, edge+M, cmp);
    for (int i = 0; i <= N; i++) f[i] = i;
    int ans = 0, k = 0;
    for (int i = 0; i < M; i++) {
        if (!isSame(edge[i].from, edge[i].to)) {
            unite(edge[i].from, edge[i].to);
            ans += edge[i].cost;
            k++;
            if (k == N-1) break;
        }
    }
    if (k < N-1) return -1;
    else return ans;
}

int main() {
    ios::sync_with_stdio(false);
    cin >> N >> M;
    for (int i = 0; i < M; i++) {
        int from, to, cost;
        cin >> from >> to >> cost;
        edge[i].from = from;
        edge[i].to = to;
        edge[i].cost = cost;
    }
    int ans = kruskal();
    cout << ans << endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章