main = print . solve . map read . words =<< getContents

solve :: [Int] -> Int
solve (n:xs)
    | all (/=2) xs = -1
    | otherwise = f 1 0
    where
        f 2 t = t
        f i t
            | n <= t = -1
            | otherwise = f (xs!!(i-1)) (t+1)
