from collections import defaultdict

def main():

    # init

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

    dic = defaultdict(list)

    for i in range(h):

        nums = [int(x) for x in input().split()]

        for j,num in enumerate(nums):

            dic[int(num)] = [i,j]

    # memo

    ls = [0 for i in range(w*h+1)]

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

        before,after = dic[i-d],dic[i]

        diff = abs(after[0]-before[0]) + abs(after[1]-before[1])

        ls[i] = ls[i-d]+ diff

    # ans

    q = int(eval(input()))



    for i in range(q):

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

        print((ls[r]-ls[l]))

if __name__ == "__main__":

    main()
from collections import defaultdict

import sys

input = sys.stdin.readline



def main():

    # init

    input = sys.stdin.readline

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

    dic = defaultdict(list)

    for i in range(h):

        nums = [int(x) for x in input().split()]

        for j,num in enumerate(nums):

            dic[int(num)] = [i,j]

    # memo

    ls = [0 for i in range(w*h+1)]

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

        before,after = dic[i-d],dic[i]

        diff = abs(after[0]-before[0]) + abs(after[1]-before[1])

        ls[i] = ls[i-d]+ diff

    # ans

    q = int(eval(input()))

    for i in range(q):

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

        print((ls[r]-ls[l]))

if __name__ == "__main__":

    main()
from collections import defaultdict


def main():
    # init
    h, w, d = list(map(int, input().split()))
    dic = defaultdict(list)
    for i in range(h):
        nums = [int(x) for x in input().split()]
        for j, num in enumerate(nums):
            dic[int(num)] = [i, j]
    # memo
    ls = [0 for i in range(w * h + 1)]
    for i in range(d + 1, w * h + 1):
        before, after = dic[i - d], dic[i]
        diff = abs(after[0] - before[0]) + abs(after[1] - before[1])
        ls[i] = ls[i - d] + diff
    # ans
    q = int(eval(input()))
    for i in range(q):
        l, r = list(map(int, input().split()))
        print((ls[r] - ls[l]))


if __name__ == "__main__":
    main()

from collections import defaultdict
import sys

input = sys.stdin.readline


def main():
    # init
    input = sys.stdin.readline
    h, w, d = list(map(int, input().split()))
    dic = defaultdict(list)
    for i in range(h):
        nums = [int(x) for x in input().split()]
        for j, num in enumerate(nums):
            dic[int(num)] = [i, j]
    # memo
    ls = [0 for i in range(w * h + 1)]
    for i in range(d + 1, w * h + 1):
        before, after = dic[i - d], dic[i]
        diff = abs(after[0] - before[0]) + abs(after[1] - before[1])
        ls[i] = ls[i - d] + diff
    # ans
    q = int(eval(input()))
    for i in range(q):
        l, r = list(map(int, input().split()))
        print((ls[r] - ls[l]))


if __name__ == "__main__":
    main()

+import sys + +input = sys.stdin.readline +    input = sys.stdin.readline