AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

详解与促背模板 -- 算法基础课 -- 搜索与图论(三):最小树prim

作者: 作者的头像   MW10 ,  2025-01-10 21:40:08 ,  所有人可见 ,  阅读 2


0


/*
I:(n,m)无向图;m (u, v, w);
(n,m)无向图,可能重边、自环,边权可能为负;
O:最小生成树的边权和,不存在最小生成树则输出“impossible”;

I:
4 5
1 2 1
1 3 2
1 4 3
2 3 2
3 4 4
O:
6
*/


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

using namespace std;

const int N = 510, INF = 0x3f3f3f3f;

// 无向图:邻接矩阵存储
int n, m;
int g[N][N];


int dist[N];
bool min_set[N];
int prim()
{
    // dist[]不是节点到源点的距离,而是:1初始值 2一条边的值代表点到点集的距离
    memset(dist, 0x3f, sizeof dist);
    // n次迭代
    int res = 0;
    for (int i = 0; i < n; i ++ )
    {
        // 每次找到:最小树集合外 + 距离最短(需要dist[t]有一个初始化)
        int t = -1;
        for (int j = 1; j <= n; j ++ )
            if (!min_set[j] && (t == -1 || dist[t] > dist[j]))
                t = j;

        if (i && dist[t] == INF) return INF;
        // 防止自环更新自己的dist[]
        if (i) res += dist[t];
        min_set[t] = true;
        // 使用集合更新距离:一条边的权重
        for (int j = 1; j <= n; j ++ ) dist[j] = min(dist[j], g[t][j]);
    }

    return res;
}


int main()
{
    // 输入无向图:邻接矩阵
    scanf("%d%d", &n, &m);
    memset(g, 0x3f, sizeof g);
    while (m -- )
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        // 应对重边、自环min
        // 有向图代替无向图:邻接矩阵为对称阵
        g[a][b] = g[b][a] = min(g[a][b], c);
    }

    int t = prim();

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

    return 0;
}

0 评论

App 内打开
你确定删除吗?
1024
x

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