题目描述

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.

样例输入

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

样例输出

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.

刚开始疯狂T了两次,原来是这个题目卡cout

#pragma
#pragma
#pragma
#pragma
#pragma
#pragma
#include <bits/stdc++.h>
#include <algorithm>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
#define
typedef long long ll;
#define
#define
template<class T> inline T min(T &x,const T &y){return x>y?y:x;}
template<class T> inline T max(T &x,const T &y){return x<y?y:x;}
///#define getchar()(p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++)
///char buf[(1 << 21) + 1], *p1 = buf, *p2 = buf;
ll read(){ll c = getchar(),Nig = 1,x = 0;while(!isdigit(c) && c!='-')c = getchar();
if(c == '-')Nig = -1,c = getchar();
while(isdigit(c))x = ((x<<1) + (x<<3)) + (c^'0'),c = getchar();
return Nig*x;}
#define
const ll inf = 1e15;
const int maxn = 2e5 + 7;
const int mod = 1e9 + 7;
#define
#define
int cnt;
string s;
int num[maxn];
int x[maxn],y[maxn];
start{
int h=read,w=read,d=read;
for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
int temp=read;
x[temp]=i;
y[temp]=j;
}
}
for(int i=d+1;i<=h*w;i++)
num[i]=num[i-d]+abs(x[i]-x[i-d])+abs(y[i]-y[i-d]);
int q=read;
for(int i=1;i<=q;i++){
int l=read,r=read;
printf("%d\n",num[r]-num[l]);
}
end;
}

/**************************************************************
Language: C++
Result: 正确
Time:41 ms
Memory:4368 kb
****************************************************************/