#ARC159A. [ARC159A] Copy and Paste Graph

[ARC159A] Copy and Paste Graph

Score : 300300 points

Problem Statement

You are given an NN-by-NN matrix A=(ai,j)A=(a_{i,j}), where ai,j{0,1}a_{i,j} \in \{0,1\}.

We have the following directed graph.

  • The graph has NKNK vertices numbered 1,2,,NK1,2,\ldots,NK.
  • The edges correspond to the NKNK-by-NKNK matrix X=(xi,j)X=(x_{i,j}) obtained by arranging K2K^2 copies of AA in KK rows and KK columns (see Sample Input/Output 1 for an example). If xi,j=1x_{i,j}=1, there is a directed edge from vertex ii to vertex jj; if xi,j=0x_{i,j}=0, that edge does not exist.

Answer the following question for i=1,2,,Qi=1,2,\ldots,Q.

  • Find the shortest length (number of edges) of a path from vertex sis_i to vertex tit_i. If there is no such path, print -1 instead.

Constraints

  • 1N1001 \leq N \leq 100
  • 1K1091 \leq K \leq 10^9
  • ai,j{0,1}a_{i,j} \in \{0,1\}
  • 1Q1001 \leq Q \leq 100
  • 1si,tiNK1 \leq s_i,t_i \leq NK
  • 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 KK

a1,1a_{1,1} \ldots a1,Na_{1,N}

\vdots

aN,1a_{N,1} \ldots aN,Na_{N,N}

QQ

s1s_1 t1t_1

\vdots

sQs_Q tQt_Q

Output

Print QQ lines. The xx-th line should contain the answer to the question for i=xi=x.

3 2
1 1 1
1 1 0
0 1 0
4
1 2
1 4
1 6
6 3
1
1
1
3

Below is the matrix XX representing the edges.

1 1 1 1 1 1
1 1 0 1 1 0
0 1 0 0 1 0
1 1 1 1 1 1
1 1 0 1 1 0
0 1 0 0 1 0
4 1000000000
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
1
1 4000000000
-1

There is no edge.