AcWing 851. spfa求最短路(Javascript)
原题链接
简单
作者:
cp777
,
2021-03-02 14:18:22
,
所有人可见
,
阅读 240
let INF = 0x3f3f3f3f;
let N = 100010;
let idx = 0;
let head = new Int32Array(N).fill(-1);
let next = [];
let edge = [];
let w = [];
let dist = new Int32Array(N).fill(INF);
let queue = [];
let st = new Int32Array(N);
let insert = (a, b, c) => {
edge[idx] = b;
w[idx] = c;
next[idx] = head[a];
head[a] = idx++;
}
let spfa = () => {
dist[1] = 0;
queue.push(1);
st[1] = true;
while (queue.length) {
let top = queue.shift();
st[top] = false;
for (let i = head[top]; i !== -1; i = next[i]) {
let point = edge[i];
if (dist[point] > dist[top] + w[i]) {
dist[point] = dist[top] + w[i];
if (!st[point]) {
queue.push(point);
st[point] = 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];
insert(a, b, c);
if (lineIdx === m) {
spfa();
if (dist[n] === INF) console.log('impossible');
else console.log(dist[n]);
}
}
});
});