문제
절댓값 힙은 다음과 같은 연산을 지원하는 자료구조이다.
- 배열에 정수 x (x ≠ 0)를 넣는다.
- 배열에서 절댓값이 가장 작은 값을 출력하고, 그 값을 배열에서 제거한다. 절댓값이 가장 작은 값이 여러개일 때는, 가장 작은 수를 출력하고, 그 값을 배열에서 제거한다.
프로그램은 처음에 비어있는 배열에서 시작하게 된다.
입력
첫째 줄에 연산의 개수 N(1≤N≤100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 0이 아니라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0이라면 배열에서 절댓값이 가장 작은 값을 출력하고 그 값을 배열에서 제거하는 경우이다. 입력되는 정수는 -231보다 크고, 231보다 작다.
출력
입력에서 0이 주어진 회수만큼 답을 출력한다. 만약 배열이 비어 있는 경우인데 절댓값이 가장 작은 값을 출력하라고 한 경우에는 0을 출력하면 된다.
예제 입력
18
1
-1
0
0
0
1
1
-1
-1
2
-2
0
0
0
0
0
0
0
예제 출력
-1
1
0
-1
-1
1
1
-2
2
0
소스 코드
const input = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n').map(Number);
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 (Math.abs(heap[idx]) < Math.abs(heap[parentIdx])) {
swap(idx, parentIdx);
idx = parentIdx;
} else if (Math.abs(heap[idx]) === Math.abs(heap[parentIdx])) {
if (heap[idx] < heap[parentIdx]) {
swap(idx, parentIdx);
idx = parentIdx;
} else {
break;
}
}
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) {
if (Math.abs(heap[idx * 2]) > Math.abs(heap[idx * 2 + 1])) {
childIdx = idx * 2 + 1;
}
else if (Math.abs(heap[idx * 2]) === Math.abs(heap[idx * 2 + 1])) {
if (heap[idx * 2] > heap[idx * 2 + 1]) {
childIdx = idx * 2 + 1;
}
}
}
}
if (Math.abs(heap[idx]) > Math.abs(heap[childIdx])) {
swap(idx, childIdx);
idx = childIdx;
} else if (Math.abs(heap[idx]) === Math.abs(heap[childIdx])) {
if (heap[idx] > heap[childIdx]) {
swap(idx, childIdx);
idx = childIdx;
} else {
break;
}
} 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] > 백준' 카테고리의 다른 글
[백준] 11659번 / 실버3 / 구간 합 구하기4 / Node.js (0) | 2021.10.12 |
---|---|
[백준] 11399번 / 실버3 / ATM / Node.js (0) | 2021.10.12 |
[백준] 11279번 / 실버2 / 최대 힙 / Node.js (0) | 2021.10.09 |
[백준] 10026번 / 골드5 / 적록색약 / Node.js (0) | 2021.10.04 |
[백준] 9461번 / 실버3 / 파도반 수열 / Node.js (0) | 2021.10.03 |