poj2377(最大生成树)

题意:给出点和边,求最大生成树,如果不能生成树,输出-1。

Sample Input

5 8
1 2 3
1 3 7
2 3 10
2 4 4
2 5 8
3 4 6
3 5 2
4 5 17

Sample Output

42

  • Line 1: Two space-separated integers: N(点) and M(边)
  • Lines 2..M+1: Each line contains three space-separated integers A, B, and C that describe a connection route between barns A and B of cost C.

思路:有N个点,如果共取了N - 1条边,就可以,否则输出-1。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <set>
using namespace std;

const int MAX_N = 1e3 + 5;
const int MAX_M = 2e4 + 5;
int par[MAX_N];
int rank[MAX_N];

struct edge {
    int a, b, cost;
};

edge es[MAX_M];

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

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

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

bool comp(const edge &a, const edge &b) {
    return a.cost > b.cost;
}

int solve(int n, int m) {
    //set<int> s;
    sort(es, es + m, comp);
    int res = 0;
    int ans = 0;//记录有多少条边
    for (int i = 0; i < m; ++i) {
        edge e = es[i];
        if (find(e.a) != find(e.b)) {
            unite(e.a, e.b);
            //s.insert(e.a);
            //s.insert(e.b);
            ++ans;
            res += e.cost;
        }
    }
    //if (s.size() != n) res = -1;//如果这样的话,各个边不一定是联通的,如12,34,s.size() = 4, 符合条件,但不能构成树
    if (ans != n - 1) res = -1;
    return res;
}

int main() {
    int n, m;
    while (scanf("%d%d", &n, &m) != EOF) {
        init(n);
        for (int i = 0; i < m; ++i) {
            int a, b, c;
            scanf("%d%d%d", &a, &b, &c);
            es[i] = (edge){a - 1, b - 1, c};
        }
        printf("%d\n", solve(n, m));
    }
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,025评论 0 23
  • 亲子共读:1、宝贝给妈妈读了《小善的被子》,宝贝的表达能力提高了很多啊,几乎是按原文讲下来的,有个别用词不太准确,...
    快乐的鸣妈阅读 176评论 0 0
  • 拍照设备:OPPO手机 后期滤镜:黄油相机 图片初衷:5月1日,漫无目的压马路。 春风再美也比不上你的笑,没见过你...
    李笑笑啊阅读 266评论 1 5
  • (100日阅读习惯之25/100)《王者速读法》 日本齐藤英治,医学博士,以提高身心健康和脑力开发为终身事业,他所...
    半尚重楼阅读 281评论 0 1
  • 刚刚特意去百度了一下我写的字数,才2000多一点。我的天啊,这么长的时间过去了。我感觉自己写了很多了呢。怎么才是2...
    禾旭阅读 284评论 0 0