You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
926 B
40 lines
926 B
#include <bits/stdc++.h>
|
|
using namespace std;
|
|
|
|
const int N = 110;
|
|
const int INF = 0x3f3f3f3f;
|
|
|
|
int n;
|
|
int g[N][N];
|
|
int dis[N];
|
|
bool st[N];
|
|
int res;
|
|
|
|
int prim() {
|
|
for (int i = 0; i < n; i++) { // 迭代n次
|
|
int t = -1;
|
|
for (int j = 1; j <= n; j++)
|
|
if (!st[j] && (t == -1 || dis[t] > dis[j])) t = j;
|
|
if (i && dis[t] == INF) return INF; // 非连通图,没有最小生成树
|
|
if (i) res += dis[t];
|
|
for (int j = 1; j <= n; j++)
|
|
if (!st[j] && g[t][j] < dis[j]) {
|
|
dis[j] = g[t][j];
|
|
}
|
|
st[t] = true;
|
|
}
|
|
return res;
|
|
}
|
|
|
|
int main() {
|
|
cin >> n;
|
|
// 初始化
|
|
memset(g, 0x3f, sizeof g);
|
|
memset(dis, 0x3f, sizeof dis);
|
|
|
|
for (int i = 1; i <= n; i++)
|
|
for (int j = 1; j <= n; j++)
|
|
cin >> g[i][j]; // 有向图
|
|
cout << prim() << endl;
|
|
return 0;
|
|
} |