859 Kruskal求最小生成树

把所有边按照权重值从小到大排序,然后一一收入集合,利用联通集判断一条边的两个点是否在一个联通集中 如果在就不收录这条边

#include<bits/stdc++.h>
using namespace std;

const int N = 100010, M = 200010;
int n, m;
int P[N];
struct edge{
    int a, b, w;
    bool operator< (edge &e) const{
        // 小括号里面的是外来的,不带修饰符的是自己, 返回true就是小于(对于这个重载)
        return w < e.w;
    }
}edges[M];

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

int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) P[i] = i;
    for (int i = 0; i < m; i++) {
        int a, b, w;
        cin >> a >> b >> w;
        edges[i] = {a, b, w};
    }
    sort(edges, edges + m);
    
    int res = 0, cnt = 1;
    for (int i = 0; i < m; i++) {
        int a = edges[i].a, b = edges[i].b, w = edges[i].w;
        a = find(a), b = find(b);
        if (a == b) continue;
        else {
            res += w;
            P[a] = b;
            cnt ++;
        }
    }
    if (cnt < n) puts("impossible");
    else cout << res;
    return 0;
}
posted @ 2022-10-25 13:19  天然气之子  阅读(11)  评论(0编辑  收藏  举报