seunghyun Note

최대힙 본문

코딩테스트/백준

최대힙

승숭슝현 2024. 2. 26. 15:15
728x90
반응형

링크 : https://www.acmicpc.net/problem/11279

 

11279번: 최대 힙

첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0

www.acmicpc.net

문제 풀이

 

힙을 복습해보자!

2024.02.23 - [코딩테스트/코테를 위한 알고리즘 & 자료구조 정리] - Binary Heaps with JS

 

Binary Heaps with JS

단일 연결 리스트 이중 연결 리스트 스택 & 큐 (배열로 하는 방법은 숙지했음! linked list로 구현해 보기) 이진 검색 트리 트리 순회 (bfs,dfs) 이진 힙 해시 테이블 (사용해 봤지만 복습) 그래프, 그래

cojjangsh.tistory.com

 

// 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
반응형