- 발행일
[99클럽] 99클럽 코테 스터디 18일차TIL + 힙
[99클럽] 99클럽 코테 스터디 18일차TIL + 힙
이 글은 네이버 블로그에 2025년 2월 12일에 올렸던 것을 그대로 옮겨온 것입니다.
오늘의 학습 키워드
공부한 내용 본인의 언어로 정리하기
오늘의 회고
어떤 문제가 있었고, 나는 어떤 시도를 했는지
어떻게 해결했는지
무엇을 새롭게 알았는지
내일 학습할 것은 무엇인지
비기너 크리스마스 선물 https://www.acmicpc.net/problem/14235
미들러 맥주 축제 https://www.acmicpc.net/problem/17503
챌린저 로봇 조종하기 https://www.acmicpc.net/problem/2169
const readline = require("readline");
class MaxHeap {
constructor() {
this.heap = [];
}
insert(value) {
this.heap.push(value);
this._heapifyUp();
}
extractMax() {
if (this.heap.length === 0) return -1;
if (this.heap.length === 1) return this.heap.pop();
const max = this.heap[0];
this.heap[0] = this.heap.pop();
this._heapifyDown();
return max;
}
_heapifyUp() {
let index = this.heap.length - 1;
while (index > 0) {
let parentIndex = Math.floor((index - 1) / 2);
if (this.heap[parentIndex] >= this.heap[index]) break;
[this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]];
index = parentIndex;
}
}
_heapifyDown() {
let index = 0;
const length = this.heap.length;
while (true) {
let leftChild = 2 * index + 1;
let rightChild = 2 * index + 2;
let largest = index;
if (leftChild < length && this.heap[leftChild] > this.heap[largest]) {
largest = leftChild;
}
if (rightChild < length && this.heap[rightChild] > this.heap[largest]) {
largest = rightChild;
}
if (largest === index) break;
[this.heap[index], this.heap[largest]] = [this.heap[largest], this.heap[index]];
index = largest;
}
}
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let n;
const maxHeap = new MaxHeap();
const results = [];
let firstInput = true;
rl.on("line", (line) => {
if (firstInput) {
n = parseInt(line.trim());
firstInput = false;
} else {
const input = line.trim().split(" ").map(Number);
const a = input[0];
if (a === 0) {
results.push(maxHeap.extractMax());
} else {
for (let i = 1; i <= a; i++) {
maxHeap.insert(input[i]);
}
}
}
}).on("close", () => {
console.log(results.join("\n"));
process.exit(0);
});
필수 해시태그: #99클럽 #코딩테스트준비 #개발자취업 #항해99 #TIL
