acwing 858 Prim algorithm for minimum spanning tree

Topic

Insert picture description here

answer

  1. Minimum spanning tree: A spanning tree of a connected graph with n nodes is a minimal connected subgraph of the original graph, and contains all n nodes in the original graph, and has the fewest edges that keep the graph connected. In fact, it is to make the graph connected with the smallest edge required to form a graph
  1. Primm algorithm O(n 2 ) Idea: We initialize all points to positive infinity, and then maintain a set, each time we find a point from outside the set to the closest point to the set, and then use this point to update other points to the set The distance (distance to the set: the minimum value of the distance from this point to all points in the set), the point found each time is the point of the minimum spanning tree

Code

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 510;
const int INF = 0x3f3f3f3f;

int n, m;
int g[N][N];
int dist[N];  //存储其他点到当前最小生成树的距离
bool st[N];  //存储每个点是否已经在生成树里面了

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;
        //用t更新其他点
        for (int j = 1; j <= n; j++) dist[j] = min(dist[j], g[t][j]);
    }

    return res;
}

int main() {
    
    

    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    memset(g, 0x3f, sizeof g);

    cin >> n >> m;
    for (int i = 1; i <= m; i++) {
    
    
        int a, b, c;
        cin >> a >> b >> c;
        g[a][b] = g[b][a] = min(g[a][b], c);
    }

    int res = prim();

    if (res == INF) cout << "impossible" << endl;
    else cout << res << endl;

    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/114456191