最小生成树 : Prim
https://www.acwing.com/problem/content/1142/
\(一道裸题\)
\(最小生成树有两种算法:Prim \ 和\ Kruskal.\)
\(Prim:O(n^2)\)
\(Kruskal:O(mlogm)\)
\(如何证明算法正确(如何证明当前这条边一定可以被选)\ ?\)
\(假设不选当前边,最终得到了一棵树,然后将这条边加上,那么必然形成一个环,在这个环上,\\一定可以找出一条不小于当前边的边,那么把当前边替换,结果一定不会变差.\)
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 110;
int n;
int w[N][N];
int dist[N];
bool st[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;
res += dist[t];
st[t] = true;
for (int j = 1; j <= n; ++j) dist[j] = min(dist[j], w[t][j]);
}
return res;
}
int main() {
IO;
cin >> n;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
cin >> w[i][j];
cout << prim() << '\n';
return 0;
}