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.
53 lines
1.4 KiB
53 lines
1.4 KiB
#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 pre[N]; // 前驱结点
|
|
|
|
// 普利姆算法求最小生成树
|
|
int prim() {
|
|
for (int i = 0; i < n; i++) { // 迭代n次
|
|
int t = -1;
|
|
for (int j = 1; j <= n; j++)
|
|
if (!st[j] && (t == -1 || dis[t] > dis[j])) t = j;
|
|
if (i && dis[t] == INF) return INF; // 非连通图,没有最小生成树
|
|
if (i) res += dis[t];
|
|
for (int j = 1; j <= n; j++)
|
|
if (!st[j] && g[t][j] < dis[j]) {
|
|
dis[j] = g[t][j];
|
|
pre[j] = t; // 记录是由谁转移而来
|
|
}
|
|
st[t] = true;
|
|
}
|
|
return res;
|
|
}
|
|
|
|
int main() {
|
|
cin >> n >> m;
|
|
memset(g, 0x3f, sizeof g);
|
|
memset(dis, 0x3f, sizeof dis);
|
|
memset(pre, -1, sizeof pre); // 记录前驱路径
|
|
|
|
// 读入数据
|
|
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;
|
|
|
|
// 输出前驱结点
|
|
for (int i = 1; i <= n; i++) printf("%d ", pre[i]);
|
|
return 0;
|
|
} |