You are a magical girl with the ability to teleport pieces on a grid. The grid has H rows and W columns, with integers from 1 to H×W written throughout. You need to take Q tests, each involving moving a piece from L to R, where R-L is a multiple of D. For each test, find the sum of magic points consumed. Constraints: 1 ≤ H,W ≤ 300, 1 ≤ D ≤ H×W, 1 ≤ A_{i,j} ≤ H×W, A_{i,j} ≠ A_{x,y} ((i,j) ≠ (x,y)), 1 ≤ Q ≤ 10^5, 1 ≤ L_i ≤ R_i ≤ H×W. Input format: H W D, followed by the grid, Q, and test details. Output the sum of magic points for each test. Examples are provided.

# Buggy version:
h,w,d = map(int, input().split())

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

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

for i in range(w):
    for j in range(h):
        s = ab[i][j]
        dp[s] =[i,j]
        
dpp= [0]*(h*w+1)

for k in range(d+1,h*w+1):
#    print(k)
    dpp[k] = dpp[k-d] + abs(dp[k][0]-dp[k-d][0]) +abs(dp[k][1]-dp[k-d][1])
    
q = int(input())

for x in range(q):
    a,b = map(int, input().split())
    print(dpp[b]-dpp[a])

# Fixed version:
h,w,d = map(int, input().split())

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

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

for i in range(h):
    for j in range(w):
        s = ab[i][j]
        dp[s] =[i,j]
        
dpp= [0]*(h*w+1)

for k in range(d+1,h*w+1):
#    print(k)
    dpp[k] = dpp[k-d] + abs(dp[k][0]-dp[k-d][0]) +abs(dp[k][1]-dp[k-d][1])
    
q = int(input())

for x in range(q):
    a,b = map(int, input().split())
    print(dpp[b]-dpp[a])

# Buggy version:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 9)
MOD = 10 ** 9 + 7

from collections import defaultdict

H, W, D = map(int, input().split())
A = [list(map(int, input().split()))  for _ in range(H)]

dic = defaultdict(list)

for h in range(W):
    for w in range(W):
        dic[A[h][w]] = [h, w]

def calc(l, r):
    return abs(dic[l][0] - dic[r][0]) + abs(dic[l][1] - dic[r][1])

lst = [0] * (H * W + 1)
for d in range(1, D + 1):
    tmp = d
    while tmp + D <= (H * W):
        lst[tmp + D] = lst[tmp] + calc(tmp, tmp + D)
        tmp += D

# print (lst)
Q = int(input())
for _ in range(Q):
    L, R = map(int, input().split())
    ans = lst[R] - lst[L]
    print (ans)


# Fixed version:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 9)
MOD = 10 ** 9 + 7

from collections import defaultdict

H, W, D = map(int, input().split())
A = [list(map(int, input().split()))  for _ in range(H)]

dic = defaultdict(list)

for h in range(H):
    for w in range(W):
        dic[A[h][w]] = [h, w]

def calc(l, r):
    return abs(dic[l][0] - dic[r][0]) + abs(dic[l][1] - dic[r][1])

lst = [0] * (H * W + 1)
for d in range(1, D + 1):
    tmp = d
    while tmp + D <= (H * W):
        lst[tmp + D] = lst[tmp] + calc(tmp, tmp + D)
        tmp += D

# print (lst)
Q = int(input())
for _ in range(Q):
    L, R = map(int, input().split())
    ans = lst[R] - lst[L]
    print (ans)

# Buggy version:
n,m,d = map(int, input().split())

grid = []

buf = {}

for j in range(n):
    grid.append(list(map(int, input().split())))
    for k in range(len(grid[j])):
        buf[grid[j][k]] = (j,k)
q = int(input())
al = []

cost = [0] * ((n*m)+1)

for i in range(d+1,n*m):
    cost[i] = cost[i-d] + abs(buf[i-d][0] - buf[i][0]) + abs(buf[i-d][1] - buf[i][1])
print(cost)
for _ in range(q):
    l,r = map(int, input().split())
    al.append([l,r])
    

for l,r in al:
    print(cost[r]-cost[l])
            
                


# Fixed version:
n,m,d = map(int, input().split())

grid = []

buf = {}

for j in range(n):
    grid.append(list(map(int, input().split())))
    for k in range(len(grid[j])):
        buf[grid[j][k]] = (j,k)
q = int(input())
al = []

cost = [0] * ((n*m)+1)

for i in range(d+1,n*m+1):
    cost[i] = cost[i-d] + abs(buf[i-d][0] - buf[i][0]) + abs(buf[i-d][1] - buf[i][1])

for _ in range(q):
    l,r = map(int, input().split())
    al.append([l,r])
    

for l,r in al:
    print(cost[r]-cost[l])

# Buggy version:
import numpy as np
import sys
input = sys.stdin
h, w, d = map(int, input().split())
num = h * w
mass = np.array([[0, 0] for _ in range(num + 1)])
mp = np.zeros(num+1, dtype=int)
for i in range(h):
    for j, a in enumerate(list(map(int, input().split()))):
        mass[a] += [i, j]
for i in range(d+1, num+1):
    mp[i] = mp[i-d] + np.sum(abs(mass[i]-mass[i-d]))
q = int(input())
for _ in range(q):
    l, r = map(int, input().split())
    print(mp[r]-mp[l])


# Fixed version:
import numpy as np
import sys
input = sys.stdin.readline
h, w, d = map(int, input().split())
num = h * w
mass = np.array([(0, 0) for _ in range(num + 1)])
mp = np.zeros(num+1)
for i in range(1, h+1):
    for j, a in enumerate(map(int, input().split())):
        mass[a] = [i, j+1]
for i in range(d+1, num+1):
    mp[i] = mp[i-d] + np.sum(abs(mass[i]-mass[i-d]))
q = int(input())
for _ in range(q):
    l, r = map(int, input().split())
    print(int(mp[r]-mp[l]))

# Buggy version:
# coding: utf-8
# Your code here!
#途中

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

A=[]
for i in range(H):
    A.append(list(map(int,input().split())))

loc=[[0,0] for i in range(W*H)]

#print(loc)

for i in range(H):
    for j in range(W):
        loc[A[i][j]-1][0]=i
        loc[A[i][j]-1][1]=j
        #print(loc)
print(loc)

cost=[[0]*((H*W)//D) for i in range(D)]

for i in range((H*W)%D):
    cost[i].append(0)

for i in range(D):
    pass
    count=1
    temp=0
    while temp<(H*W):
        temp=i+D*count
        cost[temp%D][temp//D]=abs(loc[temp][0]-loc[temp-D][0])+abs(loc[temp][1]-loc[temp-D][1])+cost[temp%D][temp//D-1]
        count+=1

print(cost)



# Fixed version:
# coding: utf-8
# Your code here!
#途中

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

A=[]
for i in range(H):
    A.append(list(map(int,input().split())))

loc=[[0,0] for i in range(W*H)]

#print(loc)

for i in range(H):
    for j in range(W):
        loc[A[i][j]-1][0]=i
        loc[A[i][j]-1][1]=j
        #print(loc)
#print(loc)

cost=[[0]*((H*W)//D) for i in range(D)]

for i in range((H*W)%D):
    cost[i].append(0)

for i in range(D):
    pass
    count=1
    temp=i
    while temp+D<(H*W):
        temp=i+D*count
        cost[temp%D][temp//D]=abs(loc[temp][0]-loc[temp-D][0])+abs(loc[temp][1]-loc[temp-D][1])+cost[temp%D][temp//D-1]
        count+=1
        #print(cost)
cost[-1]=[0]+cost[-1]

Q=int(input())
for _ in range(Q):
    x,y=map(int,input().split())
    #print(cost[x%D-1][x//D-1])
    print(cost[y%D-1][y//D]-cost[x%D-1][x//D])

#print(cost)

# Buggy version:

#import numpy as np


def acinput():
    return list(map(int, input().split(" ")))


mod = 10**9+7


def factorial(n):
    fact = 1
    for integer in range(1, n + 1):
        fact *= integer
    return fact


H, W, D = acinput()
# Ad={}
Ad = [0]*(H*W+1)
for i in range(H):
    ar = acinput()
    for j, sar in enumerate(ar):
        # Ad[sar]=np.array((i,j))
        Ad[sar] = (i, j)

#dp = [[0 for j in range(H*W+1)]for i in range(H*W+1)]
d = [0]*(H*W+1)

# for x in range(1, H*W+1):
#    dp[x][x]=0

y = D+1
while True:
        if y > H*W:
            break
        # print(x,y)
        #tmp = Ad[y]-Ad[y-D]
        #S = np.sum(np.abs(tmp[0])+abs(tmp[1]))
        #tmp = Ad[y]-Ad[y-D]
        S = abs(Ad[y][0]-Ad[y-D][0])+abs(Ad[y][1]-Ad[y-D][1])

        # dp[x][y]=dp[x][y-D]+S
        d[y] = d[y-D]+S
        y += 1


# print(np.array(dp))

Q = int(input())
for i in range(Q):
    l, r = acinput()
    print(d[r]-d[l])


# print(Ad)
# print(np.array(dp))
print(d)

# Fixed version:

#import numpy as np


def acinput():
    return list(map(int, input().split(" ")))


mod = 10**9+7


def factorial(n):
    fact = 1
    for integer in range(1, n + 1):
        fact *= integer
    return fact


H, W, D = acinput()
# Ad={}
Ad = [0]*(H*W+1)
for i in range(H):
    ar = acinput()
    for j, sar in enumerate(ar):
        # Ad[sar]=np.array((i,j))
        Ad[sar] = (i, j)

#dp = [[0 for j in range(H*W+1)]for i in range(H*W+1)]
d = [0]*(H*W+1)

# for x in range(1, H*W+1):
#    dp[x][x]=0

y = D+1
while True:
        if y > H*W:
            break
        # print(x,y)
        #tmp = Ad[y]-Ad[y-D]
        #S = np.sum(np.abs(tmp[0])+abs(tmp[1]))
        #tmp = Ad[y]-Ad[y-D]
        S = abs(Ad[y][0]-Ad[y-D][0])+abs(Ad[y][1]-Ad[y-D][1])

        # dp[x][y]=dp[x][y-D]+S
        d[y] = d[y-D]+S
        y += 1


# print(np.array(dp))

Q = int(input())
for i in range(Q):
    l, r = acinput()
    print(d[r]-d[l])


# print(Ad)
# print(np.array(dp))
#print(d)

# Buggy version:
import math
h, w, d = list(map(int, input().split()))
grid = []
num = [[] for i in range(h*w+1)]
for i in range(h):
    grid.append(list(map(int, input().split())))
for i in range(h):
    for j in range(w):
        num[grid[i][j]]=[j+1, i+1]
k = math.ceil((h*w+1) / d)
#initialize
cost = [[0 for i in range(k)] for j in range(d)]
for i in range(d + 1,h*w+1):
    x, y = num[i]
    prex, prey = num[i - d]
    cost[i % d][i//d] = abs(prex - x) + abs(prey - y)
    cost[i % d][i//d] += cost[i % d][(i - d)// d]
print(cost) 
q = int(input())
for i in range(q):
    l, r = map(int, input().split())
    print(cost[r%d][r//d] - cost[l%d][l//d])


# Fixed version:
import math
h, w, d = list(map(int, input().split()))
grid = []
num = [[] for i in range(h*w+1)]
for i in range(h):
    grid.append(list(map(int, input().split())))
for i in range(h):
    for j in range(w):
        num[grid[i][j]]=[j+1, i+1]
k = math.ceil((h*w+1) / d)
#initialize
cost = [[0 for i in range(k)] for j in range(d)]
for i in range(d + 1,h*w+1):
    x, y = num[i]
    prex, prey = num[i - d]
    cost[i % d][i//d] = abs(prex - x) + abs(prey - y)
    cost[i % d][i//d] += cost[i % d][(i - d)// d]
q = int(input())
for i in range(q):
    l, r = map(int, input().split())
    print(cost[r%d][r//d] - cost[l%d][l//d])

# Buggy version:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

H, W, D = lr()
A = [lr() for _ in range(H)]
Q = ir()
grid = [None] * (H*W + 1) # 1-indexed
for i in range(H):
    for j in range(W):
        grid[A[i][j]] = (i, j)

next_D = [0] * (H*W + 1)
for i in range(1, H*W + 1 - D):
    next_D[i] = abs(grid[i+D][0] - grid[i][0]) + abs(grid[i+D][1] - grid[i][1])

jump = [[0] * (H*W + 1) for i in range(H*W + 1)]
for i in range(1, H*W + 1 - D):
    for j in range(i+D, H*W + 1 - D, D):
        jump[i][j] = next_D[j-D]
        if j-D > i:
            jump[i][j] += jump[i][j-D]

#print(next_D)
#print(jump)
for i in range(Q):
    l, r = lr()
    answer = jump[l][r]
    print(answer)

# 49


# Fixed version:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

H, W, D = lr()
A = [lr() for _ in range(H)]
Q = ir()
grid = [None] * (H*W + 1) # 1-indexed
for i in range(H):
    for j in range(W):
        grid[A[i][j]] = (i, j)

next_D = [0] * (H*W + 1)
for i in range(1+D, H*W + 1):
    next_D[i] = abs(grid[i][0] - grid[i-D][0]) + abs(grid[i][1] - grid[i-D][1])
    next_D[i] += next_D[i-D]

for i in range(Q):
    l, r = lr()
    answer = next_D[r] - next_D[l]
    print(answer)

# 49

# Buggy version:
h,w,d = map(int, input().split())

a = [[0 for _ in range(w)] for _ in range(h)]
masu = {}
for i in range(h):
    a[i] = list(map(int, input().split())
    for j in range(w):
        masu[a[i][j]] = (i,j)
"""
masu = {}
for i in range(h):
    for j in range(w):
        masu[a[i][j]] = (i,j)
"""
point = [0] * (h*w)
for i in range(1,h*w-d+1):
    point[i] = abs(masu[i][0] - masu[i+d][0]) + abs(masu[i][1] - masu[i+d][1])


q = int(input())
ans = [0] * q
for i in range(q):
    l, r = map(int, input().split())
    if l == r:
        ans[i] = 0
    else:
        ans[i] = sum(point[l:r:d])
 
for i in range(q):
    print(ans[i])


# Fixed version:
h,w,d = map(int, input().split())

a = [[0 for _ in range(w)] for _ in range(h)]
masu = {}
for i in range(h):
    a[i] = list(map(int, input().split()))
    for j in range(w):
        masu[a[i][j]] = (i,j)

point = [0] * (h*w+10)
for i in range(d+1,h*w+1):
    point[i] = point[i-d] + abs(masu[i][0] - masu[i-d][0]) + abs(masu[i][1] - masu[i-d][1])


q = int(input())
ans = [0] * q
for i in range(q):
    l, r = map(int, input().split())
    if l == r:
        ans[i] = 0
    else:
        ans[i] = point[r] - point[l]
 
for i in range(q):
    print(ans[i])

# Buggy version:
from functools import partial
from itertools import islice


def take(n, iterable):
    return list(islice(iterable, n))


def chunked(iterable, n):
    return iter(partial(take, n, iter(iterable)), [])


def distance(x, y):
    return abs(x[0] - y[0]) + abs(x[1] - y[1])


def solve(s):
    h, w, d, *aqlr = map(int, s.split())
    n = h * w
    pos = [(i // w, i % w) for i, _a in enumerate(aqlr[:n])]
    cost = [0] * (n + 1)
    for i in range(d + 1, n + 1):
        cost[i] = cost[i - d] + distance(pos[i - d], pos[i])
    return "\n".join(["%d" % (cost[r] - cost[l]) for l, r in chunked(aqlr[n + 1:], 2)])


n, m, d = map(int, input().split())
l = '{} {} {}\n'.format(n, m, d) + '\n'.join([input() for _ in range(n)])
q, = map(int, input().split())
l += '\n{}\n'.format(q) + '\n'.join([input() for _ in range(q)])
print(solve(l))


# Fixed version:
from functools import partial
from itertools import islice


def take(n, iterable):
    return list(islice(iterable, n))


def chunked(iterable, n):
    return iter(partial(take, n, iter(iterable)), [])


def distance(x, y):
    return abs(x[0] - y[0]) + abs(x[1] - y[1])


def solve(s):
    h, w, d, *aqlr = map(int, s.split())
    a, q, lr = aqlr[:h * w], aqlr[h * w], aqlr[h * w + 1:]
    n = h * w
    pos = [0] * (n + 1)
    for i, _a in enumerate(a):
        pos[_a] = (i // w, i % w)
    cost = [0] * (n + 1)
    for i in range(d + 1, n + 1):
        cost[i] = cost[i-d]+distance(pos[i - d], pos[i])
    ans = []
    for l, r in chunked(lr, 2):
        ans.append("%d" % (cost[r] - cost[l]))
    return "\n".join(ans)


n, m, d = map(int, input().split())
l = '{} {} {}\n'.format(n, m, d) + '\n'.join([input() for _ in range(n)])
q, = map(int, input().split())
l += '\n{}\n'.format(q) + '\n'.join([input() for _ in range(q)])
print(solve(l))

# Buggy version:
h,w,d=map(int,input().split())
l=[list(map(int,input().split())) for i in range(h)]
L=[0 for i in range(h*w)]
for i in range(h):
  for j in range(w):
    L[l[i][j]-1]=[i,j]

sumL=[0 for i in range(h*w+1)]
for i in range(h*w):
  if i>=d:
    sumL[i+1]=sumL[i+1-d]+abs(L[i][0]-L[i-d][0])+abs(L[i][1]-L[i-d][1])
print(sumL)
q=int(input())
QL=[list(map(int,input().split())) for i in range(q)]
for i in range(q):
  print(sumL[QL[i][1]]-sumL[QL[i][0]])

# Fixed version:
h,w,d=map(int,input().split())
l=[list(map(int,input().split())) for i in range(h)]
L=[0 for i in range(h*w)]
for i in range(h):
  for j in range(w):
    L[l[i][j]-1]=[i,j]

sumL=[0 for i in range(h*w+1)]
for i in range(h*w):
  if i>=d:
    sumL[i+1]=sumL[i+1-d]+abs(L[i][0]-L[i-d][0])+abs(L[i][1]-L[i-d][1])

q=int(input())
QL=[list(map(int,input().split())) for i in range(q)]
for i in range(q):
  print(sumL[QL[i][1]]-sumL[QL[i][0]])

# Buggy version:
import sys
import math
import numpy as np
stdin = sys.stdin
 
ni = lambda: int(ns())
na = lambda: list(map(int, input().split()))
ns = lambda: input()
H,W,D = na()
f= [list(map(int,input().split())) for i in range(H)]
#print(f)
f = np.array(f)
Q=int(input())
'''
li = [0]*(H*W+2)
for i in range(1,D+1):
    li[i]=0
    h_=int(np.where(f==i)[0])
    w_=int(np.where(f==i)[1])
    for j in range(i+D,H*W+1,D):
        h_n=int(np.where(f==j)[0])
        w_n=int(np.where(f==j)[1])
        li[j] = li[j-D]+abs(h_ - h_n)+abs(w_ - w_n)
        h_ = h_n
        w_ = w_n
for i in range(Q):
    L,R = na()
    print(li[R]-li[L])
'''

li ={}
for i in range(H):
    for j in range(W):
        li[f[i][j]]=[i,j]
res=[0]*(H*W+1)
for i in range(1,D+1):
    for j in range(i+D,W*H+1,D):
        res[j] += abs(li[j-D][0]-li[j][0]) + abs(li[j-D][1]-li[j][1])

for i in range(Q):
    L,R = na()
    print(res[R]-res[L])


# Fixed version:
import sys
import math
import numpy as np
stdin = sys.stdin
 
ni = lambda: int(ns())
na = lambda: list(map(int, input().split()))
ns = lambda: input()
H,W,D = na()
f= [list(map(int,input().split())) for i in range(H)]
#print(f)
f = np.array(f)
Q=int(input())
'''
li = [0]*(H*W+2)
for i in range(1,D+1):
    li[i]=0
    h_=int(np.where(f==i)[0])
    w_=int(np.where(f==i)[1])
    for j in range(i+D,H*W+1,D):
        h_n=int(np.where(f==j)[0])
        w_n=int(np.where(f==j)[1])
        li[j] = li[j-D]+abs(h_ - h_n)+abs(w_ - w_n)
        h_ = h_n
        w_ = w_n
for i in range(Q):
    L,R = na()
    print(li[R]-li[L])
'''

li ={}
for i in range(H):
    for j in range(W):
        li[f[i][j]]=[i+1,j+1]
res=[0]*(H*W+1)
for i in range(1,D+1):
    for j in range(i+D,W*H+1,D):
        #print("j",j)
        #print(li[j][0],li[j][1])
        res[j] = res[j-D] +abs(li[j-D][0]-li[j][0]) + abs(li[j-D][1]-li[j][1])
#print(res)
for i in range(Q):
    L,R = na()
    print(res[R]-res[L])

# Buggy version:
h,w,d = map(int,input().split())
hw = [[] for _ in range(h*w+1)]
hw[0] = [0,0]
for i in range(h):
    row = list(map(int,input().split()))
    for j in range(w):
        hw[row[j]] = [i,j]
print(hw)

a = [0 for _ in range(h*w+1)]
for i in range(d+1,h*w+1):
    a[i] = a[i-d] + abs(hw[i][0] - hw[i-d][0]) + abs(hw[i][1] - hw[i-d][1])

q = int(input())
for i in range(q):
    L,R = map(int,input().split())
    print(a[R] - a[L])

# Fixed version:
h,w,d = map(int,input().split())
hw = [[] for _ in range(h*w+1)]
for i in range(h):
    row = list(map(int,input().split()))
    for j in range(w):
        hw[row[j]] = [i,j]
 
a = [0 for _ in range(h*w+1)]
for i in range(d+1,h*w+1):
    a[i] = a[i-d] + abs(hw[i][0] - hw[i-d][0]) + abs(hw[i][1] - hw[i-d][1])
 
q = int(input())
for i in range(q):
    L,R = map(int,input().split())
    print(a[R] - a[L])

# Buggy version:
H,W,D=map(int,input().split())
A=[list(map(int,input().split())) for _ in range(H)]
Q=int(input())
X=[[0,0] for _ in range(H*W)]
for i in range(H):
    for j in range(W):
        X[A[i][j]][0]=i
        X[A[i][j]][1]=j
M=[0]*(H*W+1)
for d in range(D+1,H*W+1):
        M[d]=abs(X[d][0]-X[d-D][0])+abs(X[d][1]-X[d-D][1])+M[d-D]

for i in range(Q):
    L,R=map(int,input().split())
    print(M[R]-M[L])

# Fixed version:
H, W, D = map( int, input().split())
A = [ list( map( int, input().split())) for _ in range(H)]
P = [(0,0)]*(H*W+1)
for i in range(H):
    for j in range(W):
        P[A[i][j]] = (i,j)
d = [0]*(H*W+1)
for i in range(D+1,H*W+1):
    d[i] = d[i-D] + abs(P[i][0] - P[i-D][0]) + abs(P[i][1] - P[i-D][1])
Q = int( input())
for _ in range(Q):
    L, R = map( int, input().split())
    print(d[R]-d[L])

# Buggy version:
ai = lambda: list(map(int, input().split()))

h,w,d = ai()
ph = [0 for _ in range(h*w + 1)]
pw = [0 for _ in range(h*w + 1)]

for i in range(h):
    a = ai()
    for j in range(w):
        ph[a[j]] = i
        pw[a[j]] = j


score = [0 for _ in range(h*w + 1)]
for i in range(d+1, h*w+1):
    score[i] = score[i-d] + abs(ph[i]-ph[i-d]) + abs(pw[i]-pw[i-d])

print(score)

q = int(input())
for _ in range(q):
    l,r = ai()
    print(score[r]-score[l])

# Fixed version:
ai = lambda: list(map(int, input().split()))

h,w,d = ai()
ph = [0 for _ in range(h*w + 1)]
pw = [0 for _ in range(h*w + 1)]

for i in range(h):
    a = ai()
    for j in range(w):
        ph[a[j]] = i
        pw[a[j]] = j


score = [0 for _ in range(h*w + 1)]
for i in range(d+1, h*w+1):
    score[i] = score[i-d] + abs(ph[i]-ph[i-d]) + abs(pw[i]-pw[i-d])


q = int(input())
for _ in range(q):
    l,r = ai()
    print(score[r]-score[l])

# Buggy version:
H, W, D=map(int, input().split())
pos={}
for i in range(H):
    A=list(map(int, input().split()))
    for j in range(W):
        pos[A[j]]=(i, j)
Q=int(input())
p=0
for i in range(Q):
    L, R=list(map(int, input().split()))
    for j in range((R-L)//D):
        p+=abs(pos[L+D*j][0]-pos[L+D*(j+1)][0])+abs(pos[L+D*j][1]-pos[L+D*(j+1)][1])
    print(p)


# Fixed version:
H, W, D=map(int, input().split())
pos={}
for i in range(H):
    A=list(map(int, input().split()))
    for j in range(W):
        pos[A[j]]=(i, j)
p=[0]*(H*W+1)
for i in range(D+1,H*W+1):
    p[i]=p[i-D]+abs(pos[i][0]-pos[i-D][0])+abs(pos[i][1]-pos[i-D][1])
Q=int(input())
for _ in range(Q):
    L, R=map(int, input().split())
    print(p[R]-p[L])

# Buggy version:
H,W,D=list(map(int,input().split()))
X=[(0,0) for i in range(H*W+1)]

for i in range(1,H+1):
	A=list(map(int,input().split()))
	for idx,a in enumerate(A):
		X[a]=(i,idx+1)

Q=int(input())
L=R=[]
S=[0]*(H*W+1)

for i in range(Q):
	l,r=list(map(int,input().split()))
	L.append(l)
	R.append(r)

for i in range(D+1,H*W+1):
	S[i]=S[i-D]+abs(X[i][0]-X[i-D][0])+abs(X[i][1]-X[i-D][1])

for i in range(Q):
	print(S[R[i]]-S[L[i]])

# Fixed version:
H,W,D=list(map(int,input().split()))
X=[(0,0) for i in range(H*W+1)]

for i in range(1,H+1):
	A=list(map(int,input().split()))
	for idx,a in enumerate(A):
		X[a]=(i,idx+1)

Q=int(input())
L=[]
R=[]
S=[0]*(H*W+1)

for i in range(Q):
	l,r=list(map(int,input().split()))
	L.append(l)
	R.append(r)

for i in range(D+1,H*W+1):
	S[i]=S[i-D]+abs(X[i][0]-X[i-D][0])+abs(X[i][1]-X[i-D][1])

for i in range(Q):
	print(S[R[i]]-S[L[i]])

# Buggy version:
h, w, d = map(int, input().split(' '))
q = int(input())
lr = [map(int, input().split(' ')) for _ in range(q)]

comp = {}
for i in range(h):
    tmp = list(map(int, input().split(' ')))
    for j in range(w):
        comp[tmp[j]] = [i, j]

dp = [0] * (h * w + 1)
for i in range(d + 1, h * w + 1):
    cnt = dp[i - d]
    cnt += abs(comp[i][0] - comp[i - d][0])
    cnt += abs(comp[i][1] - comp[i - d][1])    
    dp[i] = cnt
    

for l, r in lr:
    print(dp[r] - dp[l])

# Fixed version:
h, w, d = map(int, input().split(' '))

comp = {}
for i in range(h):
    tmp = list(map(int, input().split(' ')))
    for j in range(w):
        comp[tmp[j]] = [i, j]

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

dp = [0] * (h * w + 1)
for i in range(d + 1, h * w + 1):
    cnt = dp[i - d]
    cnt += abs(comp[i][0] - comp[i - d][0])
    cnt += abs(comp[i][1] - comp[i - d][1])    
    dp[i] = cnt
    

for l, r in lr:
    print(dp[r] - dp[l])

# Buggy version:
line = input().split(" ")
a = list(map(int, line))
data = [0] * 90001
ans = 0
for i in range(0, a[0]):
    line = input().split(" ")
    temp = list(map(int, line))
    for j in range(0, a[1]):
        data[temp[j]] = [i, j]

memo = [0] * 90001

for i in range(0, a[0] * a[1]):
    if i < a[2]:
        memo[i] = 0
    else:
        memo[i] = memo[i - a[2]] + abs(data[i][0] - data[i - a[2]][0]) + abs(data[i][1] - data[i - a[2]][1])
times = int(input())
for i in range(0, times):
    line = list(map(int, input().split(" ")))
    print(memo[line[1]] - memo[line[0]])

# Fixed version:
line = input().split(" ")
a = list(map(int, line))
data = [0] * 90001
ans = 0
for i in range(0, a[0]):
    line = input().split(" ")
    temp = list(map(int, line))
    for j in range(0, a[1]):
        data[temp[j]] = [i, j]

memo = [0] * 90001

for i in range(1, a[0] * a[1]+1):
    if i < a[2]+1:
        memo[i] = 0
    else:
        memo[i] = memo[i - a[2]] + abs(data[i][0] - data[i - a[2]][0]) + abs(data[i][1] - data[i - a[2]][1])
times = int(input())
for i in range(0, times):
    line = list(map(int, input().split(" ")))
    print(memo[line[1]] - memo[line[0]])

# Buggy version:
# coding=utf-8
line = input().split(" ")
h = int(line[0])
w = int(line[1])
d = int(line[2])

table = [0 for _ in range(h*w+1)]
for hi in range(h):
    line = list(map(int, input().split(" ")))

    for wi in range(w):
        table[line[wi]] = (hi+1, wi+1)

def calc(l,r):
    ret = 0
    if l!=r:
        c1 = table[l]
        c2 = table[r]
        ret += abs(c1[0]-c2[0])+abs(c1[1]-c2[1])
    return ret

acc = [0 for _ in range(h*w+1)]
for dd in range(1,d+1):
    s = dd+d
    while s+d<=h*w:
        acc[s] = calc(s-d,s)+acc[s-d]
        s += d

q = int(input())
for _ in range(q):
    line = input().split(" ")
    l = int(line[0])
    r = int(line[1])

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


# Fixed version:
# coding=utf-8
line = input().split(" ")
h = int(line[0])
w = int(line[1])
d = int(line[2])

table = [0 for _ in range(h*w+1)]
for hi in range(h):
    line = list(map(int, input().split(" ")))

    for wi in range(w):
        table[line[wi]] = (hi+1, wi+1)

def calc(l,r):
    ret = 0
    if l!=r:
        c1 = table[l]
        c2 = table[r]
        ret += abs(c1[0]-c2[0])+abs(c1[1]-c2[1])
    return ret

acc = [0 for _ in range(h*w+1)]
for dd in range(1,d+1):
    s = dd+d
    while s<=h*w:
        acc[s] = calc(s-d,s)+acc[s-d]
        s += d

q = int(input())
for _ in range(q):
    line = input().split(" ")
    l = int(line[0])
    r = int(line[1])

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

# Buggy version:
H,W,D=map(int,input().split())
d=[[0,0] for i in range(H*W+1)]
d2=[0 for i in range(H*W+1)]
for j in range(H):
  a=[int(x) for x in input().split()]
  for k in range(W):
    d[a[k]]=[j+1,k+1]
for l in range(D+1,H*W+1-D):
  d2[l]=abs(d[l][0]-d[l-D][0])+abs(d[l][1]-d[l-D][1])
for m in range(D+1,H*W+1-D):
  d2[m]+=d2[m-D]
Q=int(input())
for i in range(Q):
  a,b=map(int,input().split())
  if a==b:
    print(0)
  else:
    ans=d2[b]-d2[a]
    print(ans)

# Fixed version:
H,W,D=map(int,input().split())
d=[[0,0] for i in range(H*W+1)]
d2=[0 for i in range(H*W+1)]
for j in range(H):
  a=[int(x) for x in input().split()]
  for k in range(W):
    d[a[k]]=[j+1,k+1]
for l in range(D+1,H*W+1):
  d2[l]=abs(d[l][0]-d[l-D][0])+abs(d[l][1]-d[l-D][1])
for m in range(D+1,H*W+1):
  d2[m]+=d2[m-D]
Q=int(input())
for i in range(Q):
  a,b=map(int,input().split())
  if a==b:
    print(0)
  else:
    ans=d2[b]-d2[a]
    print(ans)