seunghyun Note
최대힙 본문
728x90
반응형
링크 : https://www.acmicpc.net/problem/11279
문제 풀이
힙을 복습해보자!
2024.02.23 - [코딩테스트/코테를 위한 알고리즘 & 자료구조 정리] - Binary Heaps with JS
// const input = require("fs")
// .readFileSync("/dev/stdin")
// .toString()
// .trim()
// .split("\n");
//
const input = require("fs")
.readFileSync("/dev/stdin")
.toString()
.trim()
.split("\n")
.map(Number);
class MinBinaryHeap {
constructor() {
this.values = [];
}
insert(element) {
this.values.push(element);
this.bubbleDown();
}
bubbleDown() {
let idx = this.values.length - 1;
const element = this.values[idx];
while (idx > 0) {
let parentIdx = Math.floor((idx - 1) / 2);
let parent = this.values[parentIdx];
if (element <= parent) break;
this.values[parentIdx] = element;
this.values[idx] = parent;
idx = parentIdx;
}
}
sinkUp() {
let idx = 0;
const length = this.values.length;
const element = this.values[0];
while (true) {
let leftChildIdx = 2 * idx + 1;
let rightChildIdx = 2 * idx + 2;
let leftChild, rightChild;
let swap = null;
if (leftChildIdx < length) {
leftChild = this.values[leftChildIdx];
if (leftChild > element) {
swap = leftChildIdx;
}
}
if (rightChildIdx < length) {
rightChild = this.values[rightChildIdx];
if (
(swap === null && rightChild > element) ||
(swap !== null && rightChild > leftChild)
) {
swap = rightChildIdx;
}
}
if (swap === null) break;
this.values[idx] = this.values[swap];
this.values[swap] = element;
idx = swap;
}
}
extractMin() {
const min = this.values[0];
const end = this.values.pop();
if (this.values.length > 0) {
this.values[0] = end;
this.sinkUp();
}
return min === undefined ? 0 : min;
}
}
let n = input[0];
let result = "";
let heap = new MinBinaryHeap();
for (let i = 1; i < input.length; i++) {
if (input[i] === 0) result = result + heap.extractMin() + "\n";
else heap.insert(input[i]);
}
console.log(result);
728x90
반응형
'코딩테스트 > 백준' 카테고리의 다른 글
백준 1181 : 단어 정렬 (0) | 2024.03.06 |
---|---|
[백준] 1991번 : 트리 순회 with JS (1) | 2024.02.12 |
[백준] 1316번 : 그룹 단어 체커 with JS (0) | 2024.01.25 |
[백준] 28279번 : 덱 2 with JS (0) | 2024.01.25 |
[백준] 11866번 : 요세푸스 문제 0 with JS (1) | 2024.01.24 |