AtCoder Beginner Contest 089 D - Practical Skill Test 题解
D - Practical Skill Test
Time limit : 2sec / Memory limit : 256MB
Score : 400 points
Problem Statement
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
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
Output
For each test, print the sum of magic points consumed during that test.
Output should be in the order the tests are conducted.
Sample Input 1
3 3 2 1 4 3 2 5 7 8 9 6 1 4 8
Sample Output 1
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.
Sample Input 2
4 2 3 3 7 1 4 5 2 6 8 2 2 2 2 2
Sample 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.
Sample 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
Sample Output 3
0 5 0
题意:上来一看题目就看错了,还以为是曼哈顿距离的最小生成树,然而,sum是按照顺序进行计算的。也就是在矩阵中找到介于R、L中且是R+kD(0<=k<=(L-R)/D)的坐标,并按照sum的要求进行计算。
思路:理清题意后,思路不是一个大问题,值得注意的是相当于多组数据。所以,每次寻找计算可能会T。但是对于每组值,D的值是确定的,所以可以利用一个数组记忆化这些值,直接相减即可。
代码:
1 #include<cstdio> 2 #define abs(x) ((x>0)?x:(-(x))) 3 int H,W,D,A; 4 int Q,L,R; 5 int px[90001] ,py [90001]; 6 int d[90001]; 7 int main() 8 { 9 scanf ("%d %d %d",&H,&W,&D); 10 for(int i=0;i<H;i++){ 11 for(int j=0;j<W;j++){ 12 scanf ("%d",&A); 13 px[A]=i,py[A]=j; 14 } 15 } 16 for(int i=D+1;i<=H*W;i++){ 17 d[i]=d[i-D]+abs(px[i]-px[i-D])+ abs(py[i]-py[i-D]); 18 } 19 scanf ("%d",&Q); 20 while(Q--){ 21 scanf ("%d%d",&L,&R); 22 printf ("%d\n",d[R]-d[L]); 23 } 24 }

浙公网安备 33010602011771号