atcoder#ABC287H. [ABC287Ex] Directed Graph and Query

[ABC287Ex] Directed Graph and Query

Score : 600600 points

Problem Statement

There is a directed graph with NN vertices and MM edges. The vertices are numbered 11 through NN, and the ii-th directed edge goes from vertex aia_i to vertex bib_i.

The cost of a path on this graph is defined as:

  • the maximum index of a vertex on the path (including the initial and final vertices).

Solve the following problem for each x=1,2,,Qx=1,2,\ldots,Q.

  • Find the minimum cost of a path from vertex sxs_x to vertex txt_x. If there is no such path, print -1 instead.

The use of fast input and output methods is recommended because of potentially large input and output.

Constraints

  • 2N20002 \leq N \leq 2000
  • 0MN(N1)0 \leq M \leq N(N-1)
  • 1ai,biN1 \leq a_i,b_i \leq N
  • aibia_i \neq b_i
  • If iji \neq j, then (ai,bi)(aj,bj)(a_i,b_i) \neq (a_j,b_j).
  • 1Q1041 \leq Q \leq 10^4
  • 1si,tiN1 \leq s_i,t_i \leq N
  • sitis_i \neq t_i
  • All values in the input are integers.

Input

The input is given from Standard Input in the following format:

NN MM

a1a_1 b1b_1

\vdots

aMa_M bMb_M

QQ

s1s_1 t1t_1

\vdots

sQs_Q tQt_Q

Output

Print QQ lines. The ii-th line should contain the answer for x=ix=i.

4 4
1 2
2 3
3 1
4 3
3
1 2
2 1
1 4
2
3
-1

For x=1x=1, the path via the 11-st edge from vertex 11 to vertex 22 has a cost of 22, which is the minimum. For x=2x=2, the path via the 22-nd edge from vertex 22 to vertex 33 and then via the 33-rd edge from vertex 33 to vertex 11 has a cost of 33, which is the minimum. For x=3x=3, there is no path from vertex 11 to vertex 44, so -1 should be printed.