



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

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

Q=int(eval(input()))



y=[[-1,-1] for i in range(H*W+1)]



for i in range(H):

    for j in range(W):

        y[a[i][j]]=[i,j]



x=[ [0] for i in range(D)]



for i in range(D):

    j=H*W-i-D

    while j>0:

        tmp1,tmp2=abs(y[j][0]-y[j+D][0]),abs(y[j][1]-y[j+D][1])

        x[i].append(x[i][-1]+tmp1+tmp2)

        j-=D



for q in range(Q):

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

    i=(H*W-R)%D

    l=(H*W-i-R)//D

    r=(H*W-i-L)//D

    print((x[i][r]-x[i][l]))
H,W,D=list(map(int,input().split()))

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

Q=int(eval(input()))



y=[[-1,-1] for i in range(H*W+1)]

for i in range(H):

    for j in range(W):

        y[a[i][j]]=[i,j]



x=[0 for i in range(H*W+1)]

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

    x[i]=x[i-D]+abs(y[i][0]-y[i-D][0])+abs(y[i][1]-y[i-D][1])    



for q in range(Q):

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

    print((x[R]-x[L]))
H, W, D = list(map(int, input().split()))
a = [list(map(int, input().split())) for i in range(H)]
Q = int(eval(input()))
y = [[-1, -1] for i in range(H * W + 1)]
for i in range(H):
    for j in range(W):
        y[a[i][j]] = [i, j]
x = [[0] for i in range(D)]
for i in range(D):
    j = H * W - i - D
    while j > 0:
        tmp1, tmp2 = abs(y[j][0] - y[j + D][0]), abs(y[j][1] - y[j + D][1])
        x[i].append(x[i][-1] + tmp1 + tmp2)
        j -= D
for q in range(Q):
    L, R = list(map(int, input().split()))
    i = (H * W - R) % D
    l = (H * W - i - R) // D
    r = (H * W - i - L) // D
    print((x[i][r] - x[i][l]))

H, W, D = list(map(int, input().split()))
a = [list(map(int, input().split())) for i in range(H)]
Q = int(eval(input()))
y = [[-1, -1] for i in range(H * W + 1)]
for i in range(H):
    for j in range(W):
        y[a[i][j]] = [i, j]
x = [0 for i in range(H * W + 1)]
for i in range(D + 1, H * W + 1):
    x[i] = x[i - D] + abs(y[i][0] - y[i - D][0]) + abs(y[i][1] - y[i - D][1])
for q in range(Q):
    L, R = list(map(int, input().split()))
    print((x[R] - x[L]))

-x = [[0] for i in range(D)] -for i in range(D): -    j = H * W - i - D -    while j > 0: -        tmp1, tmp2 = abs(y[j][0] - y[j + D][0]), abs(y[j][1] - y[j + D][1]) -        x[i].append(x[i][-1] + tmp1 + tmp2) -        j -= D +x = [0 for i in range(H * W + 1)] +for i in range(D + 1, H * W + 1): +    x[i] = x[i - D] + abs(y[i][0] - y[i - D][0]) + abs(y[i][1] - y[i - D][1]) -    i = (H * W - R) % D -    l = (H * W - i - R) // D -    r = (H * W - i - L) // D -    print((x[i][r] - x[i][l])) +    print((x[R] - x[L]))