AcWing 858. Prim算法求最小生成树

//稀疏图 
#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 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;//标记找过了
        //更新的到集合的距离,也就是拿找的最小的点到其他点的距离和之前的比较,取较小的
        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);
        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;
}

猜你喜欢

转载自www.cnblogs.com/QingyuYYYYY/p/11846430.html