#abc287h. Ex - Directed Graph and Query

Ex - Directed Graph and Query

Score : 600600 points

问题描述

存在一个含有 NN 个顶点和 MM 条边的有向图。顶点编号为 11NN,第 ii 条有向边从顶点 aia_i 指向顶点 bib_i

在该图上,一条路径的成本定义为:

  • 路径上(包括起点和终点)顶点的最大索引值。

对于每个 x=1,2,,Qx=1,2,\ldots,Q,解决以下问题:

  • 找出从顶点 sxs_x 到顶点 txt_x 的最小成本路径。如果不存在这样的路径,则输出 -1

由于可能存在的大规模输入和输出,建议使用快速输入输出方法。

以上为通义千问 qwen-max 翻译,仅供参考。

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.

Sample Input 1

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

Sample Output 1

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.

update @ 2024/3/10 12:01:00