天天看點

acwing 859 Kruskal算法求最小生成樹

題面

acwing 859 Kruskal算法求最小生成樹

題解

求解步驟:
  1. 将所有邊按權重從小到大排序
  2. 枚舉每條邊ab,權重c,如果ab不連通,就将這條邊加入集合 (并查集)
  3. 求最小生成樹時間複雜度 O(mlogm)

代碼

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 1e5 + 10;
const int INF = 0x3f3f3f3f;

int n, m;
int p[N];

struct Node {
    int a, b, w;

    //重載小于号
    bool operator<(const Node &W) const {
        return w < W.w;
    }
} edges[2*N];

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

int kruskal() {

    //1.将所有邊按權從小到大排序
    sort(edges, edges + m);
    //2.每次加入未在集合中的最小邊權

    for (int i = 1; i <= n; i++) p[i] = i;

    int res = 0, cnt = 0;

    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) {
            p[a] = b;
            res += w;
            cnt++;
        }
    }

    if (cnt < n - 1) return INF;
    return res;

}

int main() {

    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    cin >> n >> m;

    for (int i = 1; i <= m; i++) {
        int a, b, c;
        cin >> a >> b >> c;
        edges[i] = {a, b, c};
    }

    int res = kruskal();

    if (res == INF) cout << "impossible" << endl;
    else cout << res << endl;

    return 0;
}