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

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

Q=int(eval(input()))

X=[[[0,0] for _ in range((H*W)//D+1)] for _ in range(D)]

for i in range(H):

    for j in range(W):

        X[A[i][j]%D][A[i][j]//D][0]=i

        X[A[i][j]%D][A[i][j]//D][1]=j

M=[[0]*((H*W)//D+1) for _ in range(D)]

for d in range(D):

    for k in range((H*W)//D):

        M[d][k+1]=abs(X[d][k+1][0]-X[d][k][0])+abs(X[d][k+1][1]-X[d][k][1])+M[d][k]



for i in range(Q):

    L,R=list(map(int,input().split()))

    print((M[L%D][R//D]-M[L%D][L//D]))
H,W,D=list(map(int,input().split()))

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

Q=int(eval(input()))

X=[[0,0] for _ in range(H*W+1)]

for i in range(H):

    for j in range(W):

        X[A[i][j]][0]=i

        X[A[i][j]][1]=j

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

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

        M[d]=abs(X[d][0]-X[d-D][0])+abs(X[d][1]-X[d-D][1])+M[d-D]



for i in range(Q):

    L,R=list(map(int,input().split()))

    print((M[R]-M[L]))
H, W, D = list(map(int, input().split()))
A = [list(map(int, input().split())) for _ in range(H)]
Q = int(eval(input()))
X = [[[0, 0] for _ in range((H * W) // D + 1)] for _ in range(D)]
for i in range(H):
    for j in range(W):
        X[A[i][j] % D][A[i][j] // D][0] = i
        X[A[i][j] % D][A[i][j] // D][1] = j
M = [[0] * ((H * W) // D + 1) for _ in range(D)]
for d in range(D):
    for k in range((H * W) // D):
        M[d][k + 1] = (
            abs(X[d][k + 1][0] - X[d][k][0])
            + abs(X[d][k + 1][1] - X[d][k][1])
            + M[d][k]
        )
for i in range(Q):
    L, R = list(map(int, input().split()))
    print((M[L % D][R // D] - M[L % D][L // D]))

H, W, D = list(map(int, input().split()))
A = [list(map(int, input().split())) for _ in range(H)]
Q = int(eval(input()))
X = [[0, 0] for _ in range(H * W + 1)]
for i in range(H):
    for j in range(W):
        X[A[i][j]][0] = i
        X[A[i][j]][1] = j
M = [0] * (H * W + 1)
for d in range(D + 1, H * W + 1):
    M[d] = abs(X[d][0] - X[d - D][0]) + abs(X[d][1] - X[d - D][1]) + M[d - D]
for i in range(Q):
    L, R = list(map(int, input().split()))
    print((M[R] - M[L]))

-X = [[[0, 0] for _ in range((H * W) // D + 1)] for _ in range(D)] +X = [[0, 0] for _ in range(H * W + 1)] -        X[A[i][j] % D][A[i][j] // D][0] = i -        X[A[i][j] % D][A[i][j] // D][1] = j -M = [[0] * ((H * W) // D + 1) for _ in range(D)] -for d in range(D): -    for k in range((H * W) // D): -        M[d][k + 1] = ( -            abs(X[d][k + 1][0] - X[d][k][0]) -            + abs(X[d][k + 1][1] - X[d][k][1]) -            + M[d][k] -        ) +        X[A[i][j]][0] = i +        X[A[i][j]][1] = j +M = [0] * (H * W + 1) +for d in range(D + 1, H * W + 1): +    M[d] = abs(X[d][0] - X[d - D][0]) + abs(X[d][1] - X[d - D][1]) + M[d - D] -    print((M[L % D][R // D] - M[L % D][L // D])) +    print((M[R] - M[L]))