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 Scala (2.11.7) (judge verdict: Wrong Answer)

import scala.collection.mutable.ArrayBuffer

object Main {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)

    val V, E = sc.nextInt()
    val G = Array.fill(V)(new ArrayBuffer[Int]())
    for (i <- 0 until E) {
      val x, y= sc.nextInt()
      G(x-1).append(y-1)
    }

    // ある頂点から入って, 最長の有向パスの長さはDFSをすれば手に入る
    // dp[v] := 頂点vから入った時の最長の有向パスの長さとすれば
    //          他の頂点から入った時, すでにdp[v]が計算されていれば, その長さを追加すればいい
    // これで, 全頂点と全辺を１回ずつ通るので, O(V+E)
    def solve(V: Int, G: Array[ArrayBuffer[Int]]): Int = {
      val visited = new Array[Boolean](V)
      val dp = Array.fill(V)(-1)
      def dfs(stack: List[(Int, Int)], max: Int): Int =
        if (stack.nonEmpty) {
          val (u, l) = stack.head
          if (dp(u) >= 0) dfs(stack.tail, (l + dp(u)) max max)
          else if (!visited(u)) {
            visited(u) = true
            dfs(G(u).foldLeft(stack.tail)(
              (stack, v) => (v, l + 1) :: stack), l max max)
          } else dfs(stack.tail, l max max)
        } else max

      (0 until V).foldLeft(0)((max, s) =>
        if (!visited(s)) {
          dp(s) = dfs((s, 0) :: Nil, 0)
          dp(s) max max
        } else max)
    }

    println(solve(V, G))
  }

}