Problem:
Score : 100 points

Problem Statement

There is a directed graph G with N vertices and M edges.
The vertices are numbered 1, 2, \ldots, N, and for each i (1 \leq i \leq M), the i-th directed edge goes from Vertex x_i to y_i.
G does not contain directed cycles.

Find the length of the longest directed path in G.
Here, the length of a directed path is the number of edges in it.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq x_i, y_i \leq N

All pairs (x_i, y_i) are distinct.

G does not contain directed cycles.

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the length of the longest directed path in G.

Sample Input 1

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

Sample Output 1

3

The red directed path in the following figure is the longest:

Sample Input 2

6 3
2 3
4 5
5 6

Sample Output 2

2

The red directed path in the following figure is the longest:

Sample Input 3

5 8
5 3
2 3
2 4
5 2
5 1
1 4
4 3
1 3

Sample Output 3

3

The red directed path in the following figure is one of the longest:

Solution in C (GCC 5.4.1) (judge verdict: Wrong Answer)

#include <stdio.h>
#define swap(type, x, y) do{ type t = x; x = y; y = t; }while(0)
#define max(a, b) ((a)<(b) ? (b) : (a))

typedef struct{
  int s, g;
}Edge;
typedef struct{
  Edge edge[100001];
  int to[100001]; // = {0};
}Graph;

void quick(Graph *graph, int left, int right){
  int pl = left, pr = right, x = graph->edge[(left + right) / 2].g;
  do{
    while(graph->edge[pl].g < x) pl++;
    while(graph->edge[pr].g > x) pr--;
    if(pl <= pr){
      swap(int, graph->edge[pl].g, graph->edge[pr].g);
      if(!(graph->edge[pl].g == graph->edge[pr].g && graph->edge[pl].s < graph->edge[pr].s))
	swap(int, graph->edge[pl].s, graph->edge[pr].s);
      pl++, pr--;
    }
  }while(pl <= pr);
  if(pl < right) quick(graph, pl, right);
  if(pr > left) quick(graph, left, pr);
}


int main(){  
  int n, m;  scanf("%d %d", &n, &m);
  Graph graph;
  for(int i=1; i<=n; i++) graph.to[i] = 0;
  for(int i=0; i<m; i++){
    scanf("%d %d", &graph.edge[i].s, &graph.edge[i].g);
    graph.to[graph.edge[i].g]++;
  }

  quick(&graph, 0, m-1);

  int S[100001] = {0}; // 入次数==0 の頂点を入れる
  // S[0]にはサイズ S[1~]に頂点が入ってる 擬似的にpush popするため
  for(int i=1; i<=n; i++){
    if(graph.to[i] == 0)
      S[++S[0]] = i; // push
  }

  int afterTopo[100001] = {0};
  while(S[0] > 0){
    int node = S[S[0]--];
    afterTopo[++afterTopo[0]] = node;
    for(int i=0; i<m; i++)
      if(graph.edge[i].s == node)
	if(--graph.to[graph.edge[i].g] == 0)
	  S[++S[0]] = graph.edge[i].g;
  }
  int i, j;
  int dp[100001] = {0};
  for(i=2; i<=n; i++){ // each afterTopo
    for(j=0; j<m; j++)
      if(graph.edge[j].g == afterTopo[i]) break;
    while(graph.edge[j].g == afterTopo[i]){
      dp[i] = max(dp[i], dp[graph.edge[j].s]+1);
      j++;
    }
  }
  printf("%d\n", dp[n]);
  
  return 0;
}