# -*- coding: utf-8 -*-

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

dd = {}

for hi in range(h):

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

    for wi in range(w):

        dd[line[wi]] = (hi, wi)

q = int(eval(input()))

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



acc = [0]*(h*w+1)

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

    if i<=d:

        acc[i] = 0

        continue



    h1,w1 = dd[i]

    h2,w2 = dd[i-d]

    acc[i] = acc[i-d] + abs(h1-h2) + abs(w1-w2)



for (l,r) in lr:

    print((acc[r] - acc[l]))

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

ad = {}

for i in range(h):

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

    for j in range(w):

        ad[line[j]] = (i,j)

q = int(eval(input()))

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



cl = [0]*(h*w+1)

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

    if i+d<len(cl):

        f = ad[i]

        t = ad[i+d]

        cl[i+d] = cl[i] + abs(f[0]-t[0]) + abs(f[1]-t[1])



for l,r in lr:

    print((cl[r]-cl[l]))
# -*- coding: utf-8 -*-
h, w, d = list(map(int, input().split()))
dd = {}
for hi in range(h):
    line = list(map(int, input().split()))
    for wi in range(w):
        dd[line[wi]] = (hi, wi)
q = int(eval(input()))
lr = [list(map(int, input().split())) for _ in range(q)]
acc = [0] * (h * w + 1)
for i in range(h * w + 1):
    if i <= d:
        acc[i] = 0
        continue
    h1, w1 = dd[i]
    h2, w2 = dd[i - d]
    acc[i] = acc[i - d] + abs(h1 - h2) + abs(w1 - w2)
for (l, r) in lr:
    print((acc[r] - acc[l]))

h, w, d = list(map(int, input().split()))
ad = {}
for i in range(h):
    line = list(map(int, input().split()))
    for j in range(w):
        ad[line[j]] = (i, j)
q = int(eval(input()))
lr = [list(map(int, input().split())) for _ in range(q)]
cl = [0] * (h * w + 1)
for i in range(1, h * w + 1):
    if i + d < len(cl):
        f = ad[i]
        t = ad[i + d]
        cl[i + d] = cl[i] + abs(f[0] - t[0]) + abs(f[1] - t[1])
for l, r in lr:
    print((cl[r] - cl[l]))

-# -*- coding: utf-8 -*- -dd = {} -for hi in range(h): +ad = {} +for i in range(h): -    for wi in range(w): -        dd[line[wi]] = (hi, wi) +    for j in range(w): +        ad[line[j]] = (i, j) -acc = [0] * (h * w + 1) -for i in range(h * w + 1): -    if i <= d: -        acc[i] = 0 -        continue -    h1, w1 = dd[i] -    h2, w2 = dd[i - d] -    acc[i] = acc[i - d] + abs(h1 - h2) + abs(w1 - w2) -for (l, r) in lr: -    print((acc[r] - acc[l])) +cl = [0] * (h * w + 1) +for i in range(1, h * w + 1): +    if i + d < len(cl): +        f = ad[i] +        t = ad[i + d] +        cl[i + d] = cl[i] + abs(f[0] - t[0]) + abs(f[1] - t[1]) +for l, r in lr: +    print((cl[r] - cl[l]))