acwing算法基础之搜索与图论--prim算法

目录

  • [1 基础知识](#1 基础知识)
  • [2 模板](#2 模板)
  • [3 工程化](#3 工程化)

1 基础知识

朴素版prim算法的关键步骤:

  1. 初始化距离数组dist,将其内的所有元素都设为正无穷大。
  2. 定义集合S,表示生成树。
  3. 循环n次:找到不在集合S中且距离集合S最近的结点t,用它去更新剩余结点到集合S的距离。
  4. 最小生成树建立完毕,边长之和等于每次的dt之和。

朴素版prim算法的时间复杂度为O(n^2),它用来解决稠密图的最小生成树问题。

2 模板

cpp 复制代码
int n;      // n表示点数
int g[N][N];        // 邻接矩阵,存储所有边
int dist[N];        // 存储其他点到当前最小生成树的距离
bool st[N];     // 存储每个点是否已经在生成树中


// 如果图不连通,则返回INF(值是0x3f3f3f3f), 否则返回最小生成树的树边权重之和
int prim()
{
    memset(dist, 0x3f, sizeof dist);

    int res = 0;
    for (int i = 0; i < n; i ++ )
    {
        int t = -1;
        for (int j = 1; j <= n; j ++ )
            if (!st[j] && (t == -1 || dist[t] > dist[j]))
                t = j;

        if (i && dist[t] == INF) return INF;

        if (i) res += dist[t];
        st[t] = true;

        for (int j = 1; j <= n; j ++ ) dist[j] = min(dist[j], g[t][j]);
    }

    return res;
}

3 工程化

题目1:求最小生成树。

cpp 复制代码
#include <iostream>
#include <cstring>

using namespace std;

const int N = 510;
int g[N][N];
int d[N];
bool st[N];
int n, m;

void prim() {
    memset(d, 0x3f, sizeof d);
    
    int res = 0;
    for (int i = 0; i < n; ++i) {//n次循环
        //找到不在集合S且距离集合S最小的结点
        int t = -1;
        for (int j = 1; j <= n; ++j) {
            if (!st[j] && (t == -1 || d[t] > d[j])) {
                t = j;
            }
        }
        
        if (i && d[t] == 0x3f3f3f3f) {
            cout << "impossible" << endl;
            return;
        }
        
        st[t] = true;
        if (i) res += d[t];
        
        //用t去更新其它结点
        for (int j = 1; j <= n; ++j) {
            if (d[j] > g[t][j]) {
                d[j] = g[t][j];
            }
        }
    }
    
    cout << res << endl;
    return;
}

int main() {
    cin >> n >> m;
    
    memset(g, 0x3f, sizeof g);
    int a, b, c;
    while (m--) {
        cin >> a >> b >> c;
        g[a][b] = min(g[a][b], c);
        g[b][a] = min(g[b][a], c);
    }
    
    prim();
    
    return 0;
}
相关推荐
To_OC2 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
旖-旎3 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
To_OC4 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
delishcomcn5 小时前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹5 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试
雪碧聊技术5 小时前
力扣 LCR 091. 粉刷房子 —— 动态规划入门详解
算法·动态规划
延凡科技7 小时前
多场景落地复盘:端边云架构无人机智能巡检系统设计与实践
大数据·数据结构·人工智能·科技·架构·无人机·能源
CV-Climber8 小时前
检索技术的实际应用
人工智能·算法
hhzz8 小时前
Tiger AI Platform平台中增加人脸识别功能
图像处理·人工智能·算法·计算机视觉·大模型