All problems

Problem 251

Job Sequencing with Deadlines

Medium · 20 pts · Array, Greedy, Sorting

Problem

You have N jobs. Each job takes exactly one unit of time, has a deadline D[i] and earns a profit P[i] if it finishes by its deadline. Time starts at 0, and only one job can run at a time, so a job with deadline d must be placed in one of the time slots 1 to d. Jobs that do not fit are skipped. Find the maximum total profit. Sort the jobs by profit, highest first, and place each one in the latest free slot at or before its deadline (keeping earlier slots open for other jobs). A union-find structure over slots finds the latest free slot quickly.

Input

First line: N. Next N lines: deadline and profit of a job.

Output

Print the maximum profit.

Constraints

1 <= N <= 100000; 1 <= D[i] <= N; 1 <= P[i] <= 1000000

Example input

4
4 20
1 10
1 40
1 30

Example output

60

Explanation

Three jobs have deadline 1, but only one of them can use slot 1, so take the most profitable one, worth 40. The job with deadline 4 and profit 20 fits in a later slot. The total profit is 40 + 20 = 60.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Minimum Number of Notes Next: Minimum Cost to Connect Ropes