H,W,D = list(map(int,input().split()))

A = [list(map(int,input().split())) for i in range(H)]

Q = int(eval(input()))

S = [list(map(int,input().split())) for i in range(Q)]

P = [None]*(H*W+1)

for i in range(H):

    for j in range(W):

        P[A[i][j]] = [i,j]



Accum = [0]*(H*W+1)

accum = 0



for i in range(D+1,H*W+1):

    Accum[i] = Accum[i-D]+abs(P[i][0]-P[i-D][0])+abs(P[i][1]-P[i-D][1])



for s in S:

    print((Accum[s[1]]-Accum[s[0]]))
H, W, D = list(map(int, input().split()))

A = [tuple(map(int, input().split())) for _ in range(H)]



P = {}



for i in range(H):

    for j in range(W):

        P[A[i][j] - 1] = (i, j)



cum = [0] * (H * W + 1)



for a in range(H * W - D):

    i, j = P[a]

    x, y = P[a + D]

    cum[a + D] = cum[a] + abs(x - i) + abs(y - j)



Q = int(eval(input()))

ans = []



for _ in range(Q):

    l, r = list(map(int, input().split()))

    ans.append(cum[r - 1] - cum[l - 1])



print(('\n'.join(map(str, ans))))
H, W, D = list(map(int, input().split()))
A = [list(map(int, input().split())) for i in range(H)]
Q = int(eval(input()))
S = [list(map(int, input().split())) for i in range(Q)]
P = [None] * (H * W + 1)
for i in range(H):
    for j in range(W):
        P[A[i][j]] = [i, j]
Accum = [0] * (H * W + 1)
accum = 0
for i in range(D + 1, H * W + 1):
    Accum[i] = Accum[i - D] + abs(P[i][0] - P[i - D][0]) + abs(P[i][1] - P[i - D][1])
for s in S:
    print((Accum[s[1]] - Accum[s[0]]))

H, W, D = list(map(int, input().split()))
A = [tuple(map(int, input().split())) for _ in range(H)]
P = {}
for i in range(H):
    for j in range(W):
        P[A[i][j] - 1] = (i, j)
cum = [0] * (H * W + 1)
for a in range(H * W - D):
    i, j = P[a]
    x, y = P[a + D]
    cum[a + D] = cum[a] + abs(x - i) + abs(y - j)
Q = int(eval(input()))
ans = []
for _ in range(Q):
    l, r = list(map(int, input().split()))
    ans.append(cum[r - 1] - cum[l - 1])
print(("\n".join(map(str, ans))))

-A = [list(map(int, input().split())) for i in range(H)] -Q = int(eval(input())) -S = [list(map(int, input().split())) for i in range(Q)] -P = [None] * (H * W + 1) +A = [tuple(map(int, input().split())) for _ in range(H)] +P = {} -        P[A[i][j]] = [i, j] -Accum = [0] * (H * W + 1) -accum = 0 -for i in range(D + 1, H * W + 1): -    Accum[i] = Accum[i - D] + abs(P[i][0] - P[i - D][0]) + abs(P[i][1] - P[i - D][1]) -for s in S: -    print((Accum[s[1]] - Accum[s[0]])) +        P[A[i][j] - 1] = (i, j) +cum = [0] * (H * W + 1) +for a in range(H * W - D): +    i, j = P[a] +    x, y = P[a + D] +    cum[a + D] = cum[a] + abs(x - i) + abs(y - j) +Q = int(eval(input())) +ans = [] +for _ in range(Q): +    l, r = list(map(int, input().split())) +    ans.append(cum[r - 1] - cum[l - 1]) +print(("\n".join(map(str, ans))))