Practical Skill Test
时间限制: 1 Sec 内存限制: 128 MB
题目描述
We have a grid with H rows and W columns. The square at the i-th row and the j-th column will be called Square (i,j).
The integers from 1 through H×W are written throughout the grid, and the integer written in Square (i,j) is Ai,j.
You, a magical girl, can teleport a piece placed on Square (i,j) to Square (x,y) by consuming |x−i|+|y−j| magic points.
You now have to take Q practical tests of your ability as a magical girl.
The i-th test will be conducted as follows:
Initially, a piece is placed on the square where the integer Li is written.
Let x be the integer written in the square occupied by the piece. Repeatedly move the piece to the square where the integer x+D is written, as long as x is not Ri. The test ends when x=Ri.
Here, it is guaranteed that Ri−Li is a multiple of D.
For each test, find the sum of magic points consumed during that test.
Constraints
1≤H,W≤300
1≤D≤H×W
1≤Ai,j≤H×W
Ai,j≠Ax,y((i,j)≠(x,y))
1≤Q≤105
1≤Li≤Ri≤H×W
(Ri−Li) is a multiple of D.
输入
Input is given from Standard Input in the following format:
H W D
A1,1 A1,2 … A1,W
:
AH,1 AH,2 … AH,W
Q
L1 R1
:
LQ RQ
输出
For each test, print the sum of magic points consumed during that test.
Output should be in the order the tests are conducted.
样例输入 Copy
3 3 2
1 4 3
2 5 7
8 9 6
1
4 8
样例输出 Copy
5
提示
4 is written in Square (1,2).
6 is written in Square (3,3).
8 is written in Square (3,1).
Thus, the sum of magic points consumed during the first test is (|3−1|+|3−2|)+(|3−3|+|1−3|)=5.
题意就是给你个方格,里面都填的数,让后给你个 l 和 r ,l 对应方格中的数的位置,只要 l != r 就给 l 加上 d ,一直到 l = r 为止,计算要走的距离 ,每一个距离就是 l 和 l + d 在方格中对应数点的曼哈顿距离。
题目中的数据一开始没看让后T掉了,一开始我是直接模拟的,while( l ! = r ) 一直循环下去,可以发现这样的时间复杂度d=1的时候从1枚举到n*m再加上询问比较多,肯定是会T掉的,所以可以考虑预处理每一个点的距离的前缀和,询问直接 O(1) 查询即可。
dis是从起点到这个点的距离。
#include<cstdio>
#include<iostream>
#include