티스토리 뷰
https://www.acmicpc.net/problem/11279
11279번: 최대 힙
첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가
www.acmicpc.net
const fs = require('fs');
const [_, ...input] = fs.readFileSync("./dev/stdin").toString().trim().split("\n");
const num = input.map(v => +v);
class MaxHeap {
constructor() {
this.heap = [];
}
empty() {
if (this.heap.length == 0) {
return true;
}
return false;
}
insert(value) {
this.heap.push(value);
this.bubbleUp();
}
bubbleUp() {
let currentIndex = this.heap.length - 1;
while (currentIndex > 0) {
const parentIndex = Math.floor((currentIndex - 1) / 2);
if (this.heap[parentIndex] >= this.heap[currentIndex]) break;
[this.heap[currentIndex], this.heap[parentIndex]] = [
this.heap[parentIndex],
this.heap[currentIndex],
];
currentIndex = parentIndex;
}
}
extractMax() {
if (this.heap.length == 1) {
return this.heap.pop();
}
const max = this.heap[0];
this.heap[0] = this.heap.pop();
this.sinkDown(0);
return max;
}
sinkDown(index) {
const leftIndex = 2 * index + 1;
const rightIndex = 2 * index + 2;
const length = this.heap.length;
let largestIndex = index;
if (leftIndex < length && this.heap[leftIndex] > this.heap[largestIndex]) {
largestIndex = leftIndex;
}
if (rightIndex < length && this.heap[rightIndex] > this.heap[largestIndex]) {
largestIndex = rightIndex;
}
if (largestIndex !== index) {
[this.heap[index], this.heap[largestIndex]] = [this.heap[largestIndex], this.heap[index]]
[this.heap[index], this.heap[largestIndex]] = [this.heap[largestIndex], this.heap[index]]
this.sinkDown(largestIndex);
}
}
}
const answer = [];
const maxHeap = new MaxHeap();
num.forEach(v => {
if (v == 0) {
if (maxHeap.empty()) {
answer.push(0);
} else {
answer.push(maxHeap.extractMax());
}
} else {
maxHeap.insert(v);
}
})
console.log(answer.join('\n'));
728x90
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 11286번 : 절댓값 힙 (0) | 2021.09.16 |
---|---|
Node.js) 백준 1927번 : 최소 힙 (0) | 2021.09.16 |
Node.js)백준 2110번 : 공유기 설치 (0) | 2021.09.15 |
Node.js)백준 2805번 : 나무 자르기 (1) | 2021.09.14 |
Node.js) 백준 1654번 : 랜선 자르기 ★ (0) | 2021.09.14 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 롱베케이션
- 투포인터
- MySQL
- 최소공통조상
- 은둔청년체험
- 서버개발
- 그래프
- 면접비
- 면접질문
- 투포인터 연습
- 개발자면접
- DB 생성
- create databases;
- 다이나믹프로그래밍
- MOD
- create db
- 다이나밍프로그래밍
- 로드나인
- BFS
- 동적프로그래밍
- node.js
- 서버점검
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함