FIND ROOT!

0

0 votes
Problem

You are given with a directed graph where the graph can be cyclic or acyclic. If the graph is cyclic then output -1 else you need to find the root of the directed acyclic graph (DAG).

"The root of DAG is a vertex K, such that every vertex of the DAG can be reached by a directed path from that vertex K."

Input: First line containes an integer T denoting the number of test cases. For each test case , First line containes two integers M and N where M in the number of vertices in the graph and N is the number of edges. Next N lines contain two integers X and Y meaning there is a directed edge from X to Y.

Output: If the graph is cyclic or the graph is acyclic but root does not exist, then output -1 else print the root of DAG.

Constraints: 

1 <= T <= 10

1 <= N <= 10^6

1 <= M <= min( 10^6, N * (N - 1) ) 

1 <= X,  Y <= N

Time Limit: 5
Memory Limit: 1024
Source Limit:
Editor Image

?