Revenge of the Endless BFS
Time limit2sMemory limit512 MB
Decide whether a buggy BFS that forgets visited vertices ever terminates on a given directed graph, and if so output the loop count modulo 1e9+7.
- Level
Hard9 of 10
- Topics
- Graph, BFS, Math, Dynamic programming
- Solved
- No attempts yet
Problem
Mr. Endo wanted to write code that performs breadth-first search (BFS), a search algorithm that explores every vertex of a directed graph. An example of BFS in pseudo code follows.
1: current ← {start_vertex}
2: visited ← current
3: while visited ≠ the set of all the vertices
4: found ← {}
5: for u in current
6: for each v such that there is an edge from u to v
7: found ← found ∪ {v}
8: current ← found ∖ visited
9: visited ← visited ∪ found
However, Mr. Endo apparently forgot to manage the visited vertices in his code. More precisely, he wrote the following code.
1: current ← {start_vertex}
2: while current ≠ the set of all the vertices
3: found ← {}
4: for u in current
5: for each v such that there is an edge from u to v
6: found ← found ∪ {v}
7: current ← found
For some graphs, Mr. Endo's program never stops and keeps running forever. Note that this does not necessarily mean the program cannot explore all the vertices within a finite number of steps. To point out the bug to him, write a program that decides whether Mr. Endo's program stops within a finite number of steps for a given directed graph. If it stops, also compute the minimum number of loop iterations the program needs before it stops. Since the answer might be huge, print it modulo , which is a prime number.
Input
The input consists of a single test case in the following format.
N M
u1 v1
.
.
.
uM vM
The first line contains two integers () and (), where is the number of vertices and is the number of edges of the directed graph. The -th of the following lines contains two integers and (), which means there is an edge from to . Vertex 1 is the start vertex, that is, start_vertex in the pseudo code. The given graph also satisfies the following conditions.
- The graph has no self-loop, that is, for all .
- The graph has no multi-edge, that is, for all .
- For each vertex , there is at least one path from the start vertex 1 to .
Output
If Mr. Endo's wrong BFS code cannot stop within a finite number of steps for the given directed graph, print -1 on a line. Otherwise, print the minimum number of loop iterations needed before it stops, modulo .