티스토리 뷰

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

 

2109번: 순회강연

한 저명한 학자에게 n(0 ≤ n ≤ 10,000)개의 대학에서 강연 요청을 해 왔다. 각 대학에서는 d(1 ≤ d ≤ 10,000)일 안에 와서 강연을 해 주면 p(1 ≤ p ≤ 10,000)만큼의 강연료를 지불하겠다고 알려왔다.

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 lecture = input.sort((a, b) => b[1] - a[1]);
let day = lecture[0][1];
let pq = new MaxHeap();

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

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

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