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