|
| 1 | +"use strict"; |
| 2 | + |
| 3 | +const fs = require("fs"); |
| 4 | +const input = fs |
| 5 | + .readFileSync(process.platform === "linux" ? "/dev/stdin" : "./input.txt") |
| 6 | + .toString() |
| 7 | + .trim() |
| 8 | + .split("\n"); |
| 9 | + |
| 10 | +const [N, M] = [+input[0], +input[1]]; |
| 11 | +const adj = Array.from({ length: N + 1 }, () => []); |
| 12 | + |
| 13 | +for (let i = 2; i < M + 2; i++) { |
| 14 | + const [u, v, w] = input[i].split(" ").map(Number); |
| 15 | + adj[u].push([v, w]); |
| 16 | +} |
| 17 | + |
| 18 | +const [startNode, endNode] = input[M + 2].split(" ").map(Number); |
| 19 | + |
| 20 | +class MinHeap { |
| 21 | + constructor() { |
| 22 | + this.heap = []; |
| 23 | + } |
| 24 | + |
| 25 | + push(val) { |
| 26 | + this.heap.push(val); |
| 27 | + this.bubbleUp(); |
| 28 | + } |
| 29 | + |
| 30 | + pop() { |
| 31 | + if (this.size() === 0) return null; |
| 32 | + if (this.size() === 1) return this.heap.pop(); |
| 33 | + const top = this.heap[0]; |
| 34 | + this.heap[0] = this.heap.pop(); |
| 35 | + this.bubbleDown(); |
| 36 | + return top; |
| 37 | + } |
| 38 | + |
| 39 | + size() { |
| 40 | + return this.heap.length; |
| 41 | + } |
| 42 | + |
| 43 | + bubbleUp() { |
| 44 | + let index = this.heap.length - 1; |
| 45 | + while (index > 0) { |
| 46 | + let parent = Math.floor((index - 1) / 2); |
| 47 | + if (this.heap[parent][1] > this.heap[index][1]) { |
| 48 | + [this.heap[parent], this.heap[index]] = [ |
| 49 | + this.heap[index], |
| 50 | + this.heap[parent], |
| 51 | + ]; |
| 52 | + index = parent; |
| 53 | + } else break; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + bubbleDown() { |
| 58 | + let index = 0; |
| 59 | + while (index * 2 + 1 < this.heap.length) { |
| 60 | + let left = index * 2 + 1, |
| 61 | + right = index * 2 + 2, |
| 62 | + smaller = left; |
| 63 | + if ( |
| 64 | + right < this.heap.length && |
| 65 | + this.heap[right][1] < this.heap[left][1] |
| 66 | + ) { |
| 67 | + smaller = right; |
| 68 | + } |
| 69 | + if (this.heap[index][1] <= this.heap[smaller][1]) break; |
| 70 | + [this.heap[index], this.heap[smaller]] = [ |
| 71 | + this.heap[smaller], |
| 72 | + this.heap[index], |
| 73 | + ]; |
| 74 | + index = smaller; |
| 75 | + } |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +function dijkstra(start) { |
| 80 | + const dist = Array(N + 1).fill(Infinity); |
| 81 | + const pq = new MinHeap(); |
| 82 | + |
| 83 | + dist[start] = 0; |
| 84 | + pq.push([start, 0]); |
| 85 | + |
| 86 | + while (pq.size() > 0) { |
| 87 | + const [curr, d] = pq.pop(); |
| 88 | + if (dist[curr] < d) continue; |
| 89 | + |
| 90 | + for (const [next, weight] of adj[curr]) { |
| 91 | + const nextDist = d + weight; |
| 92 | + if (nextDist < dist[next]) { |
| 93 | + dist[next] = nextDist; |
| 94 | + pq.push([next, nextDist]); |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + return dist; |
| 99 | +} |
| 100 | + |
| 101 | +const result = dijkstra(startNode); |
| 102 | +console.log(result[endNode]); |
0 commit comments