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

目录

  • 1 基础知识
  • 2 模板
  • 3 工程化

1 基础知识

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

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

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

2 模板

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:求最小生成树。

#include 
#include 

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;
}

你可能感兴趣的:(Acwing,C++学习,算法,图论,数据结构)