acwing 859 Kruskal algorithm for minimum spanning tree

Topic

Insert picture description here

answer

Solution steps:

  1. Sort all edges by weight from smallest to largest
  2. Enumerate each edge ab, weight c, if ab is not connected, add this edge to the set (and check the set)
  3. Find the minimum spanning tree time complexity O(mlogm)

Code

#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;
}

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/114484866
Recommended