858. Prim算法求最小生成树

prim最小生成树:维护集合外所有点到集合的最小距离,每次找集合外的离集合最近的点k,并用k点更新集合到集合外所有点的距离最小值

#include<iostream>
#include<cstring>

using namespace std;

const int N = 510, INF = 0x3f3f3f3f;

int dist[N];
int g[N][N];
int st[N];
int n, m;

int prim(){
    int res = 0;
    
    for(int i = 0; i < n; i ++){
        int k = -1;
        for(int j = 1; j <= n; j ++)
            if(st[j] == 0 && (k == -1 || dist[j] < dist[k]))
                k = j;
        
        if(i && dist[k] == INF) return INF;
        st[k] = 1;
        
        for(int j = 1; j <= n; j ++)
            if(st[j] == 0)
                dist[j] = min(dist[j], g[k][j]); // 注意是更新集合外的点到集合的最短距离
        
        if(i) res += dist[k];
    }
    
    return res;
}

int main(){
    memset(dist, 0x3f, sizeof dist);
    memset(g, 0x3f, sizeof g);
    
    cin >> n >> m;
    while(m --){
        int a, b, w;
        
        cin >> a >> b >> w;
        g[a][b] = g[b][a] = min(g[a][b], w);
    }
    
    int k = prim();
    if(k == INF) puts("impossible");
    else cout << k << endl;
    return 0;
}
posted @ 2020-08-31 16:21  yys_c  阅读(147)  评论(0编辑  收藏  举报