PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#PS0000113. Bài kiểm tra dịch chuyển (Practical Skill Test)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Bài kiểm tra dịch chuyển (Practical Skill Test)

Practical Skill Test

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

A magical girl practices teleporting a piece on an HH by WW grid. The cells contain each integer from 1 through HWHW exactly once. Moving between cells (i,j)(i,j) and (x,y)(x,y) costs ∣x−i∣+∣y−j∣|x-i|+|y-j| magic points.

For a test (L,R)(L,R), start on the cell numbered LL. Repeatedly move from label vv to label v+Dv+D until reaching RR. The difference R−LR-L is divisible by DD. If L=RL=R, no movement is needed. Find the total cost of each test.

Input

The first line contains integers H,W,DH,W,D.

The next HH lines each contain the WW integers of one grid row.

The following line contains integer QQ.

Each of the last QQ lines contains integers L,RL,R.

Output

Print QQ lines, each containing the total cost of the corresponding test.

Subtasks

  • Subtask 1 (20 points): 1≤H,W≤201\le H,W\le 20; 1≤D≤HW1\le D\le HW; 1≤Ai,j≤HW, 1≤i≤H, 1≤j≤W1\le A_{i,j}\le HW,\ 1\le i\le H,\ 1\le j\le W; Ai,j≠Au,vA_{i,j}\ne A_{u,v} if (i,j)≠(u,v)(i,j)\ne(u,v); 1≤Q≤10001\le Q\le 1000; 1≤L≤R≤HW1\le L\le R\le HW; (R−L) mod D=0(R-L)\bmod D=0.
  • Subtask 2 (30 points): 1≤H,W≤3001\le H,W\le 300; 1≤D≤HW1\le D\le HW; 1≤Ai,j≤HW, 1≤i≤H, 1≤j≤W1\le A_{i,j}\le HW,\ 1\le i\le H,\ 1\le j\le W; Ai,j≠Au,vA_{i,j}\ne A_{u,v} if (i,j)≠(u,v)(i,j)\ne(u,v); 1≤Q≤1000001\le Q\le 100000; 1≤L≤R≤HW1\le L\le R\le HW; (R−L) mod D=0(R-L)\bmod D=0; (R−L)/D≤10(R-L)/D\le 10.
  • Subtask 3 (50 points): 1≤H,W≤3001\le H,W\le 300; 1≤D≤HW1\le D\le HW; 1≤Ai,j≤HW, 1≤i≤H, 1≤j≤W1\le A_{i,j}\le HW,\ 1\le i\le H,\ 1\le j\le W; Ai,j≠Au,vA_{i,j}\ne A_{u,v} if (i,j)≠(u,v)(i,j)\ne(u,v); 1≤Q≤1000001\le Q\le 100000; 1≤L≤R≤HW1\le L\le R\le HW; (R−L) mod D=0(R-L)\bmod D=0.

Examples 1

Input

3 3 2
1 4 3
2 5 7
8 9 6
1
4 8

Output

5

Explanation

With D=2D=2, the required labels are 4→6→84\to6\to8. Their cells are (1,2),(3,3),(3,1)(1,2),(3,3),(3,1). The two costs are ∣3−1∣+∣3−2∣=3|3-1|+|3-2|=3 and ∣3−3∣+∣1−3∣=2|3-3|+|1-3|=2, totaling 5.

Examples 2

Input

4 2 3
3 7
1 4
5 2
6 8
2
2 2
2 2

Output

0
0

Explanation

Both queries have L=R=2L=R=2. The piece is already at its destination, so neither query requires a move.

Examples 3

Input

5 5 4
13 25 7 15 17
16 22 20 2 9
14 11 12 1 19
10 6 23 8 18
3 21 5 24 4
3
13 13
2 10
13 13

Output

0
5
0

Explanation

The first and last queries require no move. The middle path is 2→6→102\to6\to10, through cells (2,4),(4,2),(4,1)(2,4),(4,2),(4,1). The costs are 4 and 1, totaling 5.