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.

44 lines
1.3 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int n;
int w[N][N]; // 邻接矩阵,记录每两个点之间的距离
int dist[N]; // 每个点距离集合的最小长度
bool st[N]; // 是不是已经加入到集合中
int prim() {
// 初始化所有节点到集合的距离为正无穷
memset(dist, 0x3f, sizeof dist);
dist[1] = 0; // 1号节点到集合的距离为0
int res = 0;
for (int i = 1; i <= n; i++) { // 迭代n次
int t = -1;
//(1)是不是第一次
//(2)如果不是第1次那么找出距离最近的那个点j
for (int j = 1; j <= n; j++)
if (!st[j] && (t == -1 || dist[t] > dist[j]))
t = j;
// 最小生成树的距离和增加dist[t]
res += dist[t];
// t节点入集合
st[t] = true;
// 利用t拉近其它节点长度
for (int j = 1; j <= n; j++) dist[j] = min(dist[j], w[t][j]);
}
return res;
}
int main() {
scanf("%d", &n);
// 完全图,每两个点之间都有距离,不用考虑无解情况
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
scanf("%d", &w[i][j]);
// 利用prim算法计算最小生成树
printf("%d\n", prim());
return 0;
}