problems / 147

Ticket Triage Deadlines

medium intervals greedy heap sorting 1000 ms · 256 MB

Ticket Triage Deadlines

The support team's queue has n open tickets. Ticket i can't be worked on before day s_i, because that's when the customer sends the logs it needs, and it's only worth resolving if it's done by day e_i, its SLA deadline. Once the deadline passes, the ticket is escalated and taken off the on-call engineer's plate.

The on-call engineer resolves at most one ticket per day, and each ticket takes exactly one day. Ticket i is resolved if the engineer works on it on some integer day d with s_i ≤ d ≤ e_i.

Work out a schedule that resolves as many tickets as possible, and print how many that is.

Input

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

Each of the next n lines contains two integers s_i and e_i (1 ≤ s_i ≤ e_i ≤ 10^9): the first and last day ticket i can be resolved, inclusive.

Output

Print one integer: the maximum number of tickets that can be resolved.

Notes

In the first example the five tickets all fall within days 1 to 4, so at most four can be resolved. Four is achievable: on day 1 resolve ticket 3 [1, 2], on day 2 ticket 2 [2, 2], on day 3 ticket 1 [1, 3], and on day 4 ticket 5 [4, 4].

In the second example only days 5 and 6 work for the three tickets [5, 5], [5, 5] and [5, 6], so one of them is left over. Each of the other three tickets gets its own day.

Example 1

Input

5
1 3
2 2
1 2
3 4
4 4

Output

4

Example 2

Input

6
1000000000 1000000000
1 1000000000
5 5
5 5
5 6
999999999 1000000000

Output

5

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

Hint 1

With one ticket per day, suppose several tickets are open on the same day. Which one should the engineer work on, and why would picking it never cost you a ticket later?

Hint 2

Walk through the days in order, adding each ticket when its start day arrives. Days range up to 10^9, so you need to skip stretches where nothing is open rather than step through them one by one.

Hint 3

On each working day you need the open ticket with the earliest deadline, while new tickets keep arriving. Which data structure gives you that quickly, and what should happen to tickets whose deadline has already passed?

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

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