Skip to content

Commit 3d084d9

Browse files
committed
106차 1번 문제풀이
1 parent 0b54ae2 commit 3d084d9

1 file changed

Lines changed: 98 additions & 0 deletions

File tree

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
const input = require("fs")
2+
.readFileSync(
3+
process.platform === "linux"
4+
? "/dev/stdin"
5+
: require("path").join(__dirname, "input.txt"),
6+
"utf8"
7+
)
8+
.toString()
9+
.trim()
10+
.split("\n");
11+
12+
function solution(input) {
13+
const [n, m] = input[0].split(" ").map(Number);
14+
const map = Array.from({ length: n + 1 }, () => []);
15+
16+
for (let i = 1; i <= m; i++) {
17+
const [a, b, cost] = input[i].split(" ").map(Number);
18+
map[a].push([b, cost]);
19+
map[b].push([a, cost]);
20+
}
21+
22+
const distance = Array(n + 1).fill(Infinity);
23+
distance[1] = 0;
24+
25+
const heap = new MinHeap();
26+
heap.push([0, 1]);
27+
28+
while (!heap.isEmpty()) {
29+
const [curCost, curNode] = heap.pop();
30+
31+
if (distance[curNode] < curCost) continue;
32+
33+
for (let [next, nextCost] of map[curNode]) {
34+
const newCost = curCost + nextCost;
35+
if (newCost < distance[next]) {
36+
distance[next] = newCost;
37+
heap.push([newCost, next]);
38+
}
39+
}
40+
}
41+
42+
return distance[n];
43+
}
44+
45+
class MinHeap {
46+
constructor() {
47+
this.heap = [];
48+
}
49+
50+
push(value) {
51+
this.heap.push(value);
52+
let i = this.heap.length - 1;
53+
while (i > 0) {
54+
const parent = Math.floor((i - 1) / 2);
55+
if (this.heap[parent][0] <= this.heap[i][0]) break;
56+
[this.heap[parent], this.heap[i]] = [this.heap[i], this.heap[parent]];
57+
i = parent;
58+
}
59+
}
60+
61+
pop() {
62+
if (this.heap.length === 1) return this.heap.pop();
63+
const top = this.heap[0];
64+
this.heap[0] = this.heap.pop();
65+
66+
let i = 0;
67+
while (true) {
68+
let left = i * 2 + 1;
69+
let right = i * 2 + 2;
70+
let smallest = i;
71+
72+
if (
73+
left < this.heap.length &&
74+
this.heap[left][0] < this.heap[smallest][0]
75+
) {
76+
smallest = left;
77+
}
78+
if (
79+
right < this.heap.length &&
80+
this.heap[right][0] < this.heap[smallest][0]
81+
) {
82+
smallest = right;
83+
}
84+
if (smallest === i) break;
85+
86+
[this.heap[i], this.heap[smallest]] = [this.heap[smallest], this.heap[i]];
87+
i = smallest;
88+
}
89+
90+
return top;
91+
}
92+
93+
isEmpty() {
94+
return this.heap.length === 0;
95+
}
96+
}
97+
98+
console.log(solution(input));

0 commit comments

Comments
 (0)