Kruskal(克鲁斯卡尔)算法总结

知识概览

  • 克鲁斯卡尔算法适用于稀疏图求最小生成树,时间复杂度为O(mlogm)。

例题展示

题目链接

Kruskal算法求最小生成树

859. Kruskal算法求最小生成树 - AcWing题库icon-default.png?t=N7T8https://www.acwing.com/problem/content/861/

代码

#include 
#include 

using namespace std;

const int N = 200010;

int n, m;
int p[N];

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

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

int main()
{
    scanf("%d%d", &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};
    }
    
    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) puts("impossible");
    else printf("%d\n", res);
    
    return 0;
}

参考资料

  1. AcWing算法基础课

你可能感兴趣的:(经典算法总结,图论,算法,克鲁斯卡尔算法,Kruskal算法,最小生成树,图论)