AcWing 859. Kruskal算法求最小生成树 (Javascript)
原题链接
简单
作者:
cp777
,
2021-03-03 10:14:39
,
所有人可见
,
阅读 205
const INF = 0x3f3f3f3f;
const N = 100010;
const M = 200010;
let edge = new Array(M);
//并查集
let parent = new Array(N);
//找根结点+路径压缩
let find = x => {
if (parent[x] !== x) parent[x] = find(parent[x]);
return parent[x];
}
let kruskal = () => {
edge.sort((a, b) => a[2] - b[2]); //按权值排序
let res = 0,
cnt = 0; //res生成树长度,cnt加入生成树的边数
//访问每一条边
for (let i = 0; i < m; i++) {
let e = edge[i];
let a = find(e[0]),
b = find(e[1]);
if (a !== b) { //ab不在一个集合中
res += e[2];
cnt++;
parent[a] = b; //加入集合
}
}
if (cnt < n - 1) return INF;
else return res;
}
let n = 0,
m = 0;
let buf = '';
process.stdin.on('readable', function () {
let chunk = process.stdin.read();
if (chunk) buf += chunk.toString();
});
let getInputNums = line => line.split(' ').filter(s => s !== '').map(x => parseInt(x));
let getInputStr = line => line.split(' ').filter(s => s !== '');
process.stdin.on('end', function () {
buf.split('\n').forEach(function (line, lineIdx) {
if (lineIdx === 0) {
n = getInputNums(line)[0];
m = getInputNums(line)[1];
for (let i = 1; i <= n; i++) parent[i] = i; //并查集初始化
} else if (lineIdx <= m) {
let arr = getInputNums(line);
let a = arr[0];
let b = arr[1];
let w = arr[2];
edge.push([a, b, w]);
if (lineIdx === m) {
let t = kruskal();
if (t === INF) console.log('impossible');
else console.log(t);
}
}
});
});