Skip to content

Instantly share code, notes, and snippets.

@rgrig
Last active November 24, 2020 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rgrig/a8f18a7060171d8d41597c85bee4a3eb to your computer and use it in GitHub Desktop.
Save rgrig/a8f18a7060171d8d41597c85bee4a3eb to your computer and use it in GitHub Desktop.
import Data.Array.IArray (Array, array, (!), elems)
imap :: (Int -> a -> b) -> [a] -> [b]
imap = m 1
where
m _ _ [] = []
m i f (x : xs) = (f i x) : m (i + 1) f xs
solve :: [Int] -> Int
solve xs = n - cyclesCount
where
n = length xs
bindings = imap (\i x -> (i, lookup i x)) xs
lookup i x = if i <= x then x else lookup i (table ! x)
table = array (1, n) bindings :: Array Int Int
cyclesCount = length $ filter id $ imap (==) $ elems table
main = interact ((++"\n") . show . solve . map read . words . (!!1) . lines)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment