AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 应用
  • 更多
    • 题解
    • 分享
    • 商店
    • 问答
    • 吐槽
  • App
  • 登录/注册

AcWing 859. Kruskal算法求最小生成树

作者: 作者的头像   Jesus ,  2022-04-26 00:20:10 ,  所有人可见 ,  阅读 24


0


https://mp.weixin.qq.com/s?__biz=MjM5NTY1MjY0MQ==&mid=2650853887&idx=4&sn=8bc8a0ae10131ed7ba8c9b6d71a83ed4&chksm=bd0144b18a76cda77f904b23a05818ea3db6ac58910eca05e8d844bef7e9b44e119281cbb8b9&mpshare=1&scene=23&srcid=06111rCJYTgEAZJQjMjqX0TY&sharer_sharetime=1654940817042&sharer_shareid=21b047d30a12b4dea3199d43fe677347#rd

#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 100010, M = 200010, INF = 0x3f3f3f3f;

int n, m;
int p[N];

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()
{
    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};
    }

    int t = kruskal();

    if (t == INF) puts("impossible");
    else printf("%d\n", t);

    return 0;
}

1 评论


用户头像
Jesus   11个月前         踩      回复

https://mp.weixin.qq.com/s?__biz=MjM5NTY1MjY0MQ==&mid=2650853887&idx=4&sn=8bc8a0ae10131ed7ba8c9b6d71a83ed4&chksm=bd0144b18a76cda77f904b23a05818ea3db6ac58910eca05e8d844bef7e9b44e119281cbb8b9&mpshare=1&scene=23&srcid=06111rCJYTgEAZJQjMjqX0TY&sharer_sharetime=1654940817042&sharer_shareid=21b047d30a12b4dea3199d43fe677347#rd


你确定删除吗?

© 2018-2023 AcWing 版权所有  |  京ICP备17053197号-1
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息