考察最小生成树,只要一个Prim算法即可
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 105;
const int INF = 10e5+10;
int cost[maxn][maxn];
int mincost[maxn];
bool used[maxn];
int prim(int v) {
for (int i = 0; i < v; i++) {
mincost[i] = INF;
used[i] = false;
}
mincost[0] = 0;
int res = 0;
while (true) {
int u = -1;
for (int i = 0; i < v; i++) {
if (!used[i] && (u == -1 || mincost[i] < mincost[u]))
u = i;
}
if (u == -1) {
break;
}
used[u] = true;
res += mincost[u];
for (int i = 0; i < v; i++) {
mincost[i] = min(mincost[i], cost[u][i]);
}
}
return res;
}
int main(int argc, char const *argv[]) {
int n;
while (scanf("%d", &n) == 1) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &cost[i][j]);
}
}
int ans = prim(n);
printf("%d\n", ans);
}
return 0;
}