h,w,d=list(map(int,input().split()))

l=[[0,0]]+[[]for _ in range(h*w)]

for i in range(h):

    for j,a in enumerate(map(int,input().split())):

        l[a]=[i,j]

for i in range(h*w+1):

    if i<d:

        l[i].append(0)

    else:

        a,b=l[i]

        x,y,v=l[i-d]

        l[i].append(abs(x-a)+abs(y-b)+v)

for _ in range(int(eval(input()))):

    a,b=list(map(int,input().split()))

    print((l[b][2]-l[a][2]))
h,w,d=list(map(int,input().split()))

l=[[0,0]]+[[]for _ in range(h*w)]

for i in range(h):

    for j,a in enumerate(map(int,input().split())):

        l[a]=[i,j]

for i in range(h*w+1):

    if i<d:

        l[i].append(0)

    else:

        a,b=l[i]

        x,y,v=l[i-d]

        l[i].append(abs(x-a)+abs(y-b)+v)

l=[a[2]for a in l]

for _ in range(int(eval(input()))):

    a,b=list(map(int,input().split()))

    print((l[b]-l[a]))
h, w, d = list(map(int, input().split()))
l = [[0, 0]] + [[] for _ in range(h * w)]
for i in range(h):
    for j, a in enumerate(map(int, input().split())):
        l[a] = [i, j]
for i in range(h * w + 1):
    if i < d:
        l[i].append(0)
    else:
        a, b = l[i]
        x, y, v = l[i - d]
        l[i].append(abs(x - a) + abs(y - b) + v)
for _ in range(int(eval(input()))):
    a, b = list(map(int, input().split()))
    print((l[b][2] - l[a][2]))

h, w, d = list(map(int, input().split()))
l = [[0, 0]] + [[] for _ in range(h * w)]
for i in range(h):
    for j, a in enumerate(map(int, input().split())):
        l[a] = [i, j]
for i in range(h * w + 1):
    if i < d:
        l[i].append(0)
    else:
        a, b = l[i]
        x, y, v = l[i - d]
        l[i].append(abs(x - a) + abs(y - b) + v)
l = [a[2] for a in l]
for _ in range(int(eval(input()))):
    a, b = list(map(int, input().split()))
    print((l[b] - l[a]))

+l = [a[2] for a in l] -    print((l[b][2] - l[a][2])) +    print((l[b] - l[a]))