문제
널리 잘 알려진 자료구조 중 최소 힙이 있다. 최소 힙을 이용하여 다음과 같은 연산을 지원하는 프로그램을 작성하시오.
1.배열에 자연수 x를 넣는다.
2.배열에서 가장 작은 값을 출력하고, 그 값을 배열에서 제거한다.
프로그램은 처음에 비어있는 배열에서 시작하게 된다.
입력
첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0이라면 배열에서 가장 작은 값을 출력하고 그 값을 배열에서 제거하는 경우이다. x는 231보다 작은 자연수 또는 0이고, 음의 정수는 입력으로 주어지지 않는다.
출력
입력에서 0이 주어진 횟수만큼 답을 출력한다. 만약 배열이 비어 있는 경우인데 가장 작은 값을 출력하라고 한 경우에는 0을 출력하면 된다.
예제 입력
9
0
12345678
1
2
0
0
0
0
32
예제 출력
0
1
2
12345678
0
소스 코드
const input = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n').map(v => +v);
const N = input.shift();
const result = [];
const heap = new Array(100001);
let heapSize = 0;
const swap = (idx1, idx2) => {
let tmp = heap[idx1];
heap[idx1] = heap[idx2];
heap[idx2] = tmp;
}
// 상향식
const insert = (value) => {
heap[++heapSize] = value;
let idx = heapSize;
while (idx !== 1) {
let parentIdx = Math.floor(idx / 2)
if (heap[idx] < heap[parentIdx]) {
swap(idx, parentIdx);
idx = parentIdx;
} else {
break;
}
}
}
// 하향식
const getMin = () => {
if (!heapSize) return 0
let result = heap[1];
heap[1] = heap[heapSize];
heap[heapSize] = null;
heapSize--;
let idx = 1;
// 최소 heap 추출 후 heap 재구성
let childIdx;
while (idx <= heapSize) {
// 왼쪽 자식 노드 존재
if (idx * 2 <= heapSize) {
childIdx = idx * 2;
// 오른쪽 자식 노드 존재
if (idx * 2 + 1 <= heapSize) {
childIdx = heap[idx * 2] > heap[idx * 2 + 1] ? idx * 2 + 1 : childIdx;
}
}
if (heap[idx] > heap[childIdx]) {
swap(idx, childIdx);
idx = childIdx;
} else {
break;
}
}
return result
}
for (let i = 0; i < input.length; i++) {
if (input[i]) {
insert(input[i])
} else {
result.push(getMin());
}
}
console.log(result.join('\n'))
'알고리즘 공부[Javascript] > 백준' 카테고리의 다른 글
[백준] 7569번 / 실버1 / 토마토 / Node.js (0) | 2021.10.02 |
---|---|
[백준] 7576번 / 실버1 / 토마토 / Node.js (0) | 2021.10.02 |
[백준] 6064번 / 실버1 / 카잉달력 / Node.js (0) | 2021.09.28 |
[백준] 5525번 / 실버2 / IOIOI / Node.js (0) | 2021.09.24 |
[백준] 5430번 / 골드5 / AC / Node.js (0) | 2021.09.22 |