main :: IO () main = interact $ show . solve . map read . words splitEvery2 :: [Int] -> [[Int]] splitEvery2 = takeWhile (not . null) . map (take 2) . iterate (drop 2) solve :: [Int] -> Int solve (n:m:xs) = foldl (\n -> \t -> if head t == n then last t else if last t == n then head t else n) n ys where ys = splitEvery2 xs