Selfish Grazing

Interview

Time limit1sMemory limit128 MB

Summary
Given N intervals, find the maximum number of intervals that can be chosen so that no two of them overlap.
Level

Medium4 of 10

Topics
Greedy, Sorting, Intervals, Array
Solved
No attempts yet

Problem

Each of Farmer John's NN cows (1≤N≤500001 \le N \le 50000) likes to graze in a certain part of the pasture, which can be thought of as one large one-dimensional number line. Cow ii's favorite grazing range starts at location SiS_i and ends at location EiE_i (1≤Si<Ei≤1000000001 \le S_i < E_i \le 100000000).

The cows are quite selfish: no cow wants to share any of its grazing area with another. Thus, two cows ii and jj can graze at the same time only if Si≥EjS_i \ge E_j or Ei≤SjE_i \le S_j. In other words, their ranges may touch at an endpoint but must not overlap. Farmer John would like to know the maximum number of cows that can graze at the same time, given the cows and their preferences.

Consider a set of 5 cows with the ranges shown below.

  ... 1    2    3    4    5    6    7    8    9   10   11   12   13 ...
  ... |----|----|----|----|----|----|----|----|----|----|----|----|----
Cow 1:      <===:===>          :              :              :
Cow 2: <========:==============:==============:=============>:
Cow 3:          :     <====>   :              :              :
Cow 4:          :              :     <========:===>          :
Cow 5:          :              :     <==>     :              :

These ranges represent (2,4)(2, 4), (1,12)(1, 12), (4,5)(4, 5), (7,10)(7, 10), and (7,8)(7, 8), respectively.

In one solution, the first, third, and fourth (or fifth) cows can all graze at the same time. If the second cow grazed, no other cow could graze. Also, the fourth and fifth cows cannot graze together, so it is impossible for four or more cows to graze.

Input

  • Line 1: A single integer NN.
  • Lines 2..N+1: Line i+1i+1 contains two space-separated integers SiS_i and EiE_i.

Output

  • Line 1: A single integer representing the maximum number of cows that can graze at once.

Examples2

  1. Example 1

    Input
    5
    2 4
    1 12
    4 5
    7 10
    7 8
    
    Expected output
    3
    
  2. Example 2

    Input
    4
    1 2
    2 3
    3 4
    4 5
    
    Expected output
    4