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 12.16.1) (judge verdict: Accepted)


function Main(input) {
    input = input.trim().split("\n").map(function(x) { return x.split(" ")});    
	let N = parseInt(input[0][0],10);
	let M = parseInt(input[0][1],10);
	let arr_xy = [];
	graph = Array.from({length: N}, () => []);
	for (let i = 0; i < M; i++){
		arr_xy.push(input[i + 1].map(e => parseInt(e, 10)));
		graph[arr_xy[i][0] - 1].push(arr_xy[i][1] - 1);
	}
	v = Array.from({length: N}, () => -1);
	let ans = 0;
	for (let i = 0; i < N; i++){
		ans = Math.max(ans, runRecursive(DP, i));
	}
	console.log(ans);
}

function* DP(x){
	if (v[x] !== -1) {
		return v[x];
	} else {
		let maxD = -1;
		for (let a of graph[x]){	
			maxD = Math.max(yield[a], maxD);
		}
		v[x] = maxD + 1;
		return v[x];
	}
}

function runRecursive(func, ...args) {
	// 最終結果を受け取るオブジェクトを用意
	const rootCaller = {
	  lastReturnValue: null
	};
	// 自前のコールスタックを用意
	const callStack = [];
	// 最初の関数呼び出しを追加
	callStack.push({
	  iterator: func(...args),
	  lastReturnValue: null,
	  caller: rootCaller
	});
	while (callStack.length > 0) {
	  const stackFrame = callStack[callStack.length - 1];
	  const { iterator, lastReturnValue, caller } = stackFrame;
	  // 関数の実行を再開
	  const { value, done } = iterator.next(lastReturnValue);
	  if (done) {
		// 関数がreturnしたので親に返り値を記録
		caller.lastReturnValue = value;
		callStack.pop();
	  } else {
		// 関数がyieldした（valueは再帰呼び出しの引数リスト）
		callStack.push({
		  iterator: func(...value),
		  lastReturnValue: null,
		  caller: stackFrame
		});
	  }
	}
	return rootCaller.lastReturnValue;
  }

Main(require("fs").readFileSync("/dev/stdin", "utf8"));