type heap = Node of heap * heap * int | Leaf of int * int

let rec build id n sz =
  if n > 1 then       Node (build id (n-n/2) sz, build (id+n-n/2) (n/2) sz, sz)
  else if n = 1 then  Leaf (id,sz)
  else                Leaf (id,0);;

let size heap =
  match heap with
    Node (l, r, size) -> size
  | Leaf (_, size) -> size;;

let rec use heap sz =
  match heap with
    Node (l, r, curr) when size l >= sz ->
      let (l', id) = (use l sz) in 
      (Node (l', r, max (size l') (size r)), id)

  | Node (l, r, curr) when size r >= sz ->
      let (r', id) = (use r sz) in
      (Node (l, r', max (size l) (size r')), id)

  | Leaf (id, curr) when curr >= sz -> (Leaf (id, curr - sz), id)

  | _ -> (heap, -1);;

let (inp, out) = (Scanf.Scanning.from_file "billboard.in", open_out "billboard.out");;
let (h,w,n) = Scanf.bscanf inp "%d %d %d" (fun a b c -> (a,b,c));;

let rec place heap n =
  if n > 0 then 
    let (heap, id) = Scanf.bscanf inp " %d" (use heap) in
    Printf.fprintf out "%d\n" id;
    place heap (n-1)

in place (build 1 h w) n;;

close_out out;;
