티스토리 뷰

https://www.acmicpc.net/problem/1781

 

1781번: 컵라면

상욱 조교는 동호에게 N개의 문제를 주고서, 각각의 문제를 풀었을 때 컵라면을 몇 개 줄 것인지 제시 하였다. 하지만 동호의 찌를듯한 자신감에 소심한 상욱 조교는 각각의 문제에 대해 데드라

www.acmicpc.net

 

class MaxHeap {
  constructor() {
    this.heap = []
  }
  swap(a, b) {
    [this.heap[a], this.heap[b]] = [this.heap[b], this.heap[a]]
  }

  size() {
    return this.heap.length
  }

  push(value) {
    this.heap.push(value)
    let current = this.heap.length - 1
    let parent = Math.floor((current - 1) / 2)

    while (this.heap[parent] < value) {
      this.swap(parent, current)
      current = parent
      parent = Math.floor((current - 1) / 2)
    }
  }


  pop() {
    const last = this.heap.length - 1
    let current = 0
    this.swap(current, last)
    const value = this.heap.pop()

    while (current < last) {
      let left = current * 2 + 1
      let right = current * 2 + 2

      if (left >= last) {
        break
      } else if (right >= last) {
        if (this.heap[current] < this.heap[left]) {
          this.swap(current, left)
          current = left
        } else {
          break
        }
      } else {
        if (this.heap[left] > this.heap[current] || this.heap[right] > this.heap[current]) {
          let next = this.heap[left] > this.heap[right] ? left : right
          this.swap(current, next)
          current = next
        } else {
          break
        }
      }
    }
    return value
  }
}




const fs = require('fs');
const input = fs.readFileSync("./dev/stdin").toString().trim().split("\n").map(v => v.split(' ').map(Number))
const [N] = input.shift();
if (N == 0) {
  process.exit(console.log(0))
}

let answer = 0;
const problem = input.sort((a, b) => b[0] - a[0]);
let day = problem[0][0];
let pq = new MaxHeap();

for (let i = 0; i < N; i++) {
  if (day == problem[i][0]) {
    pq.push(problem[i][1])
  } else {
    while (problem[i][0] < day) {
      if (pq.size()) answer += pq.pop();
      day--;
    }
    pq.push(problem[i][1])
  }
}

while (day > 0) {
  if (pq.size()) answer += pq.pop();
  day--;
}

console.log(answer)
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
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
글 보관함