Skip to content

Instantly share code, notes, and snippets.

@SPY
Last active August 29, 2015 14:18
Show Gist options
  • Save SPY/b2ec71ab27e1374f3ddf to your computer and use it in GitHub Desktop.
Save SPY/b2ec71ab27e1374f3ddf to your computer and use it in GitHub Desktop.
import Control.Applicative ((<$>))
import Data.List (partition)
readNumList :: String -> [Int]
readNumList = map read . words
segmentsCount :: [Int] -> [[Int]] -> Int
segmentsCount [] _ = 0
segmentsCount (v:vs) edges = let (vs', es') = mark v vs edges in 1 + segmentsCount vs' es'
mark :: Int -> [Int] -> [[Int]] -> ([Int], [[Int]])
mark v vs es =
let (adjEdges, another) = partition (elem v) es in
let adj = map (head . filter (/= v)) adjEdges in
foldl (\(vs, es) v -> mark v (filter (/= v) vs) es) (vs, another) adj
main :: IO ()
main = do
[v, e] <- readNumList <$> getLine
edges <- map readNumList <$> (sequence $ replicate e getLine)
print $ segmentsCount [1..v] edges
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment