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 JavaScript (node.js v5.12) (judge verdict: Accepted)

'use strict'

function topological_sort(nodes_count, in_count, outs){
  let start_nodes = Array.from(Array(nodes_count+1).keys()).filter(x => in_count[x]==0)
  start_nodes.shift()

  let result = [];
  let from = start_nodes.shift();
  while(from != undefined){
    result.push(from);
    for(let out_node of outs[from]){
      in_count[out_node]--;
      if(in_count[out_node]==0){ start_nodes.push(out_node); }
    }
    from = start_nodes.shift();
  }

  return result;
}

function main(input){
  const lines = input.split('\n');
  const NM = lines.shift().split(' ').map(x => parseInt(x));
  const N = NM[0];
  const M = NM[1];
  const XY = []
  for(var i=0;i<M;i++){
    let xy = lines.shift().split(' ').map(x => parseInt(x));
    XY.push(xy);
  }

  let ins = [];
  let outs = [];
  let in_count = []
  for(var i=0;i<N+1;i++){
    ins.push([]);
    outs.push([]);
  }

  for(var i=0;i<M;i++){
    let x = XY[i][0];
    let y = XY[i][1];
    ins[y].push(x);
    outs[x].push(y)
  }
  in_count = ins.map(x => x.length)

//  console.log(ins);
//  console.log(outs);
//  console.log(in_count);

  let topological_nodes = topological_sort(N, in_count, outs);
//  console.log(topological_nodes);

//  console.log('---');
  let dp=Array(N+1).fill(0);
//  console.log(dp);
  for(let current of topological_nodes){
//    console.log( [current, ins[current], ins[current].map(x => dp[x])] );
    dp[current] = Math.max(...ins[current].map(x => dp[x]+1).concat(0) )
  }
//  console.log(dp);
//  console.log('---');


  let result = Math.max(...dp);
  console.log(result);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));