Minimizing Maximizer

Time limit1sMemory limit512 MB

Summary
Given a pipeline of range-sort operations, find the minimum number of operations (kept in order) whose composition still guarantees the last position always holds the overall maximum.
Level

Hard8 of 10

Topics
Greedy, Intervals, Dynamic programming
Solved
No attempts yet

Problem

A company is building a new sorting device called Maximizer. The Maximizer has nn inputs numbered from 11 to nn; each input carries one integer. It has a single output that must always equal the maximum of the values on its inputs.

The Maximizer is implemented as a pipeline of sorters Sorter(i1,j1),…,Sorter(ik,jk)\text{Sorter}(i_1, j_1), \ldots, \text{Sorter}(i_k, j_k). Every sorter has nn inputs and nn outputs. Sorter(i,j)\text{Sorter}(i, j) sorts the values on positions i,i+1,…,ji, i+1, \ldots, j into non-decreasing order and passes every other position through unchanged. The nn-th output of the last sorter is the output of the Maximizer.

An engineer noticed that some sorters can be removed from the pipeline while the Maximizer still produces the correct result for every possible input. Determine the length of the shortest subsequence of the given pipeline (keeping the sorters in their original order) that still produces the correct result for all possible input values.

Write a program that reads the description of a Maximizer (its initial pipeline of sorters), computes the length of the shortest such subsequence, and writes that length.

Input

The first line contains two integers nn and mm (2≤n≤50 0002 \le n \le 50\,000, 1≤m≤500 0001 \le m \le 500\,000) separated by a single space, where nn is the number of inputs and mm is the number of sorters in the pipeline.

Each of the next mm lines describes one sorter in pipeline order. The kk-th of these lines contains two integers iki_k and jkj_k (1≤ik<jk≤n1 \le i_k < j_k \le n) separated by a single space, the parameters of the kk-th sorter.

Output

Print a single line containing one integer: the length of the shortest subsequence of the initial pipeline of sorters that still produces correct results for all possible inputs.

Examples3

  1. Example 1

    Input
    40 6
    20 30
    1 10
    10 20
    20 30
    15 25
    30 40
    
    Expected output
    4
    
  2. Example 2

    Input
    2 1
    1 2
    
    Expected output
    1
    
  3. Example 3

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