2023-9-2 Kruskal算法求最小生成树

题目链接:Kruskal算法求最小生成树

2023-9-2 Kruskal算法求最小生成树_第1张图片

#include 
#include 

using namespace std;

const int N = 200010;

// 与并查集中的p含义相同
int p[N];

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

int n, m;

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

int main()
{
    cin >> n >> m;
    
    for(int i = 0; i < m; i ++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        edges[i] = {a, b, c};
    }
    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) cout << "impossible" << endl;
    else cout << res << endl;
    
    return 0;
}

你可能感兴趣的:(算法,c++,图论)