let h, w, d, ps, ts = Array.(Scanf.scanf "%d %d %d" @@ fun h w d -> h, w, d, make (h * w) (0, 0), make (h * w) 0)
let lrs = Scanf.(for i = 0 to h - 1 do for j = 0 to w - 1 do ps.(scanf " %d" pred) <- i, j done done; scanf " %d" @@ fun q -> Array.init q @@ fun _ -> scanf " %d %d" @@ fun a b -> a - 1, b - 1)
let f a b = let (i, j), (k, l) = ps.(a), ps.(b) in abs (i - k) + abs (j - l)
let _ = for i = d to h * w - 1 do ts.(i) <- ts.(i - d) + f (i - d) i done; Array.iter (fun (l, r) -> Printf.printf "%d\n" @@ ts.(r) - ts.(l)) lrs