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.

69 lines
2.4 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
const int N = 510;
const int INF = 0x3f3f3f3f;
int n, m;
int g[N][N]; // 稠密图,邻接矩阵
2 years ago
int dis[N]; // 这个点到集合的距离
2 years ago
bool st[N]; // 是不是已经使用过
int res; // 最小生成树里面边的长度之和
2 years ago
// 普利姆算法求最小生成树
2 years ago
int prim() {
2 years ago
for (int i = 0; i < n; i++) { // 迭代n次
/*
1t,
1,
2,PK
*/
2 years ago
int t = -1;
for (int j = 1; j <= n; j++)
2 years ago
if (!st[j] && (t == -1 || dis[t] > dis[j])) t = j;
/*2、如果不是第一个点并且剩余的点距离集合的最小距离是INF说明现在没有点可以连通到生成树
INF
dist[t]=INF,
*/
if (i && dis[t] == INF) return INF;
// 3、同上这里也需要特判一下是不是第1个节点第一个节点不用加边权值其它的需要加
if (i) res += dis[t];
// 4、因为本轮选择的是结点t,那么用t更新其它未加入到集合中点到集合的距离
2 years ago
for (int j = 1; j <= n; j++)
2 years ago
if (!st[j] && dis[j] > g[t][j])
dis[j] = g[t][j];
// 5、把t放到集合中
st[t] = true;
2 years ago
}
return res;
}
int main() {
cin >> n >> m;
2 years ago
// 所有点之间的距离初始化为正无穷,然后再读入所有边
2 years ago
memset(g, 0x3f, sizeof g);
2 years ago
// 距离初始化无穷大,表示所有结点都在生成树之外
memset(dis, 0x3f, sizeof dis);
2 years ago
// 读入数据
while (m--) {
int a, b, c;
cin >> a >> b >> c;
g[a][b] = g[b][a] = min(g[a][b], c);
2 years ago
// 允许重复,构建双向有向成为无向图,同时保留最小的
2 years ago
}
2 years ago
int t = prim(); // 普利姆算法
// 输出结果
if (t == INF) puts("impossible");
// 不存在生成树,比如所有点不连通的情况下
2 years ago
else
2 years ago
cout << t << endl; // 否则输出t
2 years ago
return 0;
}