Problem:


Score : 400 points

Problem Statement

We have a grid with H rows and W columns. The square at the i-th row and the j-th column will be called Square (i,j).

The integers from 1 through H×W are written throughout the grid, and the integer written in Square (i,j) is A_{i,j}.

You, a magical girl, can teleport a piece placed on Square (i,j) to Square (x,y) by consuming |x-i|+|y-j| magic points.

You now have to take Q practical tests of your ability as a magical girl.

The i-th test will be conducted as follows:

Initially, a piece is placed on the square where the integer L_i is written.

Let x be the integer written in the square occupied by the piece. Repeatedly move the piece to the square where the integer x+D is written, as long as x is not R_i. The test ends when x=R_i.

Here, it is guaranteed that R_i-L_i is a multiple of D.

For each test, find the sum of magic points consumed during that test.

Constraints

1 \leq H,W \leq 300

1 \leq D \leq H×W

1 \leq A_{i,j} \leq H×W

A_{i,j} \neq A_{x,y} ((i,j) \neq (x,y))

1 \leq Q \leq 10^5

1 \leq L_i \leq R_i \leq H×W

(R_i-L_i) is a multiple of D.

Input

Input is given from Standard Input in the following format:

H W D
A_{1,1} A_{1,2} ... A_{1,W}
:
A_{H,1} A_{H,2} ... A_{H,W}
Q
L_1 R_1
:
L_Q R_Q

Output

For each test, print the sum of magic points consumed during that test.

Output should be in the order the tests are conducted.

Sample Input 1

3 3 2
1 4 3
2 5 7
8 9 6
1
4 8

Sample Output 1

5

4 is written in Square (1,2).

6 is written in Square (3,3).

8 is written in Square (3,1).

Thus, the sum of magic points consumed during the first test is (|3-1|+|3-2|)+(|3-3|+|1-3|)=5.

Sample Input 2

4 2 3
3 7
1 4
5 2
6 8
2
2 2
2 2

Sample Output 2

0
0

Note that there may be a test where the piece is not moved at all, and there may be multiple identical tests.

Sample Input 3

5 5 4
13 25 7 15 17
16 22 20 2 9
14 11 12 1 19
10 6 23 8 18
3 21 5 24 4
3
13 13
2 10
13 13

Sample Output 3

0
5
0



Sample input:
3 3 2
1 4 3
2 5 7
8 9 6
1
4 8


Sample output:
5

Submission status: Runtime Error

Solution code:
import sys
from collections import defaultdict


def input():
    return sys.stdin.readline().strip()


sys.setrecursionlimit(20000000)


def main():
    H, W, D = map(int, input().split())
    A = [list(map(int, input().split())) for _ in range(H)]
    M = defaultdict(list)
    for h in range(H):
        for w in range(W):
            M[A[h][w]] = [h, w]
    P = defaultdict(list)
    for d in range(1, D + 1):
        a = d
        while a <= H * W - D:
            p = abs(M[a][0] - M[a + D][0]) + abs(M[a][1] - M[a + D][1])
            if P[d]:
                P[d].append(P[d][-1] + p)
            else:
                P[d] = [0, p]
            a += D
    Q = int(input())
    for i in range(Q):
        L, R = map(int, input().split())
        d = L % D
        l = L // D
        r = R // D
        if d == 0:
            if len(P[d]) > 0:
                d = D
                print(P[d][r - 1] - P[d][l - 1])
            else:
                print(0)
        else:
            print(P[d][r] - P[d][l])


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
from collections import defaultdict


def input():
    return sys.stdin.readline().strip()


sys.setrecursionlimit(20000000)


def main():
    H, W, D = map(int, input().split())
    A = [list(map(int, input().split())) for _ in range(H)]
    M = defaultdict(list)
    for h in range(H):
        for w in range(W):
            M[A[h][w]] = [h, w]
    P = defaultdict(list)
    for d in range(1, D + 1):
        a = d
        while a <= H * W - D:
            p = abs(M[a][0] - M[a + D][0]) + abs(M[a][1] - M[a + D][1])
            if P[d]:
                P[d].append(P[d][-1] + p)
            else:
                P[d] = [0, p]
            a += D
    Q = int(input())
    for i in range(Q):
        L, R = map(int, input().split())
        d = L % D
        l = L // D
        r = R // D
        if d == 0:
            d = D
            print(P[d][r - 1] - P[d][l - 1])
        else:
            print(P[d][r] - P[d][l])


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
from collections import defaultdict


def input():
    return sys.stdin.readline().strip()


sys.setrecursionlimit(20000000)


def main():
    H, W, D = map(int, input().split())
    A = [list(map(int, input().split())) for _ in range(H)]
    M = defaultdict(list)
    for h in range(H):
        for w in range(W):
            M[A[h][w]] = [h, w]
    P = defaultdict(list)
    for d in range(1, D + 1):
        a = d
        while a <= H * W - D:
            p = abs(M[a][0] - M[a + D][0]) + abs(M[a][1] - M[a + D][1])
            if P[d]:
                P[d].append(P[d][-1] + p)
            else:
                P[d] = [0, p]
            a += D
    Q = int(input())
    for i in range(Q):
        L, R = map(int, input().split())
        d = L % D
        l = L // D
        r = R // D
        if d == 0:
            d = D
            print(P[d][-1] - P[d][l - 1])
        else:
            print(P[d][r] - P[d][l])


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
H,W,D=map(int,input().split())
A=[]
for i in range(H):
    a=list(map(int,input().split()))
    A.append(a)
Q=int(input())
L=[]
R=[]

lst=[[]for _ in range(H*W+1)]
for i in range(H):
    for j in range(W):
        lst[A[i][j]].append(i)
        lst[A[i][j]].append(j)
#print(lst)
#print(lst[1][1])
d=[]
for i in range(D):
    if (i+D)>(H*W):
        break
    if i==0:
        tmp=D
        cnt=[0]*(H*W+1)
        sx=lst[tmp][0]
        sy=lst[tmp][1]
        cnt[tmp]=0
    else:
        tmp=i
        cnt=[0]*(H*W+1)
        #print(tmp)
        sx=lst[tmp][0]
        sy=lst[tmp][1]
        cnt[i]=0
    while(1):
        sx=lst[tmp][0]
        sy=lst[tmp][1]
        tmp=tmp+D
        #print(tmp)
        #この段階？
        #1週目で超える場合
        if tmp>(H*W):
            break
        x=lst[tmp][0]
        y=lst[tmp][1]
        val=abs(sx-x)+abs(sy-y)
        cnt[tmp]=cnt[tmp-D]+val
        if (tmp+D)>(H*W):
            break
    d.append(cnt)
ans=[]
#print(cnt)
#print(d)
for i in range(Q):
    l,r=map(int,input().split())
    ll=l%D
    count=d[ll]
    #print(count)
    vall=count[l]
    valr=count[r]
    val=valr-vall
    #print(val)
    ans.append(val)

for i in range(Q):
    print(ans[i])

Submission status: Runtime Error

Solution code:
H,W,D=map(int,input().split())
A=[]
for i in range(H):
    a=list(map(int,input().split()))
    A.append(a)
Q=int(input())
L=[]
R=[]

lst=[[]for _ in range(H*W+1)]
for i in range(H):
    for j in range(W):
        lst[A[i][j]].append(i)
        lst[A[i][j]].append(j)
#print(lst)
#print(lst[1][1])
d=[]
for i in range(D):

    if i==0:
        tmp=D
        cnt=[0]*(H*W+1)
        sx=lst[tmp][0]
        sy=lst[tmp][1]
        cnt[tmp]=0
    else:
        tmp=i
        cnt=[0]*(H*W+1)
        #print(tmp)
        sx=lst[tmp][0]
        sy=lst[tmp][1]
        cnt[i]=0
    while(1):
        sx=lst[tmp][0]
        sy=lst[tmp][1]
        tmp=tmp+D
        #print(tmp)
        x=lst[tmp][0]
        y=lst[tmp][1]
        val=abs(sx-x)+abs(sy-y)
        cnt[tmp]=cnt[tmp-D]+val
        if (tmp+D)>(H*W):
            break
    d.append(cnt)
ans=[]
#print(cnt)
#print(d)
for i in range(Q):
    l,r=map(int,input().split())
    ll=l%D
    count=d[ll]
    #print(count)
    vall=count[l]
    valr=count[r]
    val=valr-vall
    #print(val)
    ans.append(val)

for i in range(Q):
    print(ans[i])

Submission status: Runtime Error

Solution code:
h,w,d=map(int,input().split())
A=[]
for _ in range(h):
    A.append([int(i) for i in input().split()])
q=int(input())
lr=[]
for _ in range(q):
    l,r = map(int,input().split())
    lr.append((l,r))
D=dict()
for i in range(h):
    for j in range(w):
        D[A[i][j]]=(i,j)

def dist(a,b):
    return abs(a[0]-b[0])+abs(a[1]-b[1])
#ans=[[-1 for _ in range(h*w//d+1)] for _ in range(d)]
res=dict()
for i in range(d):
    j=i+1
    cnt=0
    #ans[i][0] = 0
    while j<=h*w-d:
        #ans[i][cnt+1] = ans[i][cnt] + dist(D[j],D[j+d])
        res[j] = ans[i][cnt]
        j+=d
        cnt+=1
for l,r in lr:
    print(res[r]-res[l])

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.buffer.readline

def main():
    H,W,D = map(int,input().split())
    a = [list(map(int,input().split())) for _ in range(H)]
    pos = [[-1,-1] for _ in range(H*W)]
    for i in range(H):
        for j in range(W):
            pos[a[i][j]-1][0] = i
            pos[a[i][j]-1][1] = j
    
    def manhattan_dist(x1,y1,x2,y2):
        return abs(x2-x1)+abs(y2-y1)

    ans_list = [[0] for _ in range(D)]
    for i in range(D):
        do = -(-(H*W-i)//D)
        for j in range(do-1):
            x1,y1 = pos[D*j+i]
            x2,y2 = pos[D*(j+1)+i]
            md = manhattan_dist(x1,y1,x2,y2)
            ans_list[i].append(ans_list[i][-1]+md)
    
    Q = int(input())
    for _ in range(Q):
        a,b = map(int,input().split())
        mod = (a-1)%D
        print(ans_list[mod][(b-mod)//D]-ans_list[mod][(a-mod)//D])

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.buffer.readline

def main():
    H,W,D = map(int,input().split())
    a = [list(map(int,input().split())) for _ in range(H)]
    pos = [[-1,-1] for _ in range(H*W)]
    for i in range(H):
        for j in range(W):
            pos[a[i][j]-1][0] = i
            pos[a[i][j]-1][1] = j
    
    def manhattan_dist(x1,y1,x2,y2):
        return abs(x2-x1)+abs(y2-y1)

    ans_list = [[0] for _ in range(D)]
    for i in range(D):
        for j in range((H*W-i-1)//D):
            x1,y1 = pos[D*j+i]
            x2,y2 = pos[D*(j+1)+i]
            md = manhattan_dist(x1,y1,x2,y2)
            ans_list[i].append(ans_list[i][-1]+md)
    
    Q = int(input())
    for _ in range(Q):
        a,b = map(int,input().split())
        mod = (a-1)%D
        print(ans_list[mod][(b-mod)//D]-ans_list[mod][(a-mod)//D])

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
dic = {}
h, w, d = map(int, input().split())
lis = [list(input().split()) for _ in range(h)]
for i in range(h):
    for j in range(w):
        dic[int(lis[i][j])] = (i, j)
#print(dic)
n = h * w
su = [0] * n
for k in range(1, n - d):
    x = dic[k + d][0] - dic[k][0]
    y = dic[k + d][1] - dic[k][1]
    su[k + d] = su[k] + abs(x) + abs(y)
#print(su)

q = int(input())
for i in range(q):
    s, g = map(int, input().split())
    print(su[g] - su[s])

Submission status: Runtime Error

Solution code:
# coding: utf-8

# https://atcoder.jp/contests/abc089/tasks/abc089_d
# 17:17-18:17 done


def main():
    H, W, D = map(int, input().split())
    A = [None] * H
    for i in range(H):
        A[i] = list(map(int, input().split()))
    Q = int(input())
    L, R = [None] * Q, [None] * Q
    for i in range(Q):
        L[i], R[i] = map(int, input().split())
        L[i] -= 1  # 1-index => 0-index
        R[i] -= 1  # 1-index => 0-index

    positions = [None] * (H*W)
    for i in range(H):
        for j in range(W):
            positions[A[i][j]-1] = (i, j)

    n_graph = D if D <= (H*W)//2 else (H*W)-D

    graphs = [[] for _ in range(n_graph)]

    for start in range(n_graph):
        cost = 0
        start_x, start_y = positions[start]
        m = 0
        while start + m*D < H*W:
            to_x, to_y = positions[start + m*D]
            cost += abs(to_x-start_x) + abs(to_y-start_y)
            graphs[start].append(cost)
            start_x, start_y = to_x, to_y
            m += 1
        
    for l, r in zip(L, R):
        graph_num = l % n_graph
        graph = graphs[graph_num]
        print(graph[r//D] - graph[l//D])


main()
# print(main())

Submission status: Runtime Error

Solution code:
# coding: utf-8

# https://atcoder.jp/contests/abc089/tasks/abc089_d
# 17:17-18:12 done


def main():
    H, W, D = map(int, input().split())
    A = [None] * H
    for i in range(H):
        A[i] = list(map(int, input().split()))
    Q = int(input())
    L, R = [None] * Q, [None] * Q
    for i in range(Q):
        L[i], R[i] = map(int, input().split())
        L[i] -= 1  # 1-index => 0-index
        R[i] -= 1  # 1-index => 0-index

    positions = [None] * (H*W)
    for i in range(H):
        for j in range(W):
            positions[A[i][j]-1] = (i, j)

    n_graph = D if D <= (H*W)//2 else (H*W)-D

    graphs = [[] for _ in range(n_graph)]

    for start in range(n_graph):
        cost = 0
        start_x, start_y = positions[start]
        m = 0
        while start + m*D < H*W:
            to_x, to_y = positions[start + m*D]
            cost += abs(to_x-start_x) + abs(to_y-start_y)
            graphs[start].append(cost)
            start_x, start_y = to_x, to_y
            m += 1
        
    for l, r in zip(L, R):
        graph_num = l % n_graph
        graph = graphs[graph_num]
        print(graph[r//n_graph] - graph[l//n_graph])


main()
# print(main())

Submission status: Runtime Error

Solution code:
# coding: utf-8

# https://atcoder.jp/contests/abc089/tasks/abc089_d
# 17:17-18:02 done


def main():
    H, W, D = map(int, input().split())
    A = [None] * H
    for i in range(H):
        A[i] = list(map(int, input().split()))
    Q = int(input())
    L, R = [None] * Q, [None] * Q
    for i in range(Q):
        L[i], R[i] = map(int, input().split())
        L[i] -= 1  # 1-index => 0-index
        R[i] -= 1  # 1-index => 0-index

    positions = [None] * (H*W)
    for i in range(H):
        for j in range(W):
            positions[A[i][j]-1] = (i, j)

    n_graph = D if D <= (H*W)//2 else (H*W)-D

    graphs = [[] for _ in range(n_graph)]

    for start in range(n_graph):
        cost = 0
        start_x, start_y = positions[start]
        for m in range(H*W // D):  # check!
            to_x, to_y = positions[start + m*D]
            cost += abs(to_x-start_x) + abs(to_y-start_y)
            graphs[start].append(cost)
            start_x, start_y = to_x, to_y
        
    for l, r in zip(L, R):
        graph_num = l % n_graph
        graph = graphs[graph_num]
        print(graph[r//n_graph] - graph[l//n_graph])


main()
# print(main())

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline

h, w, d = [int(x) for x in input().split()]
a = [[int(x) for x in input().split()] for _ in range(h)]
q = int(input())
lr = [[int(x) for x in input().split()] for _ in range(q)]

dic = {}

for i in range(h):
    for j in range(w):
        dic[a[i][j]] = (i, j)

dis = {}

for i in range(1, d + 1):
    dis[i] = 0
    while i + d < h * w:
        dis[i + d] = dis[i] + abs(dic[i + d][0] - dic[i][0]) + abs(dic[i + d][1] - dic[i][1])
        i += d

for i in range(q):
    l, r = lr[i]
    print(dis[r] - dis[l])

Submission status: Runtime Error

Solution code:
mod = 10 ** 9 + 7
mod2 = 2 ** 61 + 1
from collections import deque
import heapq
import time
from bisect import bisect_left, insort_left, bisect_right
import sys
import random

input = sys.stdin.readline
_NUMINT_ALL = list(range(10))
_START_TIME = time.time()


def main():
    ans = solve()

    if ans is True or ans is False:
        YesNo(ans)
    elif ans is not None:
        print(ans)


def solve():
    H, W, D = iip()
    time_debug_10percent()

    A = iipt(H)
    Q = iip(False)
    LR = iipt(Q)

    position = [None for i in range(H*W)]
    for i in range(H):
       for j in range(W):
           n = A[i][j]
           position[n-1] = (i, j)

    try:
        distanse = [None] * (H*W)
        for i in range(H*W):
            if i+D >= H*W:
                continue
            if distanse[i] is None:
                distanse[i] = 0
            distanse[i+D] = distanse[i] + abs(position[i][0]-position[i+D][0]) + abs(position[i][1]-position[i+D][1])
    except:
        time_debug(1.2)

    #print(distanse)
    for l, r in LR:
         l -= 1
         r -= 1
         print(distanse[r]-distanse[l])


#####################################################ライブラリ集ここから

def kiriage_warizan(a, b):
    return -(-a//b)


def iip(listed=True):  # 数字のinputをlistで受け取る
    d = input().rstrip("\n").split()
    try:
        ret = [int(i) for i in d]
    except:
        ret = [int(i) if i in _NUMINT_ALL else i for i in d]
        if len(ret) == 1 and listed is False:
            return ret[0]

    if len(ret) == 1 and not listed:
        return ret[0]
    return ret

def iipt(l, listed=True, num_only=True):  # 縦向きに並んでいるデータをリストに落とし込む(iip利用)
    ret = []
    for i in range(l):
        ret.append(iip(listed=listed))
    return ret


def saidai_kouyakusuu(A):  # 最大公約数
    l = len(A)
    while True:
        m = min(A)
        mx = max(A)
        if m == mx:
            return m

        for i in range(l):
            if A[i] % m == 0:
                A[i] = m
            else:
                A[i] %= m

def time_debug_10percent():
    a = random.randint(0, 9)
    if a == 9:
        sys.exit()

def time_debug(t):
    time.sleep(_START_TIME + t - time.time())
    sys.exit()


def make_graph_edge_flat(N):  # グラフ作成のための辺をリストで返す
    ret = []
    for i in range(N-1):
        a, b, c = iip()
        a -= 1
        b -= 1
        ret[a].append((b, c))
        ret[b].append((a, c))
    return ret


def sort_tuples(l, index):  # タプルのリストを特定のインデックスでソートする
    if isinstance(l, list):
        l.sort(key=lambda x: x[index])
        return l
    else:
        l = list(l)
        return sorted(l, key=lambda x: x[index])


def count_elements(l):  # リストの中身の個数を種類分けして辞書で返す
    d = {}
    for i in l:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return d


def safeget(l, index, default="exception"):  # listの中身を取り出す時、listからはみ出たり
    if index >= len(l):                      # マイナスインデックスになったりするのを防ぐ
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。配列の長さは", len(l), "です"]))
        else:
            return default
    elif index < 0:
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。負の値は許可されていません"]))
        else:
            return default
    else:
        return l[index]


def sortstr(s):  # 文字列をソートする
    return "".join(sorted(s))


def iip_ord(startcode="a"):  # 文字列を数字の列に変換する(数字と文字は1:1対応)
    if isinstance(startcode, str):
        startcode = ord(startcode)
    return [ord(i) - startcode for i in input()]


def YesNo(s):  # TrueFalseや1, 0をYesNoに変換する
    if s:
        print("Yes")
    else:
        print("No")


def fprint(s):  # リストを平たくしてprintする(二次元リストを見やすくしたりとか)
    for i in s:
        print(i)


def bitall(N):  # ビット全探索用のインデックスを出力
    ret = []
    for i in range(2 ** N):
        a = []
        for j in range(N):
            a.append(i % 2)
            i //= 2
        ret.append(a)
    return ret

def split_print_space(s):  # リストの中身をスペース区切りで出力する
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):  # リストの中身を改行区切りで出力する
    print("\n".join([str(i) for i in s]))


def soinsuu_bunkai(n):  # 素因数分解
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):  # nCrをmodを使って計算する
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):  #  modnにおける逆元を計算
    return power(n, mod - 2)


def power(n, p, mod_=mod):  # 繰り返し二乗法でn**p % modを計算
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


def nibutan_func(func, target, left, right, side="left"): # 関数を二分探索
    l = left
    r = right
    x = (l + r) // 2
    while r-l > 1:
        x = (l+r)//2
        if func(x) == target:
            return x
        elif func(x) > target:
            r = x
        else:
            l = x

    if side == "left" or func(x) == target:
        return l
    else:
        return r


def nibutan_list(list_, target, side="left"):  # リストを二分探索
    if not isinstance(list_, list):
        list_ = list(list_)

    l = 0
    r = len(list_)
    x = (l + r) // 2
    while r-l > 1:
        x = (l+r)//2
        if list_[x] == target:
            return x
        elif list_[x] > target:
            r = x
        else:
            l = x

    if side == "left" or list_[x] == target:
        return l
    else:
        return r


class UfTree():
    def __init__(self, maxnum):
        self.parent = list(range(maxnum))
        self._size = [1] * maxnum
        self.rank = [0] * maxnum

    def size(self, a):
        return self._size[self.root(a)]

    def root(self, a):
        rank = 0
        cur = a
        while True:
            if self.parent[cur] == cur:
                #for i in path: # 経路圧縮
                #    self.parent[i] = cur
                return cur
            else:
                self.parent[cur] = self.parent[self.parent[cur]]
                cur = self.parent[cur]
                rank += 1

    def unite(self, a, b):
        ra = self.root(a)
        rb = self.root(b)
        if ra == rb:
            return self

        self._size[ra] += self._size[rb]
        self.parent[rb] = ra
        return self

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
mod = 10 ** 9 + 7
mod2 = 2 ** 61 + 1
from collections import deque
import heapq
import time
from bisect import bisect_left, insort_left, bisect_right
import sys
import random

input = sys.stdin.readline
_NUMINT_ALL = list(range(10))
_START_TIME = time.time()


def main():
    ans = solve()

    if ans is True or ans is False:
        YesNo(ans)
    elif ans is not None:
        print(ans)


def solve():
    H, W, D = iip()
    time_debug_10percent()

    A = iipt(H)
    Q = iip(False)
    LR = iipt(Q)

    position = [None for i in range(H*W)]
    for i in range(H):
       for j in range(W):
           n = A[i][j]
           position[n-1] = (i, j)

    try:
        distanse = [None] * (H*W)
        for i in range(H*W):
            if i+D >= H*W:
                continue
            if distanse[i] is None:
                distanse[i] = 0
            distanse[i+D] = distanse[i] + abs(position[i][0]-position[i+D][0]) + abs(position[i][1]-position[i+D][1])
    except:
        time_debug(1.2)

    #print(distanse)
    for l, r in LR:
         l -= 1
         r -= 1
         print(distanse[r]-distanse[l])


#####################################################ライブラリ集ここから

def kiriage_warizan(a, b):
    return -(-a//b)


def iip(listed=True):  # 数字のinputをlistで受け取る
    d = input().rstrip("\n").split()
    try:
        ret = [int(i) for i in d]
    except:
        ret = [int(i) if i in _NUMINT_ALL else i for i in d]
        if len(ret) == 1 and listed is False:
            return ret[0]

    if len(ret) == 1 and not listed:
        return ret[0]
    return ret

def iipt(l, listed=True, num_only=True):  # 縦向きに並んでいるデータをリストに落とし込む(iip利用)
    ret = []
    for i in range(l):
        ret.append(iip(listed=listed))
    return ret


def saidai_kouyakusuu(A):  # 最大公約数
    l = len(A)
    while True:
        m = min(A)
        mx = max(A)
        if m == mx:
            return m

        for i in range(l):
            if A[i] % m == 0:
                A[i] = m
            else:
                A[i] %= m

def time_debug_10percent():
    a = random.randint(9)
    if a == 9:
        sys.exit()

def time_debug(t):
    time.sleep(_START_TIME + t - time.time())
    sys.exit()


def make_graph_edge_flat(N):  # グラフ作成のための辺をリストで返す
    ret = []
    for i in range(N-1):
        a, b, c = iip()
        a -= 1
        b -= 1
        ret[a].append((b, c))
        ret[b].append((a, c))
    return ret


def sort_tuples(l, index):  # タプルのリストを特定のインデックスでソートする
    if isinstance(l, list):
        l.sort(key=lambda x: x[index])
        return l
    else:
        l = list(l)
        return sorted(l, key=lambda x: x[index])


def count_elements(l):  # リストの中身の個数を種類分けして辞書で返す
    d = {}
    for i in l:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return d


def safeget(l, index, default="exception"):  # listの中身を取り出す時、listからはみ出たり
    if index >= len(l):                      # マイナスインデックスになったりするのを防ぐ
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。配列の長さは", len(l), "です"]))
        else:
            return default
    elif index < 0:
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。負の値は許可されていません"]))
        else:
            return default
    else:
        return l[index]


def sortstr(s):  # 文字列をソートする
    return "".join(sorted(s))


def iip_ord(startcode="a"):  # 文字列を数字の列に変換する(数字と文字は1:1対応)
    if isinstance(startcode, str):
        startcode = ord(startcode)
    return [ord(i) - startcode for i in input()]


def YesNo(s):  # TrueFalseや1, 0をYesNoに変換する
    if s:
        print("Yes")
    else:
        print("No")


def fprint(s):  # リストを平たくしてprintする(二次元リストを見やすくしたりとか)
    for i in s:
        print(i)


def bitall(N):  # ビット全探索用のインデックスを出力
    ret = []
    for i in range(2 ** N):
        a = []
        for j in range(N):
            a.append(i % 2)
            i //= 2
        ret.append(a)
    return ret

def split_print_space(s):  # リストの中身をスペース区切りで出力する
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):  # リストの中身を改行区切りで出力する
    print("\n".join([str(i) for i in s]))


def soinsuu_bunkai(n):  # 素因数分解
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):  # nCrをmodを使って計算する
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):  #  modnにおける逆元を計算
    return power(n, mod - 2)


def power(n, p, mod_=mod):  # 繰り返し二乗法でn**p % modを計算
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


def nibutan_func(func, target, left, right, side="left"): # 関数を二分探索
    l = left
    r = right
    x = (l + r) // 2
    while r-l > 1:
        x = (l+r)//2
        if func(x) == target:
            return x
        elif func(x) > target:
            r = x
        else:
            l = x

    if side == "left" or func(x) == target:
        return l
    else:
        return r


def nibutan_list(list_, target, side="left"):  # リストを二分探索
    if not isinstance(list_, list):
        list_ = list(list_)

    l = 0
    r = len(list_)
    x = (l + r) // 2
    while r-l > 1:
        x = (l+r)//2
        if list_[x] == target:
            return x
        elif list_[x] > target:
            r = x
        else:
            l = x

    if side == "left" or list_[x] == target:
        return l
    else:
        return r


class UfTree():
    def __init__(self, maxnum):
        self.parent = list(range(maxnum))
        self._size = [1] * maxnum
        self.rank = [0] * maxnum

    def size(self, a):
        return self._size[self.root(a)]

    def root(self, a):
        rank = 0
        cur = a
        while True:
            if self.parent[cur] == cur:
                #for i in path: # 経路圧縮
                #    self.parent[i] = cur
                return cur
            else:
                self.parent[cur] = self.parent[self.parent[cur]]
                cur = self.parent[cur]
                rank += 1

    def unite(self, a, b):
        ra = self.root(a)
        rb = self.root(b)
        if ra == rb:
            return self

        self._size[ra] += self._size[rb]
        self.parent[rb] = ra
        return self

if __name__ == "__main__":
    main()