import Control.Monad import Data.Maybe import Data.List last' xs = if null xs then Nothing else Just (last xs) main = do n <- readLn as <- replicateM n getLine m <- readLn bs <- replicateM m getLine putStrLn (maybe "-1" id (brokenAcc as bs)) brokenAcc as bs = do let as' = map (checkps bs) as guard (valid as') return (connect as') checkps bs a = (a, (prev,next)) where pre = head a suf = last a prev = find (elem pre) bs >>= last' . takeWhile (/= pre) next = find (elem suf) bs >>= last' . takeWhile (/= suf) . reverse valid = (\(ps,ss) -> (nothing ps, nothing ss) == (1,1)) . unzip . map snd where nothing = length . filter isNothing connect as = concat (unfoldr connect' (as,Nothing)) where connect' ([],_) = Nothing connect' (as,next) = Just (a, (as',Just (last a))) where ([(a,(_,s))],as') = partition ((==next).fst.snd) as