let rec seq a b = if a > b then [] else a :: seq (a+1) b
let (>>=) x f = List.map f x |> List.concat

let len = 20
let costs = [|0;2;5;5;4;5;6;3;7;6|]

let cmp xs ys =
  let lx = List.fold_left (fun s (x, i) -> s+i) 0 xs in
  let ly = List.fold_left (fun s (y, i) -> s+i) 0 ys in
  if lx <> ly then lx - ly
  else
  let rec f xs ys =
    match xs, ys with
    | [], [] -> 0
    | _::_, [] -> -1
    | [], _::_ -> 1
    | ((x,i)::xs), ((y,j)::ys) ->
        if x <> y then x - y
        else if i <> j then i - j
        else f xs ys
  in f xs ys

let () =
  Scanf.scanf "%d %d" @@ fun n m ->
  let a = Array.init m (fun _ ->
    Scanf.scanf " %d" (fun x -> (costs.(x), -x, x)))
  |> Array.to_list
  |> List.sort compare
  in
  let ca, _, va = List.hd a in
  let la = max 0 (n - len) / ca in
  let ma = la * ca in

  let rec f th = function
    | [] -> if th = 0 then [[]] else []
    | (c, _, x) :: xs ->
        seq 0 (th / c) >>= fun i ->
          List.map (fun y -> (x, i) :: y) (f (th - i * c) xs)
  in

  let be =
    f (n - ma) a |> List.fold_left (fun ans xs ->
      let xs = List.sort (fun x y -> compare y x) xs in
      if cmp ans xs >= 0 then ans else xs) []
  in
  ((va, la) :: be) |> List.sort (fun x y -> compare y x)
  |> List.iter (fun (x, i) -> for n = 1 to i do Printf.printf "%d" x done);
  print_newline ()
