type tree = Leaf of int * int | Node of tree * int * tree let solve h w n pieces = let rec init_tree a b = if a=b then Leaf(a,w) else let m = a + (b-a)/2 in Node(init_tree a m, w, init_tree (m+1) b) in let size = function Leaf(_,w) -> w | Node(_,w,_) -> w in let rec lookup piece t = match t with Leaf(index,s) -> if piece > s then -1 else index | Node(left,s,right) -> if piece > s then -1 else if piece <= (size left) then lookup piece left else lookup piece right in let rec insert piece t = (* we've done the lookup so we know there's enough space *) match t with Leaf(index,s) -> Leaf(index,s-piece) | Node(left,_,right) -> let (l,r) = if piece <= (size left) then (insert piece left, right) else (left, insert piece right) in Node(l, max (size l) (size r), r) in let root = init_tree 1 h in let rec loop plist accum t = match plist with [] -> accum | piece::tail -> let index = lookup piece t in loop tail (index::accum) (if index >= 0 then insert piece t else t) in loop pieces [] root let main () = let read_int () = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x) in let h = read_int() in let w = read_int() in let n = read_int() in let rec loop count accum = if count=n then accum else loop (count+1) ((read_int())::accum) in let data = List.rev (loop 0 []) in let answer = List.rev (solve h w n data) in let rec print_loop = function [] -> () | h::tail -> Printf.printf "%d\n" h; print_loop tail in print_loop answer ;; main()