problems / 124

The Party Photographer

medium intervals greedy sorting 1000 ms · 256 MB

The Party Photographer

Alice has been hired to photograph Bob's birthday party. The client has one demand: every guest must appear in at least one photo. Film is expensive, so Alice wants to take as few photos as possible.

Guest i arrives at time a_i and leaves at time b_i, and is at the party during the whole closed time range from a_i to b_i, including both of those instants. Alice can take a photo at any instant t (not necessarily an integer), and the photo captures every guest who is at the party at instant t. In particular, a guest who arrives at the exact instant another guest leaves is at the party at the same moment as that guest, so one photo taken at that instant captures both. Photos take no time, and any number of photos may be taken, at any instants.

Find the minimum number of photos Alice needs so that every guest appears in at least one of them.

Input

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

Each of the next n lines contains two integers a_i and b_i (0 ≤ a_i ≤ b_i ≤ 10^9), the arrival and leaving times of guest i. A guest may arrive and leave at the same instant (a_i = b_i), and several guests may have identical times.

Output

Print one integer: the minimum number of photos.

Notes

In the first example, a photo at time 4 captures guests 1, 2 and 3 (guest 1 leaves at 4 and guest 3 arrives at 4, so both are there), and a photo at time 9 captures guests 4 and 5. No single instant has all five guests present, so 2 photos are needed.

In the second example, nobody's stay overlaps with anyone else's, so every guest needs a photo of their own.

Example 1

Input

5
1 4
2 6
4 8
7 9
9 12

Output

2

Example 2

Input

4
3 3
0 2
5 10
11 11

Output

4

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

Hint 1

Each guest is a closed interval of time and a photo is a single instant. Which guest's departure is the most urgent to capture, and where in that guest's stay is the best place to take a photo?

Hint 2

Process guests by their leaving time. Take a photo at a guest's leaving time only if no earlier photo already captured them, since a photo taken later is still within every stay that remained open. Remember that stays include both endpoints.

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

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