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.

45 lines
1.3 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int n;
2 years ago
int g[N][N]; // 邻接矩阵,记录每两个点之间的距离
int dis[N]; // 每个点距离集合的最小长度
2 years ago
bool st[N]; // 是不是已经加入到集合中
int prim() {
// 初始化所有节点到集合的距离为正无穷
2 years ago
memset(dis, 0x3f, sizeof dis);
dis[1] = 0; // 1号节点到集合的距离为0
2 years ago
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++)
2 years ago
if (!st[j] && (t == -1 || dis[t] > dis[j])) // 第一次就是猴子选大王,赶鸭子上架
2 years ago
t = j;
2 years ago
// 最小生成树的距离和增加dis[t]
res += dis[t];
2 years ago
// t节点入集合
st[t] = true;
// 利用t拉近其它节点长度
2 years ago
for (int j = 1; j <= n; j++) dis[j] = min(dis[j], g[t][j]);
2 years ago
}
return res;
}
int main() {
2 years ago
cin >> n;
2 years ago
// 完全图,每两个点之间都有距离,不用考虑无解情况
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
2 years ago
cin >> g[i][j];
2 years ago
// 利用prim算法计算最小生成树
2 years ago
cout << prim() << endl;
2 years ago
return 0;
}