Problem:
Score : 400 points

Problem Statement

There are N islands lining up from west to east, connected by N-1 bridges.

The i-th bridge connects the i-th island from the west and the (i+1)-th island from the west.

One day, disputes took place between some islands, and there were M requests from the inhabitants of the islands:

Request i: A dispute took place between the a_i-th island from the west and the b_i-th island from the west. Please make traveling between these islands with bridges impossible.

You decided to remove some bridges to meet all these M requests.

Find the minimum number of bridges that must be removed.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq a_i < b_i \leq N

All pairs (a_i, b_i) are distinct.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the minimum number of bridges that must be removed.

Sample Input 1

5 2
1 4
2 5

Sample Output 1

1

The requests can be met by removing the bridge connecting the second and third islands from the west.

Sample Input 2

9 5
1 8
2 7
3 5
4 6
7 9

Sample Output 2

2

Sample Input 3

5 10
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5

Sample Output 3

4

Solution in C# (Mono 4.6.2.0) (judge verdict: Accepted)

using System;
using System.Linq;
using System.Collections.Generic;

public class Program{
  public static int med3(int x, int y, int z){
    if(x<y){
      if(y<z) return y; else if(z<x) return x; else return z;
    }else{
      if(z<y) return y; else if(x<z) return x; else return z;
    }
  }
  public static void sort(ref int[] a, int l, int r){
    if(l<r){
      int i=l, j=r;
      int y = i+(j-i)/2;
      if(y%2==0) y--;
      int t1, t2, p=med3(a[i], a[y], a[j]);
      while(true){
        while(a[i]<p) i+=2;
        while(p<a[j]) j-=2;
        if(i>=j) break;
        t1 = a[i-1]; t2 = a[i];
        a[i-1] = a[j-1]; a[i] = a[j];
        a[j-1] = t1; a[j] = t2;
        i+=2; j-=2;
      }
      sort(ref a, l, i-2);
      sort(ref a, j+2, r);
    }
  }
  public static void Main(){
    var nm = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
    var a = new int[2*nm[1]];
    for(var i=0; i<nm[1]; i++){
      var ab = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
      a[2*i] = ab[0];
      a[2*i+1] = ab[1];
    }
    sort(ref a, 1, 2*nm[1]-1);
    //for(var i=0; i<nm[1]; i++)Console.WriteLine("[{0} {1}]", a[2*i], a[2*i+1]);
    var c=0;
    var b=0;
    for(var i=0; i<nm[1]; i++){
      if(b<a[2*i]){ b=a[2*i+1]-1; c++; }
    }
    Console.WriteLine(c.ToString());
  }
}