#atcoderABC089D. Practical Skill Test
Practical Skill Test
Problem Statement
We have a grid with rows and columns. The square at the -th row and the -th column will be called Square .
The integers from through are written throughout the grid, and the integer written in Square is .
You, a magical girl, can teleport a piece placed on Square to Square by consuming magic points.
You now have to take practical tests of your ability as a magical girl.
The -th test will be conducted as follows:
-
Initially, a piece is placed on the square where the integer is written.
-
Let be the integer written in the square occupied by the piece. Repeatedly move the piece to the square where the integer is written, as long as is not . The test ends when .
-
Here, it is guaranteed that is a multiple of .
For each test, find the sum of magic points consumed during that test.
Constraints
- is a multiple of .
Input
Input is given from Standard Input in the following format:
Output
For each test, print the sum of magic points consumed during that test.
Output should be in the order the tests are conducted.
Input 1
3 3 2
1 4 3
2 5 7
8 9 6
1
4 8
Output 1
5
-
is written in Square .
-
is written in Square .
-
is written in Square .
Thus, the sum of magic points consumed during the first test is .
Input 2
4 2 3
3 7
1 4
5 2
6 8
2
2 2
2 2
Output 2
0
0
Note that there may be a test where the piece is not moved at all, and there may be multiple identical tests.
Input 3
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 3
0
5
0