
import qualified Data.Map as Map
import Data.Maybe
import qualified Control.Monad.State as St
import Control.Monad

newtype Env = Env { runEnv :: (Map.Map Int Int, Map.Map Int Int, Map.Map Int Int) }
  deriving (Eq,Show)

kenkenpa' :: Int -> St.State Env Int
kenkenpa' start = do
  env <- St.get
  let (m1,m2,m3) = runEnv env
  case Map.lookup start m1 of
    Nothing -> return (-1)
    Just r1 ->
      case Map.lookup r1 m2 of
        Nothing -> return (-1)
        Just r2 -> 
          case Map.lookup r2 m3 of
            Nothing -> return (-1)
            Just r3 -> do
              St.put . Env $ (Map.delete start m1, Map.delete r1 m2, Map.delete r2 m3)
              return r3

find :: Int -> Int -> Int -> St.State Env Int
find start dest num = do
  r <- kenkenpa' start
  if r == (-1) then return (-1)
  else if r == dest then return num
  else find r dest (num+1)



-- main = do
--   _ <- getLine
--   s <- map  ((\ls -> (head ls,last ls)) . map read . words) . lines <$> getContents :: IO [(Int,Int)]
--   let map = Map.fromList (init s)
--   let (start,dest) = last s
--   -- print $ steps map [start] start dest 0
--   print $ St.evalState (find start dest 1) (Env (map,map,map))

main = do
  m <- last . map read . words <$> getLine :: IO Int
  s <- replicateM m getLine :: IO [String]
  s1 <- map read . words <$> getLine :: IO [Int]
  let (start,dest) = (head s1, last s1)
  let tmp = map ((\ls -> (head ls, last ls)) . map read . words) s
  let map = Map.fromList tmp
  print $ St.evalState (find start dest 1) (Env (map,map,map))


