#!/usr/bin/env python



from collections import deque

import itertools as it

import sys

import math



sys.setrecursionlimit(1000000)



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

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

for i in range(H):

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

    for j in range(W):

        m[A[j]] = (i, j)



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



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

    x1, y1 = m[i + 1]

    x2, y2 = m[i + 1 - D]

    dist = abs(x1 - x2) + abs(y1 - y2)

    ls = DP[i % D]

    ls.append(ls[-1] + dist)



Q = eval(input())



for i in range(Q):

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

    ls = DP[(R - 1) % D]

    print(ls[(R - 1) / D] - ls[(L - 1) / D])
#!/usr/bin/env python



from collections import deque

import itertools as it

import sys

import math



sys.setrecursionlimit(1000000)



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

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

for i in range(H):

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

    for j in range(W):

        m[A[j]] = (i, j)



DP = [0] * D



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

    x1, y1 = m[i + 1]

    x2, y2 = m[i + 1 - D]

    dist = abs(x1 - x2) + abs(y1 - y2)

    DP.append(DP[i - D] + dist)



Q = eval(input())



for i in range(Q):

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

    print(DP[R - 1] - DP[L - 1])
#!/usr/bin/env python
from collections import deque
import itertools as it
import sys
import math

sys.setrecursionlimit(1000000)
H, W, D = list(map(int, input().split()))
m = [0] * (H * W + 1)
for i in range(H):
    A = list(map(int, input().split()))
    for j in range(W):
        m[A[j]] = (i, j)
DP = [[0] for i in range(D)]
for i in range(D, H * W):
    x1, y1 = m[i + 1]
    x2, y2 = m[i + 1 - D]
    dist = abs(x1 - x2) + abs(y1 - y2)
    ls = DP[i % D]
    ls.append(ls[-1] + dist)
Q = eval(input())
for i in range(Q):
    L, R = list(map(int, input().split()))
    ls = DP[(R - 1) % D]
    print(ls[(R - 1) / D] - ls[(L - 1) / D])

#!/usr/bin/env python
from collections import deque
import itertools as it
import sys
import math

sys.setrecursionlimit(1000000)
H, W, D = list(map(int, input().split()))
m = [0] * (H * W + 1)
for i in range(H):
    A = list(map(int, input().split()))
    for j in range(W):
        m[A[j]] = (i, j)
DP = [0] * D
for i in range(D, H * W):
    x1, y1 = m[i + 1]
    x2, y2 = m[i + 1 - D]
    dist = abs(x1 - x2) + abs(y1 - y2)
    DP.append(DP[i - D] + dist)
Q = eval(input())
for i in range(Q):
    L, R = list(map(int, input().split()))
    print(DP[R - 1] - DP[L - 1])

-DP = [[0] for i in range(D)] +DP = [0] * D -    ls = DP[i % D] -    ls.append(ls[-1] + dist) +    DP.append(DP[i - D] + dist) -    ls = DP[(R - 1) % D] -    print(ls[(R - 1) / D] - ls[(L - 1) / D]) +    print(DP[R - 1] - DP[L - 1])