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()
let readsInt() = read().Split() |> Array.map int

[<EntryPoint>]
let main _ = 
    let l1 = readsInt() 
    let H = l1.[0] 
    let W = l1.[1] 
    let D = l1.[2] 
    
    let xIdx = Array.zeroCreate (H*W)
    let yIdx = Array.zeroCreate (H*W)
    for i in 0..H-1 do
        let mutable j = 0
        readsInt() |> Array.iter (fun a ->
            xIdx.[a-1] <- i
            yIdx.[a-1] <- j
            j <- j + 1)

    let dp = Array.zeroCreate (H*W)
    for i in D..(H*W-1) do
        dp.[i] <- dp.[i-D] 
                + abs (xIdx.[i-D]-xIdx.[i]) 
                + abs (yIdx.[i-D]-yIdx.[i])

    let Q = read() |> int
    for i in 0..Q-1 do
        let t = readsInt()
        printfn "%i" <| dp.[t.[1]-1]-dp.[t.[0]-1]
        
    0

