type trays = Tray of int list * int list * int list

type move_command = AB | BA | BC | CB

let finished = function
  | Tray (_, [], []) | Tray ([], [], _) -> true
  | _ -> false

let move (Tray (as_, bs, cs)) command =
  let move xs ys = match xs, ys with
    | x :: xs, [] -> (xs, [x])
    | x :: xs, y :: ys when x > y -> (xs, x :: y :: ys)
    | _ -> invalid_arg "move" in
  try
    Some
      begin
        match command with
        | AB -> let as_, bs = move as_ bs in Tray (as_, bs, cs)
        | BA -> let bs, as_ = move bs as_ in Tray (as_, bs, cs)
        | BC -> let bs, cs = move bs cs in Tray (as_, bs, cs)
        | CB -> let cs, bs = move cs bs in Tray (as_, bs, cs)
      end
  with Invalid_argument _ -> None

let next_states state =
  List.fold_left
    (fun acc ->
     function
     | None -> acc
     | Some s -> s :: acc)
    []
  @@ List.map (move state) [CB; BC; BA; AB]

let search initial_state max_swaps =
  let states = Queue.create () in
  Queue.push (initial_state, 0) states;
  let seen = Hashtbl.create 1024 in
  let rec search () =
    if Queue.length states = 0 then -1
    else
      let state, count = Queue.pop states in
      if finished state then count
      else if count > max_swaps then -1
      else if Hashtbl.mem seen state then search ()
      else
        begin
          Hashtbl.add seen state true;
          List.iter
            (fun next_state -> Queue.push (next_state, succ count) states)
            @@ List.filter
                 (fun state -> not @@ Hashtbl.mem seen state)
                 (next_states state);
          search ()
        end in
  search ()

let read_lines n =
  let rec read_lines n acc =
    if n = 0 then List.rev acc
    else read_lines (pred n) ((read_line ()) :: acc) in
  read_lines n []

let split str delim =
  let len = String.length str in
  let rec split offset acc =
    try
      let index = String.index_from str offset delim in
      split (index + 1) ((String.sub str offset (index - offset)) :: acc)
    with Not_found -> List.rev ((String.sub str offset (len - offset)) :: acc) in
  split 0 []

let rec solve () =
  let read_tray () =
    List.rev @@ List.tl @@ List.map int_of_string @@ split (read_line ()) ' ' in
  let line = read_line () in
  let n_cups, max_swaps = Scanf.sscanf line "%d %d" (fun n m -> (n, m)) in
  if (n_cups, max_swaps) = (0, 0) then ()
  else
    let tray_a = read_tray () in
    let tray_b = read_tray () in
    let tray_c = read_tray () in
    print_endline @@ string_of_int
    @@ search (Tray (tray_a, tray_b, tray_c)) max_swaps;
    solve ()

let () = solve ()