Minimizing maximizer
The company Chris Ltd. is preparing a new sorting hardware called Maximizer. Maximizer has n inputs numbered from 1 to n. Each input represents one integer. Maximizer has one output which represents the maximum value present on Maximizer's inputs.
Maximizer is implemented as a pipeline of sorters Sorter(i[1]
, j[1]
), ..., Sorter(i[k]
, j[k]
). Each sorter has n inputs and n outputs. Sorter(i, j) sorts values on inputs i, i + 1, ..., j in non-decreasing order and lets the other inputs pass through unchanged. The n-th output of the last sorter is the output of the Maximizer.
An intern (a former ACM contestant) observed that some sorters could be excluded from the pipeline and Maximizer would still produce the correct result. What is the length of the shortest subsequence of the given sequence of sorters in the pipeline still producing correct results for all possible combinations of input values?
Input
Consists of several test cases. For each case, the first line contains two integers n and m (2 ≤ n ≤ 50000, 1 ≤ m ≤ 500000) separated by a single space. Integer n is the number of inputs and integer m is the number of sorters in the pipeline. The initial sequence of sorters is described in the next m lines. The k-th of these lines contains the parameters of the k-th sorter: two integers i[k]
and j[k]
(1 ≤ i[k]
< j[k]
≤ n) separated by a single space.
Output
For each test case, print in one line the length of the shortest subsequence of the initial sequence of sorters still producing correct results for all possible data.