{-# LANGUAGE BangPatterns#-}
module Main where


import Data.Maybe
import Control.Monad
import Data.Functor

main :: IO ()
main = do
  (cups,mvs) <- getNM
  unless (cups==0 && mvs==0) $
    do
      initState <- getState
      print $ solve mvs initState
      main
  where
    getNM::IO (Int,Int)
    getNM=do
       (n:m:_)<-map read . words <$> getLine
       return (n,m)
    getTray::IO [Int]
    getTray=do
      (n:try) <- map read . words <$> getLine
      return $ reverse $ take n try
    getState::IO GameState
    getState=do
      [ta,tb,tc] <-replicateM 3 getTray
      return $ GameState (Tray ta tb tc) []

data Move=AB|BA|BC|CB deriving(Eq)

data Tray=Tray {trayA::[Int]
              , trayB::[Int]
              , trayC::[Int]
               }

data GameState=GameState {tray::Tray
                        , history::[Move]}

solve::Int->GameState->Int
solve mvs state=solve' mvs [state] mvs
  where
    solve'::Int->[GameState]->Int->Int
    solve' _ states (-1) = -1
    solve' m states !n
      |any (\x->isClearA x || isClearC x) states =m-n
      |otherwise =solve' m
                  (concatMap (\st@(GameState tr hi)->moves (noReturn hi) st) states )
                  (n-1)
move::Move->GameState->Maybe GameState
move mv (GameState tray hist)=do
  tray' <- move'' mv tray
  return $ GameState tray' (mv:hist)
  where
    move''::Move->Tray->Maybe Tray
    move'' AB (Tray ta tb tc)=do
      (ta',tb') <- move' (ta,tb)
      return $ Tray ta' tb' tc
    move'' BA (Tray ta tb tc)=do
      (tb',ta') <- move' (tb,ta)
      return $ Tray ta' tb' tc
    move'' BC (Tray ta tb tc)=do
      (tb',tc') <- move' (tb,tc)
      return $ Tray ta tb' tc'
    move'' CB (Tray ta tb tc)=do
      (tc',tb') <- move' (tc,tb)
      return $ Tray ta tb' tc'
    move'::([Int],[Int])->Maybe([Int],[Int])
    move' ([],_)=Nothing
    move' (x:xs,[])=Just (xs,[x])
    move' (x:xs,tr@(y:ys))
      |x>y =Just (xs,x:tr)
      |otherwise=Nothing

moves::[Move]->GameState->[GameState]
moves mvs state=mapMaybe  (`move` state) mvs

isClearA::GameState->Bool
isClearA (GameState (Tray _ [] []) _)=True
isClearA _ =False

isClearC::GameState->Bool
isClearC (GameState (Tray [] [] _) _)=True
isClearC _=False

noReturn::[Move]->[Move]
noReturn (x:_) =filter (/= x) [AB,BA,BC,CB]
noReturn []=[AB,BA,BC,CB]