|
| 1 | +class MinHeap { |
| 2 | + constructor() { |
| 3 | + this.heap = []; |
| 4 | + } |
| 5 | + |
| 6 | + push(node) { |
| 7 | + this.heap.push(node); |
| 8 | + this.bubbleUp(); |
| 9 | + } |
| 10 | + |
| 11 | + pop() { |
| 12 | + if (this.heap.length === 1) return this.heap.pop(); |
| 13 | + const min = this.heap[0]; |
| 14 | + this.heap[0] = this.heap.pop(); |
| 15 | + this.bubbleDown(); |
| 16 | + return min; |
| 17 | + } |
| 18 | + |
| 19 | + bubbleUp() { |
| 20 | + let i = this.heap.length - 1; |
| 21 | + while (i > 0) { |
| 22 | + const parent = Math.floor((i - 1) / 2); |
| 23 | + if (this.heap[parent][0] <= this.heap[i][0]) break; |
| 24 | + [this.heap[parent], this.heap[i]] = [this.heap[i], this.heap[parent]]; |
| 25 | + i = parent; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + bubbleDown() { |
| 30 | + let i = 0; |
| 31 | + const len = this.heap.length; |
| 32 | + while (true) { |
| 33 | + const left = 2 * i + 1; |
| 34 | + const right = 2 * i + 2; |
| 35 | + let smallest = i; |
| 36 | + |
| 37 | + if (left < len && this.heap[left][0] < this.heap[smallest][0]) |
| 38 | + smallest = left; |
| 39 | + if (right < len && this.heap[right][0] < this.heap[smallest][0]) |
| 40 | + smallest = right; |
| 41 | + if (smallest === i) break; |
| 42 | + |
| 43 | + [this.heap[i], this.heap[smallest]] = [this.heap[smallest], this.heap[i]]; |
| 44 | + i = smallest; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + size() { |
| 49 | + return this.heap.length; |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +const input = require('fs') |
| 54 | + .readFileSync(process.platform === 'linux' ? '/dev/stdin' : './input.txt') |
| 55 | + .toString() |
| 56 | + .trim() |
| 57 | + .split('\n') |
| 58 | + .map((el) => el.split(' ').map(Number)); |
| 59 | + |
| 60 | +function solution(input) { |
| 61 | + const [V, E] = input[0]; |
| 62 | + const K = input[1][0]; |
| 63 | + const edges = input.slice(2); |
| 64 | + |
| 65 | + const graph = Array.from({ length: V + 1 }, () => []); |
| 66 | + for (const [u, v, w] of edges) { |
| 67 | + graph[u].push([v, w]); |
| 68 | + } |
| 69 | + |
| 70 | + const ans = Array(V + 1).fill(Infinity); |
| 71 | + ans[K] = 0; |
| 72 | + |
| 73 | + const minHeap = new MinHeap(); |
| 74 | + minHeap.push([0, K]); |
| 75 | + |
| 76 | + while (minHeap.size()) { |
| 77 | + const [dis, node] = minHeap.pop(); |
| 78 | + if (dis > ans[node]) continue; |
| 79 | + |
| 80 | + for (const [v, w] of graph[node]) { |
| 81 | + if (ans[v] > dis + w) { |
| 82 | + ans[v] = dis + w; |
| 83 | + minHeap.push([ans[v], v]); |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + return ans |
| 89 | + .slice(1) |
| 90 | + .map((x) => (x === Infinity ? 'INF' : x)) |
| 91 | + .join('\n'); |
| 92 | +} |
| 93 | + |
| 94 | +console.log(solution(input)); |
0 commit comments