All problems

Problem 452

Russian Doll Envelopes

Hard · 30 pts · Array, Binary Search, Dynamic Programming, Sorting

Problem

Each envelope has a width and a height. One envelope fits inside another only if both its width and its height are strictly smaller; envelopes cannot be rotated. Find the maximum number of envelopes you can nest inside each other, like Russian dolls. Sort by width ascending, and for equal widths by height descending; the answer is then the longest strictly increasing subsequence of the heights, which can be found in O(N log N).

Input

First line: N. Next N lines: the width and height of an envelope.

Output

Print the maximum number of nested envelopes.

Constraints

1 <= N <= 100000; 1 <= width, height <= 100000

Example input

4
5 4
6 4
6 7
2 3

Example output

3

Explanation

From 5x4, 6x4, 6x7 and 2x3, the envelopes 2x3, 5x4 and 6x7 nest inside one another, so the answer is 3. 6x4 cannot hold 5x4 because their heights are equal.

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

Previous: Number of Longest Increasing Subsequences Next: Partition Array for Maximum Sum