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

arr = [[0 for i in range(2)] for j in range(H*W+1)]



for i in range(H):

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

  for j in range(len(tmp)):

    x = tmp[j]

    arr[x][0], arr[x][1] = i, j



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

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

  cumsum[i] = cumsum[i-D] + abs(arr[i-D][0] - arr[i][0]) + abs(arr[i-D][1] - arr[i][1])



Q = int(eval(input()))

for i in range(Q):

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

  print((cumsum[R] - cumsum[L]))
#memoryが少ない例。下手に２次元とかでやるより良いってこと？

H, W, D = [int(i) for i in input().split()]

px = [0] * 90001

py = [0] * 90001



for i in range(H):

    a = [int(i) for i in input().split()]

    for j, v in enumerate(a):

        px[v] = j

        py[v] = i



d = [0] * 90001

for i in range(D + 1, 90001):

    d[i] = d[i - D] + abs(px[i] - px[i - D]) + abs(py[i] - py[i - D])



Q = int(eval(input()))



for i in range(Q):

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

    ans = d[R] - d[L]

    print(ans)

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

# memoryが少ない例。下手に２次元とかでやるより良いってこと？
H, W, D = [int(i) for i in input().split()]
px = [0] * 90001
py = [0] * 90001
for i in range(H):
    a = [int(i) for i in input().split()]
    for j, v in enumerate(a):
        px[v] = j
        py[v] = i
d = [0] * 90001
for i in range(D + 1, 90001):
    d[i] = d[i - D] + abs(px[i] - px[i - D]) + abs(py[i] - py[i - D])
Q = int(eval(input()))
for i in range(Q):
    L, R = list(map(int, input().split()))
    ans = d[R] - d[L]
    print(ans)

-H, W, D = list(map(int, input().split())) -arr = [[0 for i in range(2)] for j in range(H * W + 1)] +# memoryが少ない例。下手に２次元とかでやるより良いってこと？ +H, W, D = [int(i) for i in input().split()] +px = [0] * 90001 +py = [0] * 90001 -    tmp = list(map(int, input().split())) -    for j in range(len(tmp)): -        x = tmp[j] -        arr[x][0], arr[x][1] = i, j -cumsum = [0] * (H * W + 1) -for i in range(D + 1, H * W + 1): -    cumsum[i] = ( -        cumsum[i - D] + abs(arr[i - D][0] - arr[i][0]) + abs(arr[i - D][1] - arr[i][1]) -    ) +    a = [int(i) for i in input().split()] +    for j, v in enumerate(a): +        px[v] = j +        py[v] = i +d = [0] * 90001 +for i in range(D + 1, 90001): +    d[i] = d[i - D] + abs(px[i] - px[i - D]) + abs(py[i] - py[i - D]) -    print((cumsum[R] - cumsum[L])) +    ans = d[R] - d[L] +    print(ans)