problems / 156

Weighted Interval Scheduling

medium dp binary-search sorting intervals 1000 ms · 256 MB

Weighted Interval Scheduling

You are given n jobs. Job i occupies the half-open time interval [s_i, e_i) and pays a profit of p_i if it is done.

A single machine can work on at most one job at a time, so a chosen set of jobs must be pairwise non-overlapping. Because the intervals are half-open, two jobs that only touch (one ends at the exact moment the other starts, e_i = s_j) are compatible.

Choose a set of pairwise non-overlapping jobs with the largest total profit. The empty set is allowed.

Input

The first line contains an integer n (1 ≤ n ≤ 2·10^5), the number of jobs.

Each of the next n lines contains three integers s_i, e_i, p_i (0 ≤ s_i < e_i ≤ 10^9, 1 ≤ p_i ≤ 10^9): the start, the end and the profit of job i. Several jobs may have identical intervals.

Output

Print one integer: the maximum total profit. It may not fit in a 32-bit integer.

Notes

In the first example, the best choice is the jobs [1, 3), [3, 6) and [6, 9) with profit 5 + 6 + 4 = 15. They touch at times 3 and 6, which is allowed. The single job [2, 8) pays only 12.

In the second example, every job overlaps with every other, so only one job can be taken. The most profitable one pays 10.

Example 1

Input

5
1 3 5
2 8 12
3 6 6
6 9 4
4 7 3

Output

15

Example 2

Input

4
0 10 7
5 15 10
5 12 3
1 6 2

Output

10

Hints · reveal one at a time if you're stuck

Hint 1

Taking the most profitable job first, or the job that ends earliest, fails on small cases. Which order of the jobs makes it natural to decide, job by job, whether to take it?

Hint 2

Sort the jobs by end time and let the best profit for the first i jobs be the value of a DP. When you take job i, the other jobs you can combine with it are exactly the ones ending by its start time, and in sorted order those form a prefix you can find with a binary search.

Hint 3

Jobs that only touch are compatible, so a job ending exactly at the start of job i must count. Use profits in 64-bit integers, since the total can exceed 2·10^14.

report an issue Prefer your own editor? sooks prep 156 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.