1. 程式人生 > 其它 >【樸素Prim】AcWing858.Prim演算法求最小生成樹

【樸素Prim】AcWing858.Prim演算法求最小生成樹

AcWing858.Prim演算法求最小生成樹

題解

Prim的思路就是每次找出距離最近的點,再用距離最近的點更新其他點使其變得更近,尋得n-1條邊成為最小生成樹

#include <iostream>
#include <cstring>
using namespace std;

const int N = 510, INF = 0x3f3f3f3f;

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

int prim()
{
    int res = 0;
    memset(dist, 0x3f, sizeof dist);
    for(int i = 0; i < n; ++i)
    {
        int t = -1;
        for(int j = 1; j <= n; ++j)
            if(!st[j] && (t == -1 || dist[j] < dist[t]) )
                t = j;
        st[t] = true;
        
        if(i) res += dist[t];
        if(i && dist[t] == INF) return INF;
        
        for(int j = 1; j <= n; ++j)
            dist[j] = min(dist[j], g[t][j]);
    }
    
    return res;
}

int main()
{
    cin >> n >> m;
    int a, b, c;
    memset(g, 0x3f, sizeof g);
    for(int i = 0; i < m; ++i)
    {
        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;
}