Kruskal算法求最小生成树

Kruskal 算法原理及证明见提高课

Kruskal算法求最小生成树 $O(m\log m)$

IMG_20210629_141909_edit_223503600585686.jpg

这里重载运算符的方式也可以通过写cmp()来作为sort的第三个参数

1
2
3
4
bool cmp(Edge a, Edge b)
{
    return a.w < b.w;
}

完整代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

const int N = 100010, M = 200010, INF = 0x3f3f3f3f;
int p[N];
int n, m;

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;

    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()
{
    cin >> n >> m;

    for (int i = 0; i < m; i ++ )
    {
        int a, b, w;
        scanf("%d%d%d", &a, &b, &w);
        edges[i] = {a, b, w};
    }

    int t = kruskal();

    if (t == INF)   puts("impossible");
    else cout << t << endl;
    return 0;
}
yitao 支付宝支付宝
yitao 微信微信
0%