洛谷P1546 最短网络 Agri-Net 题解 最小生成树/Prim算法

题目链接:https://www.luogu.com.cn/problem/P1546

题目大意:

给你一个邻接矩阵,求它的最小生成树。

解题思路:

因为是邻接矩阵,用Prim算法求最小生成树写起来比较方便。

实现代码如下:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 110;
int n, g[maxn][maxn], cost[maxn], ans;
bool vis[maxn];
int main() {
    cin >> n;
    for (int i = 0; i < n; i ++)
        for (int j = 0; j < n; j ++)
            cin >> g[i][j];
    memset(cost, -1, sizeof(cost));
    cost[0] = 0;
    for (int i = 0; i < n; i ++) {
        int id = -1;
        for (int j = 0; j < n; j ++)
            if (!vis[j] && cost[j] != -1 && (id == -1 || cost[id] > cost[j]))
                id = j;
        vis[id] = true;
        ans += cost[id];
        for (int j = 0; j < n; j ++)
            if (!vis[j] && (cost[j] == -1 || g[id][j] < cost[j])) cost[j] = g[id][j];
    }
    cout << ans << endl;
    return 0;
}