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.

55 lines
1.3 KiB

#include <bits/stdc++.h>
using namespace std;
const int N = 510;
const int INF = 0x3f3f3f3f;
int n, m;
int g[N][N]; // 稠密图,邻接矩阵
int dist[N]; // 这个点到集合的距离
bool st[N]; // 是不是已经使用过
int res; // 最小生成树里面边的长度之和
/**
* 功能:普利姆算法求最小生成树
* @return
*/
int prim() {
// 迭代n次
for (int i = 0; i < n; i++) {
// 找出距离集合最小的点
int t = -1;
for (int j = 1; j <= n; j++)
if (!st[j] && (t == -1 || dist[t] > dist[j])) t = j;
// 如果找不到距离最小的点
if (i && dist[t] == INF) return INF;
// 累加最小生成树的长度
if (i) res += dist[t];
// 利用找到的t更新其它的点
for (int j = 1; j <= n; j++)
if (!st[j] && g[t][j] < dist[j])
dist[j] = g[t][j];
// 标识t点已在集合内
st[t] = 1;
}
return res;
}
int main() {
cin >> n >> m;
memset(g, 0x3f, sizeof g);
memset(dist, 0x3f, sizeof dist);
// 读入数据
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
printf("%d\n", t);
return 0;
}