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

Solution in C# (.NET Core 3.1.201) (judge verdict: Accepted)

using static System.Math;
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System;

class Program
{
    #region Reader
    static string ReadStr => Console.ReadLine();
    static string[] ReadStrs => Console.ReadLine().Split(' ');
    static int ReadInt => Convert.ToInt32(Console.ReadLine().Trim());
    static int[] ReadInts => Console.ReadLine().Trim().Split(' ').Select(s => Convert.ToInt32(s)).ToArray();
    static long ReadLong => Convert.ToInt64(Console.ReadLine().Trim());
    static long[] ReadLongs => Console.ReadLine().Trim().Split(' ').Select(s => Convert.ToInt64(s)).ToArray();
    static List<int[]> ReadPairs(int N)
    {
        List<int[]> ans = new List<int[]>();
        for (int i = 0; i < N; i++) { ans.Add(ReadInts); }
        return ans;
    }
    static List<long[]> ReadPairsLong(int N)
    {
        List<long[]> ans = new List<long[]>();
        for (int i = 0; i < N; i++) { ans.Add(ReadLongs); }
        return ans;
    }
    #endregion
    #region Method
    const int mod = 1000000007;
    public static int Mod(int a, int mod) { return a % mod >= 0 ? a % mod : a % mod + mod; }
    public static long Mod(long a, long mod = mod) { return a % mod >= 0 ? a % mod : a % mod + mod; }
    bool eq<T, U>() => typeof(T).Equals(typeof(U));
    T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T));
    T cv<T>(string s) => eq<T, int>() ? ct<T, int>(int.Parse(s))
                       : eq<T, long>() ? ct<T, long>(long.Parse(s))
                       : eq<T, double>() ? ct<T, double>(double.Parse(s))
                       : eq<T, char>() ? ct<T, char>(s[0])
                                         : ct<T, string>(s);
    void Multi<T>(out T a) => a = cv<T>(ReadStr);
    void Multi<T, U>(out (T,U) ans)
    {
        var ar = ReadStrs;
        ans =(cv<T>(ar[0]), cv<U>(ar[1]));
    }
    void Multi<T, U, V>(out (T,U,V) ans)
    {
        var ar = ReadStrs; 
        ans =(cv<T>(ar[0]), cv<U>(ar[1]),cv<V>(ar[2]));
    }
    void Multi<T,U>(out T a,out U b)
    {
        var ar = ReadStrs; 
        a = cv<T>(ar[0]);  b = cv<U>(ar[1]);
    }
    void Multi<T, U, V>(out T a,out U b,out V c)
    {
        var ar = ReadStrs;
        a = cv<T>(ar[0]);  b = cv<U>(ar[1]);  c = cv<V>(ar[2]);
    }
    #endregion


    /// <summary>
    /// とりうる最大値に1を足すこと
    /// </summary>
    /// <param name="minLimit"></param>
    /// <param name="maxLimitPlus1"></param>
    /// <param name="judge"></param>
    /// <returns></returns>
    static long[] BinarySearch(long minLimit, long maxLimitPlus1, Func<long, bool> judge)
    {
        long max = maxLimitPlus1;
        long min = minLimit;
        long mid = (min + max) / 2;

        while (max - min > 1)
        {
            if (judge(mid))
            {
                min = mid;
                mid = (mid + max) / 2;
            }
            else
            {
                max = mid;
                mid = (mid + min) / 2;
            }
        }

        if (max == maxLimitPlus1) return new long[2] { mid, mid + 1 };
        else if (min == minLimit - 1) return new long[2] { -1, 0 };
        else
        {
            return judge(mid) != judge(mid + 1) ? new long[2] { mid, mid + 1 }
            : new long[2] { mid - 1, mid };
        }
    }

    static int[] BinarySearch(IEnumerable<int> numbers, Func<int, bool> judge)
    {
        int max = numbers.Count();
        int min = -1;
        int mid = (min + max) / 2;

        while (max - min > 1)
        {
            if (judge(numbers.ElementAt(mid)))
            {
                min = mid;
                mid = (mid + max) / 2;
            }
            else
            {
                max = mid;
                mid = (mid + min) / 2;
            }
        }

        if (max == numbers.Count()) return new int[2] { mid, mid + 1 };
        else if (min == -1) return new int[2] { -1, 0 };
        else
        {
            return judge(numbers.ElementAt(mid)) != judge(numbers.ElementAt(mid + 1)) ? new int[2] { mid, mid + 1 }
            : new int[2] { mid - 1, mid };
        }
    }

    #region SegmentTree_Lazy

    /// <summary>
    /// 行う演算は結合法則を満たす必要あり
    /// </summary>
    public class SegmentTree<T> where T : IComparable
    {
        /// <summary>
        /// 完全二分木
        /// </summary>
        protected T[] Data { get; }

        /// <summary>
        /// 完全二分木に含まれる葉の数
        /// </summary>
        protected int LeavesCount { get; }

        /// <summary>
        /// 数列(問題などで与えられる)の要素数
        /// </summary>
        public int Count { get; }

        /// <summary>
        /// 葉のうち使われなかったもの、そしてQueryで引数として取得した範囲がDataのインデックスの外である場合に使う
        /// </summary>
        public T Default { get; }

        protected T[] lazy;


        public SegmentTree(T[] data, T def)
        {

            //初期値の設定
            Count = data.Length;
            Default = def;
            LeavesCount = (int)Pow(2, Ceiling(Log(data.Length, 2)));
            Data = new T[LeavesCount * 2 - 1];
            lazy = new T[LeavesCount * 2 - 1];
            //

            //完全二分木の全要素を初期化
            for (int i = 0; i < Data.Length; i++)
            {
                Data[i] = def;
                lazy[i] = def;
            }

            //dataを用いて必要な要素をすべて埋める
            for (int i = 0; i < data.Length; i++)
            {
                this[i] = data[i];
            }

           // WriteLine("初期化完了");
        }

        public T this[int index]
        {
            get
            {
                return Query(index, index + 1);
            }
            set
            {
                Update(index, index + 1, value);
            }
        }

        public void Update(int a, int b, T newValue)
        {
            Update_sub(a, b, 0, LeavesCount, 0, newValue);
        }

        protected virtual void Update_sub(int a, int b, int l, int r, int current, T newValue)
        {
            Eval(current);
            if (a <= l && r <= b)
            {
                lazy[current] = newValue;
                Eval(current);
            }
            else if (a < r && l < b)
            {
                var children = GetChildIndexes(current);

                Update_sub(a, b, l, (l + r) / 2, children.l, newValue);
                Update_sub(a, b, (l + r) / 2, r, children.r, newValue);
                Data[current] = Select(Data[children.l], Data[children.r]);
            }
        }


        /// <summary>
        /// 唯一の親のインデックスを返す
        /// </summary>
        /// <param name="childIndex"></param>
        /// <returns></returns>
        private int GetParentIndex(int childIndex)
        {
            return (childIndex - 1) / 2;
        }

        /// <summary>
        /// 二つの子のインデックスを返す
        /// </summary>
        /// <param name="parentIndex"></param>
        /// <returns>小さいほうはl、大きいほうはr</returns>
        protected (int l, int r) GetChildIndexes(int parentIndex)
        {
            return (2 * parentIndex + 1, 2 * parentIndex + 2);
        }

        /// <summary>
        /// 親の値を二つの子から決定する
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        private T DecideNewElementFromTwoChildren(int index)
        {
            var children = GetChildIndexes(index);

            return Select(Data[children.l], Data[children.r]);
        }



        /// <summary>
        /// [a,b)の範囲で回答を探す
        /// </summary>
        /// <param name="a"></param>
        /// <param name="halfOpen_b"></param>
        /// <returns></returns>
        public T Query(int a, int halfOpen_b)
        {
            return _Query(a, halfOpen_b, 0, LeavesCount, 0);
        }

        private T _Query(int a, int b, int l, int r, int current)
        {
            Eval(current);

            //Φ
            if (r <= a || b <= l)
            {
                return Default;
            }
            //部分集合
            else if (a <= l && r <= b)
            {
                return Data[current];
            }
            //一部
            else
            {

                //(1) 範囲[l,r)を分割し、子lの回答と子rの回答を取得
                //(2) 二つの回答を比べて、適切(Selectメソッド)な方を返す


                //(1)
                var children = GetChildIndexes(current);
                T t1 = _Query(a, b, l, (l + r) / 2, children.l);
                T t2 = _Query(a, b, (l + r) / 2, r, children.r);

                //(2)
                return Select(t1, t2);
            }

        }

        /// <summary>
        /// 配列のk番と、その葉をlazyの値に更新
        /// (もしlazyがDefaultなら何もしない)
        /// </summary>
        /// <param name="k"></param>
        public virtual void Eval(int k)
        {
            //kがDefaultの時は、伝搬も自身の更新もしない
            if (lazy[k].Equals(Default))
            {
                return;
            }


            //kが葉でないなら伝搬
            if (k < LeavesCount - 1)
            {
                var children = GetChildIndexes(k);

                lazy[children.l] = lazy[k];
                lazy[children.r] = lazy[k];
            }

            //自信を更新
            Data[k] = lazy[k];


            lazy[k] = Default;
        }





        /// <summary>
        /// カスタマイズするところ。二つの子の値から、親の値を決定する方法を定める。
        /// </summary>
        /// <param name="t1">子の値1</param>
        /// <param name="t2">子の値2</param>
        /// <returns></returns>
        protected T Select(T t1, T t2)
        {
            return t1.CompareTo(t2) < 0 ? t1 : t2;
        }

    }

    /// <summary>
    /// 区間足し算
    /// </summary>
    public class SegmentTreeLong : SegmentTree<long>
    {
        public SegmentTreeLong(long[] data, long def) : base(data, def)
        {
        }

        protected override void Update_sub(int a, int b, int l, int r, int current, long newValue)
        {
            Eval(current);
            if (a <= l && r <= b)
            {
                if (lazy[current] == Default)
                {
                    lazy[current] = newValue;
                }
                else
                {
                    lazy[current] += newValue;
                }
                Eval(current);
            }
            else if (a < r && l < b)
            {
                var children = GetChildIndexes(current);

                Update_sub(a, b, l, (l + r) / 2, children.l, newValue);
                Update_sub(a, b, (l + r) / 2, r, children.r, newValue);
                Data[current] = Select(Data[children.l], Data[children.r]);
            }
        }

        /// <summary>
        /// 配列のk番と、その葉をlazyの値に更新
        /// (もしlazyがDefaultなら何もしない)
        /// </summary>
        /// <param name="k"></param>
        public override void Eval(int k)
        {
            //kがDefaultの時は、伝搬も自身の更新もしない
            if (lazy[k] == Default)
            {
                return;
            }


            //kが葉でないなら伝搬
            if (k < LeavesCount - 1)
            {
                var children = GetChildIndexes(k);

                if (lazy[children.l] == Default)
                {
                    lazy[children.l] = lazy[k];
                }
                else
                {
                    lazy[children.l] += lazy[k];
                }

                if (lazy[children.r] == Default)
                {
                    lazy[children.r] = lazy[k];
                }
                else
                {
                    lazy[children.r] += lazy[k];
                }

            }

            //自信を更新
            if (Data[k] == Default)
            {
                Data[k] = lazy[k];
            }
            else
            {
                Data[k] += lazy[k];
            }



            lazy[k] = Default;
        }
    }

    #endregion


    static void Main()
    {
        int[] HWD = ReadInts;
        int H = HWD[0];
        int W = HWD[1];
        int D = HWD[2];

        Dictionary<int, (int h, int w)> map = new Dictionary<int, (int h, int w)>();

        for (int h = 0; h < H; h++)
        {
            var v = ReadInts;

            for (int w = 0; w < W; w++)
            {
                map.Add(v[w], (h, w));
            }
        }

        Dictionary<int, List<int>> costs = new Dictionary<int, List<int>>();

        for (int i = 1; i <= D; i++)
        {
            List<int> cost = new List<int>();
            cost.Add(0);
            (int h,int w) curPos = map[i];
            int curNum = i;

            while (curNum+D<=H*W)
            {
                var nextPos = map[curNum + D];
                cost.Add(cost[cost.Count-1]+ Abs(curPos.h - nextPos.h) + Abs(curPos.w - nextPos.w));
                curPos = nextPos;
                curNum = curNum + D;
            }
            costs.Add(i%D, cost);
        }


        int qNum = ReadInt;

        List<int> ans = new List<int>();
        for (int i = 0; i < qNum; i++)
        {
            var v = ReadInts;
            var cost = costs[v[0] % D];

            int index_s = v[0]%D == 0?(v[0]-1) / D: v[0] / D;
            int index_g = v[1] % D == 0 ?( v[1]-1) / D : v[1] / D;

            ans.Add(cost[index_g] - cost[index_s]);
        }
        WriteLine(string.Join("\n", ans));
    }



}