let () =
  let h, w, d = Scanf.scanf "%d %d %d\n" (fun h w d -> h, w, d) in
  let xs = Array.make (h * w) 0 in
  let ys = Array.make (h * w) 0 in
  for i = 0 to h - 1 do
    for j = 0 to w - 1 do
      Scanf.scanf "%d " (fun a ->
      xs.(a - 1) <- j;
      ys.(a - 1) <- i)
    done
  done;
  let dp = Array.make (h * w) 0 in
  for i = 0 to h * w - d - 1 do
    dp.(i + d) <- dp.(i) + abs (xs.(i + d) - xs.(i)) + abs (ys.(i + d) - ys.(i))
  done;
  let q = Scanf.scanf "%d\n" (fun q -> q) in
  for i = 0 to q - 1 do
    Scanf.scanf "%d %d\n" (fun l r ->
      Printf.printf "%d\n" (dp.(r - 1) - dp.(l - 1)))
  done