let h, w, d = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let ps = Array.make (h * w) (0, 0)
let q = for i = 0 to h - 1 do for j = 0 to w - 1 do ps.(Scanf.scanf " %d" pred) <- i, j done done; Scanf.scanf " %d" (+) 0
let lrs = Array.init q @@ fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a - 1, b - 1
let tss = Array.make d [||]
let f a b = let (i, j), (k, l) = ps.(a), ps.(b) in abs (i - k) + abs (j - l)
let _ = for i = 0 to d - 1 do let s, m = (h * w - 1 - i) / d + 1, ref i in tss.(i) <- Array.make s 0; for j = 1 to s - 1 do tss.(i).(j) <- tss.(i).(j - 1) + f !m (!m + d); m := !m + d done done; Array.iter (fun (l, r) -> let m = l mod d in Printf.printf "%d\n" @@ tss.(m).((r - m) / d) - tss.(m).((l - m) / d)) lrs