#C1232. Maximum Total Reward

    ID: 41734 Type: Default 1000ms 256MiB

Maximum Total Reward

Maximum Total Reward

You are given n tasks where each task is represented by two integers: its deadline and its reward. Each task takes exactly one unit of time and only one task can be completed at a time.

The goal is to schedule a subset of the tasks in order to maximize the total reward. Note that, for any task, if it is completed after its deadline, it does not contribute to the total reward.

An optimal strategy is to process tasks in the order of increasing deadlines while always keeping the most rewarding tasks that can be accommodated. This greedy method can be efficiently implemented with a min-heap. In particular, whenever the number of scheduled tasks exceeds the current task's deadline, remove the task with the smallest reward. The maximum total reward is the sum of the rewards of the tasks that remain scheduled.

The mathematical idea can be summarized as follows: if we let \( H \) be the min-heap storing the rewards of scheduled tasks, for each task with deadline \( d_i \) and reward \( r_i \), we execute:

\[ \text{push}(r_i) \quad \text{into } H, \quad \text{if } |H| > d_i \text{ then remove the smallest reward from } H. \]

Finally, the answer is \( \sum_{r \in H} r \).

inputFormat

The first line contains an integer n (1 ≤ n ≤ 105), the number of tasks.

Each of the next n lines contains two space-separated integers d and r representing the task's deadline and reward respectively.

outputFormat

Output a single integer — the maximum total reward that can be obtained by optimally scheduling the tasks.

## sample
5
2 50
2 10
1 20
3 30
2 40
120