Module: Patterns in Dynamic Programming


Problem

5 /7


Restaurant

Theory Click to read/hide

Disclaimer: The method described below is not universal, but it can often solve a problem or help you come to the right solution.

If there is a set of gaps located on some axis (usually the time axis or indices of some array) and you need to choose some of them in an optimal way so that the selected gaps do not intersect, then you should try using dynamic programming.

Approximate solution scheme:

Initially, we sort the available gaps by the right border. Let's start the following dynamics: dp[i] - the answer for the first i intervals. 
We will recalculate as follows: first, consider the situation that this interval will not be used, then just dp[i] = dp[i-1]. Note that this ensures that the values ​​of dp[i] do not decrease as i grows. And this is logical, because. adding a new gap, we cannot worsen the global answer: either we simply ignore the new gap, or we construct a more profitable variant using it. Now, if we want to use the i-th gap, then we can use those gaps whose right borders are less than the left border of the current gap, since we must choose a set of non-overlapping gaps. To do this, we initially sorted the gaps by the right border, so that now we can efficiently find the required position. This can be done analytically, if possible, but in the general case it is possible to find a gap with a binsearch, the right border of which is less than the left border of the current one and, at the same time, the maximum possible one. We want to maximize the right border for greedy reasons, because as i grows, the answer can only increase. Accordingly, we find the required position p and recalculate dp[i] through dp[p] and the i-th interval.

Problem

The restaurant received n orders for a banquet. Each order is characterized by two values: the start time of the banquet li and the end time ri (li ≤ r i).

The restaurant management can either accept the order or reject it. What is the maximum number of orders that can be accepted?

No two accepted orders can intersect, that is, there should not be a point in time that belongs to two accepted orders at once. If one of the orders starts at the same time as the other ends, then they cannot be accepted together.

Input:
The first line contains an integer n (1 ≤ n ≤ 200000) — the number of orders. Each of the next n lines contains a pair of integers li, ri (0 ≤ li &le ; ri ≤ 109).

Output:
Print the maximum number of orders that can be accepted.

Examples:
 
Input Output
2
7 11
4 7
1
5
1 2
23
34
4 5
5 6
3
6
48
15
47
25
1 3
68
2