Skip to content

Commit f19daae

Browse files
committed
Feat: 힙 실버2 최소 힙
1 parent c53fdb3 commit f19daae

File tree

1 file changed

+111
-0
lines changed

1 file changed

+111
-0
lines changed
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
const local_input = `
2+
9
3+
0
4+
12345678
5+
1
6+
2
7+
0
8+
0
9+
0
10+
0
11+
32
12+
`;
13+
14+
const input = process.execArgv.includes("--stack-size=65536")
15+
? require("fs").readFileSync("dev/stdin").toString()
16+
: local_input;
17+
18+
const inputs = input
19+
.trim()
20+
.split("\n")
21+
.map((v) => Number(v));
22+
23+
const n = inputs[0];
24+
const arr = inputs.slice(1);
25+
26+
class MinHeap {
27+
constructor() {
28+
this.heap = [];
29+
}
30+
31+
insert(value) {
32+
this.heap.push(value);
33+
this.heapifyUp();
34+
}
35+
36+
heapifyUp() {
37+
let index = this.heap.length - 1;
38+
while (index > 0) {
39+
let parentIndex = Math.floor((index - 1) / 2);
40+
41+
if (this.heap[parentIndex] <= this.heap[index]) {
42+
break;
43+
}
44+
45+
[this.heap[parentIndex], this.heap[index]] = [
46+
this.heap[index],
47+
this.heap[parentIndex],
48+
];
49+
index = parentIndex;
50+
}
51+
}
52+
53+
extractMin() {
54+
const min = this.heap[0];
55+
const ok = this.heap.pop();
56+
if (this.size() !== 0) this.heap[0] = ok;
57+
this.heapifyDown();
58+
return min;
59+
}
60+
61+
heapifyDown(index = 0) {
62+
let leftChildIndex = 2 * index + 1;
63+
let rightChildIndex = 2 * index + 2;
64+
let smallest = index;
65+
66+
if (
67+
leftChildIndex < this.heap.length &&
68+
this.heap[leftChildIndex] < this.heap[smallest]
69+
) {
70+
smallest = leftChildIndex;
71+
}
72+
73+
if (
74+
rightChildIndex < this.heap.length &&
75+
this.heap[rightChildIndex] < this.heap[smallest]
76+
) {
77+
smallest = rightChildIndex;
78+
}
79+
80+
if (smallest !== index) {
81+
[this.heap[smallest], this.heap[index]] = [
82+
this.heap[index],
83+
this.heap[smallest],
84+
];
85+
this.heapifyDown(smallest);
86+
}
87+
}
88+
size() {
89+
return this.heap.length;
90+
}
91+
peek() {
92+
return this.heap[0];
93+
}
94+
}
95+
96+
const minHeap = new MinHeap();
97+
let result = "";
98+
99+
arr.forEach((v) => {
100+
// 0이면 최소힙에서 최솟값을 빼서 출력
101+
if (v === 0) {
102+
if (minHeap.size() === 0) result += 0 + "\n";
103+
else result += minHeap.extractMin() + "\n";
104+
} else {
105+
// 0이 아니면 최소힙에 삽입
106+
minHeap.insert(v);
107+
}
108+
});
109+
110+
// 정답 출력
111+
console.log(result);

0 commit comments

Comments
 (0)