open System
open System.Collections
open System.Collections.Generic
open System.IO
open System.Text
open System.Text.RegularExpressions
open Microsoft.FSharp.Reflection

let read() = Console.ReadLine()


type Point2D =
    struct
        val A:int
        val B:int
        new (a:int,b:int)={A=a;B=b}
    end

let memoize(f:'a->'b) =
    let memo = new Dictionary<'a,'b>()
    let mFunc (inp:'a) =
        match memo.ContainsKey(inp) with
        | true  -> memo.[inp]
        | false -> 
            let ans = f inp
            memo.[inp]<-ans
            ans
    mFunc

[<EntryPoint>]
let main _ = 
    let l1 = read().Split() |> Array.map int
    let H = l1.[0] 
    let W = l1.[1] 
    let D = l1.[2] 
    let A :int[][] = Array.zeroCreate H
    for i in 0..H-1 do
        A.[i] <- read().Split() |> Array.map int
    let Q = read() |> int
    let L :int[] = Array.zeroCreate Q
    let R :int[] = Array.zeroCreate Q
    for i in 0..Q-1 do
        let t = read().Split() |> Array.map int
        L.[i] <- t.[0]
        R.[i] <- t.[1]

    let dict = new Dictionary<int,Point2D>()
    for i in 0..H-1 do
        for j in 0..W-1 do
            dict.[A.[i].[j]]<- new Point2D(i,j)

    let calCost(f:Point2D,t:Point2D) = 
        abs (f.A-t.A) + abs (f.B-t.B)
    let rec mCalCosts =
        let calCosts(f:int,t:int) =
            let diff = t - f
            match diff with
            | 0 -> 0
            | n -> calCost(dict.[f],dict.[f+D]) + mCalCosts(f+D,t)
        memoize calCosts

    for i in 0..Q-1 do
        printfn "%d" <| mCalCosts(L.[i],R.[i])

    0

