|
|
|
@ -161,7 +161,9 @@ int prim() {
|
|
|
|
|
if (i) res += dis[t];
|
|
|
|
|
|
|
|
|
|
// 4、因为本轮选择的是结点t,那么用t更新其它未加入到集合中点到集合的距离
|
|
|
|
|
for (int j = 1; j <= n; j++) dis[j] = min(dis[j], g[t][j]);
|
|
|
|
|
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;
|
|
|
|
@ -203,53 +205,49 @@ 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]; //前驱结点
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 功能:普利姆算法求最小生成树
|
|
|
|
|
* @return
|
|
|
|
|
*/
|
|
|
|
|
int g[N][N]; // 稠密图,邻接矩阵
|
|
|
|
|
int dis[N]; // 这个点到集合的距离
|
|
|
|
|
bool st[N]; // 是不是已经使用过
|
|
|
|
|
int res; // 最小生成树里面边的长度之和
|
|
|
|
|
int pre[N]; // 前驱结点
|
|
|
|
|
|
|
|
|
|
// 普利姆算法求最小生成树
|
|
|
|
|
int prim() {
|
|
|
|
|
//迭代n次
|
|
|
|
|
for (int i = 0; i < n; i++) {
|
|
|
|
|
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];
|
|
|
|
|
if (i && dis[t] == INF) return INF; // 非连通图,没有最小生成树
|
|
|
|
|
if (i) res += dis[t];
|
|
|
|
|
for (int j = 1; j <= n; j++)
|
|
|
|
|
if (!st[j]) {
|
|
|
|
|
if (g[t][j] < dis[j]) {
|
|
|
|
|
dis[j] = g[t][j];
|
|
|
|
|
pre[j] = t;//记录是由谁转移而来
|
|
|
|
|
}
|
|
|
|
|
if (!st[j] && g[t][j] < dis[j]) {
|
|
|
|
|
dis[j] = g[t][j];
|
|
|
|
|
pre[j] = t; // 记录是由谁转移而来
|
|
|
|
|
}
|
|
|
|
|
st[t] = 1;
|
|
|
|
|
st[t] = true;
|
|
|
|
|
}
|
|
|
|
|
return res;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
|
cin >> n >> m;
|
|
|
|
|
memset(g, 0x3f, sizeof g);
|
|
|
|
|
memset(dist, 0x3f, sizeof dist);
|
|
|
|
|
memset(pre, -1, sizeof pre);
|
|
|
|
|
//读入数据
|
|
|
|
|
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 printf("%d\n", t);
|
|
|
|
|
if (t == INF)
|
|
|
|
|
puts("impossible");
|
|
|
|
|
else
|
|
|
|
|
cout << t << endl;
|
|
|
|
|
|
|
|
|
|
//输出前驱结点
|
|
|
|
|
// 输出前驱结点
|
|
|
|
|
for (int i = 1; i <= n; i++) printf("%d ", pre[i]);
|
|
|
|
|
return 0;
|
|
|
|
|
}
|
|
|
|
|