|
| 1 | +class minHeap { |
| 2 | + constructor() { |
| 3 | + this.heap = []; |
| 4 | + this.heap.push([Number.MIN_SAFE_INTEGER, 0]); |
| 5 | + } |
| 6 | + insert([a, b]) { |
| 7 | + this.heap.push([a, b]); |
| 8 | + this.upheap(this.heap.length - 1); |
| 9 | + } |
| 10 | + upheap(pos) { |
| 11 | + let tmp = this.heap[pos]; |
| 12 | + while (tmp[1] < this.heap[parseInt(pos / 2)][1]) { |
| 13 | + this.heap[pos] = this.heap[parseInt(pos / 2)]; |
| 14 | + pos = parseInt(pos / 2); |
| 15 | + } |
| 16 | + this.heap[pos] = tmp; |
| 17 | + } |
| 18 | + get() { |
| 19 | + if (this.heap.length === 2) { |
| 20 | + return this.heap.pop(); |
| 21 | + } |
| 22 | + let res; |
| 23 | + res = this.heap[1]; |
| 24 | + this.heap[1] = this.heap.pop(); |
| 25 | + this.downheap(1, this.heap.length - 1); |
| 26 | + return res; |
| 27 | + } |
| 28 | + downheap(pos, len) { |
| 29 | + let tmp, i; |
| 30 | + tmp = this.heap[pos]; |
| 31 | + while (pos <= parseInt(len / 2)) { |
| 32 | + i = pos * 2; |
| 33 | + if (i < len && this.heap[i][1] < this.heap[i + 1][1]) i++; |
| 34 | + if (tmp[1] <= this.heap[i][1]) break; |
| 35 | + this.heap[pos] = this.heap[i]; |
| 36 | + pos = i; |
| 37 | + } |
| 38 | + this.heap[pos] = tmp; |
| 39 | + } |
| 40 | + size() { |
| 41 | + return this.heap.length - 1; |
| 42 | + } |
| 43 | + top() { |
| 44 | + return this.heap[1]; |
| 45 | + } |
| 46 | +} |
| 47 | +function solution(N, road, K) { |
| 48 | + let answer = 0; |
| 49 | + let minH = new minHeap(); |
| 50 | + let graph = Array.from(Array(N + 1), () => Array()); |
| 51 | + let dist = Array.from({ length: N + 1 }, () => 1000); |
| 52 | + for (let [a, b, c] of road) { |
| 53 | + graph[a].push([b, c]); |
| 54 | + } |
| 55 | + dist[1] = 0; |
| 56 | + minH.insert([1, 999]); |
| 57 | + minH.insert([1, 312]); |
| 58 | + minH.insert([1, 21]); |
| 59 | + minH.insert([2, 2]); |
| 60 | + minH.insert([1, 263]); |
| 61 | + console.log(minH); //4 |
| 62 | + minH.insert([1, 0]); |
| 63 | + while (minH.size() > 0) { |
| 64 | + let tmp = minH.get(); |
| 65 | + let now = tmp[0]; |
| 66 | + let nowCost = tmp[1]; |
| 67 | + if (nowCost > dist[now]) continue; |
| 68 | + for (let [next, cost] of graph[now]) { |
| 69 | + if (nowCost + cost < dist[next]) { |
| 70 | + dist[next] = nowCost + cost; |
| 71 | + minH.insert([next, dist[next]]); |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + if (dist[K] === 1000) answer = -1; |
| 76 | + else answer = dist[K]; |
| 77 | + return answer; |
| 78 | +} |
| 79 | +console.log( |
| 80 | + solution( |
| 81 | + 6, |
| 82 | + [ |
| 83 | + [1, 2, 12], |
| 84 | + [1, 3, 4], |
| 85 | + [2, 1, 2], |
| 86 | + [2, 3, 5], |
| 87 | + [2, 5, 5], |
| 88 | + [3, 4, 5], |
| 89 | + [4, 2, 2], |
| 90 | + [4, 5, 5], |
| 91 | + [6, 4, 5], |
| 92 | + ], |
| 93 | + 5 |
| 94 | + ) |
| 95 | +); |
0 commit comments