๐ŸŽฒ ๋ฐฑ์ค€ ์ตœ์†Œ ํž™ 1927๋ฒˆ [JS]

Jeongeunยท2024๋…„ 5์›” 5์ผ
0

๋ฐฑ์ค€

๋ชฉ๋ก ๋ณด๊ธฐ
186/188

๐Ÿงถ 1. ํž™์— ๊ฐ’ ์ถ”๊ฐ€ : ๋ฐฐ์—ด์˜ ๋งˆ์ง€๋ง‰์— ๋„ฃ๊ณ  ๋ถ€๋ชจ ์ธ๋ฑ์Šค๋ž‘ ๋น„๊ตํ•˜๋ฉฐ ์ž๋ฆฌ๋ฅผ ์ฐพ๋Š”๋‹ค. (bubbleUp)
2. ํž™(MinHeap)์—์„œ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’ ์‚ญ์ œ : ๋ฐฐ์—ด์˜ ๋งˆ์ง€๋ง‰ ์›์†Œ๋ฅผ ๋ฃจํŠธ ์ž๋ฆฌ์— ๋„ฃ๊ณ  ์™ผ์ชฝ ์ž์‹๊ณผ ์˜ค๋ฅธ์ชฝ ์ž์‹๊ณผ ๋น„๊ตํ•˜๋ฉฐ ์ž๋ฆฌ๋ฅผ ์ฐพ๋Š”๋‹ค. (bubbleDown)
๐Ÿงธ ์ด์ œ ํž™์„ ์Šค์Šค๋กœ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค!!

์ฝ”๋“œ

const fs = require('fs'); 
const input = fs.readFileSync('/dev/stdin').toString().trim().split("\n").map(Number);
const N = input.shift();

class MinHeap {
  constructor() {
    this.heap = [];
  }

  swap(a, b) {
    [this.heap[a], this.heap[b]] = [this.heap[b], this.heap[a]];
  }

  add(value) {
    this.heap.push(value);
    this.bubbleUp();
  }

  bubbleUp() {
    let index = this.heap.length - 1;
    let parentIndex = Math.floor((index - 1) / 2);

    while (
      this.heap[parentIndex] &&
      this.heap[parentIndex] > this.heap[index]
    ) {
      this.swap(parentIndex, index);
      index = parentIndex;
      parentIndex = Math.floor((index - 1) / 2);
    }
  }

  remove() {
    if (this.heap.length === 0) return 0;
    if (this.heap.length === 1) return this.heap.pop();

    let root = this.heap[0];
    this.heap[0] = this.heap.pop();
    this.bubbleDown();

    return root;
  }

  bubbleDown() {
    let index = 0;
    let leftChild = index * 2 + 1;
    let rightChild = index * 2 + 2;

    while (
      (this.heap[leftChild] && this.heap[leftChild] < this.heap[index]) ||
      (this.heap[rightChild] && this.heap[rightChild] < this.heap[index])
    ) {
      let min = leftChild;

      if (this.heap[rightChild] && this.heap[leftChild] > this.heap[rightChild])
        min = rightChild;

      this.swap(min, index);

      index = min;
      leftChild = index * 2 + 1;
      rightChild = index * 2 + 2;
    }
  }
}

const minHeap = new MinHeap();
let answer = "";

for (let i = 0; i < N; i++) {
  if (input[i] === 0) answer += minHeap.remove() + "\n";
  else minHeap.add(input[i]);
}

console.log(answer);

0๊ฐœ์˜ ๋Œ“๊ธ€