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 rs
            | n <= t = -1
            | next == i = -1
            | any (==i) rs = -1
            | otherwise = f next (t+1) (i:rs)
            where
                next = xs!!(i-1)
