Scanf.scanf "%d %d %d" (fun h w d ->
    let pos = Array.make (h * w + 1) (0, 0) in
    for y = 1 to h do
        for x = 1 to w do
            Scanf.scanf " %d" (fun a -> pos.(a) <- (y, x))
        done
    done;
    Scanf.scanf " %d" (fun q ->
        for i = 1 to q do
            Scanf.scanf " %d %d" (fun l r ->
                let rec loop cur (y0, x0) acc =
                    if cur = r then Printf.printf "%d\n" acc else
                        let next = cur + d in
                        let (y1, x1) = pos.(next) in
                        loop next (y1, x1) (acc + abs (y1 - y0) + abs (x1 - x0))
                in
                loop l pos.(l) 0
            )
        done
    )
)