编程语言
首页 > 编程语言> > [AcWing 859] Kruskal算法求最小生成树

[AcWing 859] Kruskal算法求最小生成树

作者:互联网

image
image

复杂度 \(O(m*log(m))\)


点击查看代码
#include<iostream>
#include<algorithm>

using namespace std;
const int N = 1e5 + 10, M = 2 * N, INF = 0x3f3f3f3f;
int n, m;
int p[N];
int res, cnt;

struct Edge {
    int a, b, w;
    bool operator< (const Edge & W) const {
        return w < W.w;
    }
}edges[M];

int find(int x)
{
    if (p[x] != x)  p[x] = find(p[x]);
    return p[x];
}
int Kruskal()
{
    sort(edges, edges + m);
    for (int i = 1; i <= n; i ++)   p[i] = i;
    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;
    else    return res;
}
int main()
{
    cin >> n >> m;
    for (int i = 0; i < m; i ++) {
        int a, b, w;
        cin >> a >> b >> w;
        edges[i] = {a, b, w};
    }
    int t = Kruskal();
    if (t == INF)   puts("impossible");
    else    cout << res << endl;
    return 0;
}

  1. Kruskal 思路:每次取出权值最小的边,如果边的两个端点之间没有连通,则把两个端点放到同一个并查集当中;
  2. 要先对所有的边进行排序,使用 sort 函数进行排序,在 struct 中对小于号进行重载;

标签:const,int,Kruskal,859,edges,include,find,AcWing
来源: https://www.cnblogs.com/wKingYu/p/16242717.html