All problems

Problem 953

Maximum Length of Pair Chain

Medium · 20 pts · Array, Greedy, Dynamic Programming, Sorting

Problem

Each pair (a, b) has a < b. Pair (c, d) can follow pair (a, b) in a chain if b < c. Using the pairs in any order, each at most once, find the length of the longest chain. Sorting by the second number and greedily taking every pair that can follow the last one taken is optimal, exactly like scheduling the most non-overlapping intervals.

Input

The first line contains N. Each of the next N lines contains a and b.

Output

Print the length of the longest chain.

Constraints

1 <= N <= 1000; -1000 <= a < b <= 1000

Example input

3
1 2
2 3
3 4

Example output

2

Explanation

From (1,2), (2,3) and (3,4), the chain (1,2) → (3,4) works because 2 < 3, but (2,3) cannot follow (1,2) since 2 is not less than 2. So the answer is 2.

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

Previous: Arithmetic Slices Next: 2 Keys Keyboard