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

ind={}

for i in range(h):

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



    for j in range(w):

        ind[l[j]]=(i,j)

dp=[0]*(h*w)

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

    x,y=ind[i]

    z,q=ind[i-d]

    dp[i-1]=abs(z-x)+abs(y-q)+dp[i-d-1]





q=int(eval(input()))

for i in range(q):

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

    print((dp[r-1]-dp[l-1]))
import sys

input=sys.stdin.buffer.readline

inputs=sys.stdin.buffer.readlines

sys.setrecursionlimit(10**9)

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

inds={}

for i in range(h):

    for D,j in enumerate(input().split()):

        inds[int(j)-1]=(i,D)

nows=[[0]for c in range(d)]



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

    a,b=inds[k]

    x,y=inds[k-d]

    k%=d

    nows[k].append(nows[k][-1]+abs(a-x)+abs(b-y))

q=eval(input())

for i in inputs():

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

    l-=1;r-=1

    l,b=divmod(l,d)

    r,b=divmod(r,d)

    print((nows[b][r]-nows[b][l]))

h, w, d = list(map(int, input().split()))
ind = {}
for i in range(h):
    l = list(map(int, input().split()))
    for j in range(w):
        ind[l[j]] = (i, j)
dp = [0] * (h * w)
for i in range(d + 1, h * w + 1):
    x, y = ind[i]
    z, q = ind[i - d]
    dp[i - 1] = abs(z - x) + abs(y - q) + dp[i - d - 1]
q = int(eval(input()))
for i in range(q):
    l, r = list(map(int, input().split()))
    print((dp[r - 1] - dp[l - 1]))

import sys

input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines
sys.setrecursionlimit(10**9)
h, w, d = list(map(int, input().split()))
inds = {}
for i in range(h):
    for D, j in enumerate(input().split()):
        inds[int(j) - 1] = (i, D)
nows = [[0] for c in range(d)]
for k in range(d, h * w):
    a, b = inds[k]
    x, y = inds[k - d]
    k %= d
    nows[k].append(nows[k][-1] + abs(a - x) + abs(b - y))
q = eval(input())
for i in inputs():
    l, r = list(map(int, i.split()))
    l -= 1
    r -= 1
    l, b = divmod(l, d)
    r, b = divmod(r, d)
    print((nows[b][r] - nows[b][l]))

+import sys + +input = sys.stdin.buffer.readline +inputs = sys.stdin.buffer.readlines +sys.setrecursionlimit(10**9) -ind = {} +inds = {} -    l = list(map(int, input().split())) -    for j in range(w): -        ind[l[j]] = (i, j) -dp = [0] * (h * w) -for i in range(d + 1, h * w + 1): -    x, y = ind[i] -    z, q = ind[i - d] -    dp[i - 1] = abs(z - x) + abs(y - q) + dp[i - d - 1] -q = int(eval(input())) -for i in range(q): -    l, r = list(map(int, input().split())) -    print((dp[r - 1] - dp[l - 1])) +    for D, j in enumerate(input().split()): +        inds[int(j) - 1] = (i, D) +nows = [[0] for c in range(d)] +for k in range(d, h * w): +    a, b = inds[k] +    x, y = inds[k - d] +    k %= d +    nows[k].append(nows[k][-1] + abs(a - x) + abs(b - y)) +q = eval(input()) +for i in inputs(): +    l, r = list(map(int, i.split())) +    l -= 1 +    r -= 1 +    l, b = divmod(l, d) +    r, b = divmod(r, d) +    print((nows[b][r] - nows[b][l]))