
open Scanf
open Printf

let flip f x y = f y x

let rec range a b = if a >= b then [] else a :: range (a+1) b

let read_int () = scanf " %d" (fun x -> x)
let rec read_ints n = if n = 0 then [] else let i = read_int () in i :: read_ints (n-1)

let rec for_iter a b f = if a >= b then [] else let x = f a in x :: for_iter (a+1) b f
let rec for_iter_ a b f = if a >= b then () else (f a; for_iter_ (a+1) b f)

let list_of_string str = range 0 (String.length str) |> List.map (fun i -> str.[i])
let array_of_string str = Array.init (String.length str) (fun i -> str.[i])

let () =
  let h, w, d = scanf "%d %d %d" (fun a b c -> a, b, c) in
  let arr = Array.init h (fun _ -> Array.init w (fun _ -> scanf " %d" (fun x -> x))) in
  let qs = scanf " %d" (fun q -> Array.init q (fun _ -> scanf " %d %d" (fun x y -> x, y))) in
  let ps = Array.make (h*w+1) (-1, -1) in
  let cs = Array.make (h*w+1) (h*w) in

  for_iter_ 0 h (fun x -> for_iter_ 0 w (fun y -> ps.(arr.(x).(y)) <- (x, y)));

  for_iter_ 0 d (fun i -> cs.(i) <- 0);
  for_iter_ d (h*w+1) (fun i ->
    let (x, y) = ps.(i) in let (x', y') = ps.(i-d) in
    cs.(i) <- cs.(i-d) + abs (x-x') + abs (y-y'));

  qs
  |> Array.map (fun (i, j) -> cs.(j) - cs.(i))
  |> Array.iter (printf "%d\n")

