AcWing 858. Prim算法求最小生成树(Javascript)
原题链接
简单
作者:
cp777
,
2021-03-02 21:58:41
,
所有人可见
,
阅读 231
const INF = 0x3f3f3f3f;
const N = 510;
let res = 0;
let graph = [];
for (let i = 0; i < N; i++) graph[i] = new Array(N).fill(INF);
let dist = new Array(N).fill(INF);
let st = new Int32Array(N);
let prim = () => {
for (let i = 0; i < n; i++) {
let t = -1;
for (let j = 1; j <= n; j++) {
if (!st[j] && (t === -1 || dist[t] > dist[j])) t = j;
}
if (i && dist[t] === INF) return false;
if (i) res += dist[t];
st[t]++;
for (let j = 1; j <= n; j++)
dist[j] = Math.min(dist[j], graph[j][t]);
}
return true;
}
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];
} else if (lineIdx <= m) {
let arr = getInputNums(line);
let a = arr[0];
let b = arr[1];
let c = arr[2];
if (a !== b) graph[a][b] = graph[b][a] = Math.min(graph[a][b], c); //最小生成树中无环 无向图
if (lineIdx === m) {
let s = prim();
if (s) console.log(res);
else console.log('impossible');
}
}
});
});