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

p=[0]*(h*w)

for i in range(h):

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

  for j in range(w):p[a[j]-1]=(i,j)

x=[0]*d

calc=lambda x1,y1,x2,y2:abs(x1-x2)+abs(y1-y2)

for i in range(d,h*w):

  x.append(x[i-d]+calc(p[i][0],p[i][1],p[i-d][0],p[i-d][1]))

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

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

  print((x[r-1]-x[l-1]))
h,w,d=list(map(int,input().split()))

b=[(0--(h*w-i)//d)*[0]for i in range(d)]

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

for i in range(h):

  for j in range(w):

    a[i][j]-=1

    b[a[i][j]%d][a[i][j]//d]=(i,j)

bb=[[0]for _ in range(d)]

for i in range(d):

  for j in range(1,len(b[i])):

    bb[i].append(bb[i][-1]+(abs(b[i][j-1][0]-b[i][j][0])+abs(b[i][j-1][1]-b[i][j][1])))

for ll,rr in [list(map(int,input().split()))for _ in range(int(eval(input())))]:

  l=ll-1

  r=rr-1

  print((bb[l%d][r//d]-bb[l%d][l//d]))
h, w, d = list(map(int, input().split()))
p = [0] * (h * w)
for i in range(h):
    a = list(map(int, input().split()))
    for j in range(w):
        p[a[j] - 1] = (i, j)
x = [0] * d
calc = lambda x1, y1, x2, y2: abs(x1 - x2) + abs(y1 - y2)
for i in range(d, h * w):
    x.append(x[i - d] + calc(p[i][0], p[i][1], p[i - d][0], p[i - d][1]))
for i in range(int(eval(input()))):
    l, r = list(map(int, input().split()))
    print((x[r - 1] - x[l - 1]))

h, w, d = list(map(int, input().split()))
b = [(0 - -(h * w - i) // d) * [0] for i in range(d)]
a = [list(map(int, input().split())) for _ in range(h)]
for i in range(h):
    for j in range(w):
        a[i][j] -= 1
        b[a[i][j] % d][a[i][j] // d] = (i, j)
bb = [[0] for _ in range(d)]
for i in range(d):
    for j in range(1, len(b[i])):
        bb[i].append(
            bb[i][-1]
            + (abs(b[i][j - 1][0] - b[i][j][0]) + abs(b[i][j - 1][1] - b[i][j][1]))
        )
for ll, rr in [list(map(int, input().split())) for _ in range(int(eval(input())))]:
    l = ll - 1
    r = rr - 1
    print((bb[l % d][r // d] - bb[l % d][l // d]))

-p = [0] * (h * w) +b = [(0 - -(h * w - i) // d) * [0] for i in range(d)] +a = [list(map(int, input().split())) for _ in range(h)] -    a = list(map(int, input().split())) -        p[a[j] - 1] = (i, j) -x = [0] * d -calc = lambda x1, y1, x2, y2: abs(x1 - x2) + abs(y1 - y2) -for i in range(d, h * w): -    x.append(x[i - d] + calc(p[i][0], p[i][1], p[i - d][0], p[i - d][1])) -for i in range(int(eval(input()))): -    l, r = list(map(int, input().split())) -    print((x[r - 1] - x[l - 1])) +        a[i][j] -= 1 +        b[a[i][j] % d][a[i][j] // d] = (i, j) +bb = [[0] for _ in range(d)] +for i in range(d): +    for j in range(1, len(b[i])): +        bb[i].append( +            bb[i][-1] +            + (abs(b[i][j - 1][0] - b[i][j][0]) + abs(b[i][j - 1][1] - b[i][j][1])) +        ) +for ll, rr in [list(map(int, input().split())) for _ in range(int(eval(input())))]: +    l = ll - 1 +    r = rr - 1 +    print((bb[l % d][r // d] - bb[l % d][l // d]))