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 Java8 (OpenJDK 1.8.0) (judge verdict: Accepted)

import java.util.*;

public class Main {
	
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n=in.nextInt();
		int m=in.nextInt();
		int ar1 = 0,ar2=0;
		Graph g = new Graph(n);
		
		for(int i=0;i<m;i++) {
			ar1= in.nextInt();
			ar2= in.nextInt();
			g.addEdge(ar1-1,ar2-1);
		}
		
		System.out.println(g.getAns());
	}
}

class Graph{
	int N;
	ArrayList<Integer>[] listy;
	private boolean[] visited;
	private int[] val;
	Graph(int n){
		N=n;
		val = new int[n];
		visited = new boolean[n];
		listy = new ArrayList[n];
		for(int i=0;i<n;i++) {
			listy[i] = new ArrayList<Integer>();
		}
	}
	public int getAns() {
		for(int i=0;i<N;i++) {
			if(visited[i]!=true) {
				int x = DFS(i);
				val[i]=x;
			}
		}
		int maxy=-1;
		for(int i=0;i<N;i++) {
			maxy= Math.max(maxy,val[i]);
		}
		return maxy-1;
				
	}
	private int DFS(int i) {
		visited[i] = true;
		
		Iterator<Integer> x = listy[i].listIterator();
		int maxy=0;
		while(x.hasNext()) {
			int j = x.next();
//			System.out.println("Parent: " + (i+1) + " Son: "+(j+1));

			if(visited[j]!=true) {
				int cu = DFS(j);
				val[j] =cu;
			}
//			System.out.println("Value for "+ (j+1) + " is "+val[j]);
			maxy = Math.max(maxy, val[j]);
		}
		return maxy+1;
	}
	
	public void addEdge(int ar1, int ar2) {
		listy[ar1].add(ar2);
	}
}