type heap = Node of heap * heap * (int ref) | Leaf of int * (int ref)

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, ref sz)
  else if n = 1 then  Leaf (id, ref sz)
  else                Leaf (id, ref 0);;

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

let rec use heap prev_fn sz =
  match heap with
    Node (l, r, curr) when size l >= sz -> 
      use l (fun x -> curr := max x (size r); prev_fn !curr) sz

  | Node (l, r, curr) when size r >= sz ->
      use r (fun x -> curr := max x (size l); prev_fn !curr) sz

  | Leaf (id, curr) when !curr >= sz -> 
      curr := !curr - sz; prev_fn !curr; id

  | _ -> -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 heap = build 1 h w;;

for i = 1 to n do
  let id = Scanf.bscanf inp " %d" (use heap (fun _ -> ())) in
  Printf.fprintf out "%d\n" id
done;;

close_out out;;
