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.

72 lines
2.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
const int N = 510;
const int INF = 0x3f3f3f3f;
int n, m;
int g[N][N]; // 稠密图,邻接矩阵
int dis[N]; // 这个点到集合的距离
bool st[N]; // 是不是已经使用过
int res; // 最小生成树里面边的长度之和
// 普利姆算法求最小生成树
int prim() {
// 距离初始化无穷大,表示所有结点都在生成树之外
memset(dis, 0x3f, sizeof dis);
dis[1] = 0;
for (int i = 0; i < n; i++) { // 迭代n次
/*
1、找到集合外距离集合最近的点记为t,此时有两种情况进行猴子选大王:
1首次查找,此时还没有大王,那么,默认第一个找到的就是大王
2非首次查找,那么PK距离最小的成为大王
*/
int t = -1;
for (int j = 1; j <= n; j++)
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更新其它未加入到集合中点到集合的距离
for (int j = 1; j <= n; j++)
if (!st[j] && dis[j] > g[t][j])
dis[j] = g[t][j];
// 5、把t放到集合中
st[t] = true;
}
return res;
}
int main() {
cin >> n >> m;
// 所有点之间的距离初始化为正无穷,然后再读入所有边
memset(g, 0x3f, sizeof g);
// 读入数据
while (m--) {
int a, b, c;
cin >> a >> b >> c;
g[a][b] = g[b][a] = min(g[a][b], c);
// 允许重复,构建双向有向成为无向图,同时保留最小的
}
int t = prim(); // 普利姆算法
// 输出结果
if (t == INF) puts("impossible");
// 不存在生成树,比如所有点不连通的情况下
else
cout << t << endl; // 否则输出t
return 0;
}