1. 程式人生 > 實用技巧 >Prim演算法求最小生成樹

Prim演算法求最小生成樹

#include <bits/stdc++.h>
using namespace std;

const int N = 550, M = 100010, INF = 0x3f3f3f3f;

int g[N][N], dist[N]; // dist存點到(最小生成樹的點集合)的最小距離
bool st[N];
int m, n;

int prim() {
    int res = 0;
    memset(dist,0x3f,sizeof dist);
    dist[1] = 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; } } st[t] = true; if(dist[t] == INF) return INF; // 找到這個距離最小生成樹最近的點為INF時,說明不聯通
res += dist[t]; 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; }