#jag2017autumni. [jag2017autumn_i]Revenge of the Endless BFS
[jag2017autumn_i]Revenge of the Endless BFS
MathJax.Hub.Config({ tex2jax: { inlineMath: [[""], ["\\(","\\)"]], processEscapes: true }}); blockquote { font-family: Menlo, Monaco, "Courier New", monospace; color: #333333; display: block; padding: 8.5px; margin: 0 0 9px; font-size: 16px; line-height: 18px; background-color: #f5f5f5; border: 1px solid rgba(0, 0, 0, 0.15); -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; white-space: pre; white-space: pre-wrap; word-break: break-all; word-wrap: break-word; }
Problem Statement
Mr. Endo wanted to write the code that performs breadth-first search (BFS), which is a search algorithm to explore all vertices on a directed graph. An example of pseudo code of BFS is as follows:
1: 2: 3: while the set of all the vertices 4: 5: for in 6: for each such that there is an edge from to 7: 8: 9:
However, Mr. Endo apparently forgot to manage visited vertices in his code. More precisely, he wrote the following code:
1: 2: while the set of all the vertices 3: 4: for in 5: for each such that there is an edge from to 6: 7:
You may notice that for some graphs, Mr. Endo's program will not stop because it keeps running infinitely. Notice that it does not necessarily mean the program cannot explore all the vertices within finite steps. Your task here is to make a program that determines whether Mr. Endo's program will stop within finite steps for a given directed graph in order to point out the bug to him. Also, calculate the minimum number of loop iterations required for the program to stop if it is finite. Since the answer might be huge, thus print the answer modulo , which is a prime number.
Input
The input consists of a single test case formatted as follows.
The first line consists of two integers () and (), where is the number of vertices and is the number of edges in a given directed graph, respectively. The -th line of the following lines consists of two integers and (), which means there is an edge from to in the given graph. The vertex is the start vertex, i.e. in the pseudo codes. You can assume that the given graph also meets the following conditions.
- The graph has no self-loop, i.e., for all .
- The graph has no multi-edge, i.e., for all .
- For each vertex , there is at least one path from the start vertex to .
Output
If Mr. Endo's wrong BFS code cannot stop within finite steps for the given input directed graph, print -1
in a line. Otherwise, print the minimum number of loop iterations required to stop modulo .
Sample Input 1
4 4
1 2
2 3
3 4
4 1
Output for Sample Input 1
-1
Sample Input 2
4 5
1 2
2 3
3 4
4 1
1 3
Output for Sample Input 2
7
Sample Input 3
5 13
4 2
2 4
1 2
5 4
5 1
2 1
5 3
4 3
1 5
4 5
2 3
5 2
1 3
Output for Sample Input 3
3