๐งถ 1. ํ์ ๊ฐ ์ถ๊ฐ : ๋ฐฐ์ด์ ๋ง์ง๋ง์ ๋ฃ๊ณ ๋ถ๋ชจ ์ธ๋ฑ์ค๋ ๋น๊ตํ๋ฉฐ ์๋ฆฌ๋ฅผ ์ฐพ๋๋ค. (bubbleUp)
2. ํ(MinHeap)์์ ๊ฐ์ฅ ์์ ๊ฐ ์ญ์ : ๋ฐฐ์ด์ ๋ง์ง๋ง ์์๋ฅผ ๋ฃจํธ ์๋ฆฌ์ ๋ฃ๊ณ ์ผ์ชฝ ์์๊ณผ ์ค๋ฅธ์ชฝ ์์๊ณผ ๋น๊ตํ๋ฉฐ ์๋ฆฌ๋ฅผ ์ฐพ๋๋ค. (bubbleDown)
๐งธ ์ด์ ํ์ ์ค์ค๋ก ๊ตฌํํ ์ ์๋ค!!
์ฝ๋
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split("\n").map(Number);
const N = input.shift();
class MinHeap {
constructor() {
this.heap = [];
}
swap(a, b) {
[this.heap[a], this.heap[b]] = [this.heap[b], this.heap[a]];
}
add(value) {
this.heap.push(value);
this.bubbleUp();
}
bubbleUp() {
let index = this.heap.length - 1;
let parentIndex = Math.floor((index - 1) / 2);
while (
this.heap[parentIndex] &&
this.heap[parentIndex] > this.heap[index]
) {
this.swap(parentIndex, index);
index = parentIndex;
parentIndex = Math.floor((index - 1) / 2);
}
}
remove() {
if (this.heap.length === 0) return 0;
if (this.heap.length === 1) return this.heap.pop();
let root = this.heap[0];
this.heap[0] = this.heap.pop();
this.bubbleDown();
return root;
}
bubbleDown() {
let index = 0;
let leftChild = index * 2 + 1;
let rightChild = index * 2 + 2;
while (
(this.heap[leftChild] && this.heap[leftChild] < this.heap[index]) ||
(this.heap[rightChild] && this.heap[rightChild] < this.heap[index])
) {
let min = leftChild;
if (this.heap[rightChild] && this.heap[leftChild] > this.heap[rightChild])
min = rightChild;
this.swap(min, index);
index = min;
leftChild = index * 2 + 1;
rightChild = index * 2 + 2;
}
}
}
const minHeap = new MinHeap();
let answer = "";
for (let i = 0; i < N; i++) {
if (input[i] === 0) answer += minHeap.remove() + "\n";
else minHeap.add(input[i]);
}
console.log(answer);