Skip to content

Instantly share code, notes, and snippets.

@naota
Created July 26, 2010 17:39
Show Gist options
  • Save naota/490897 to your computer and use it in GitHub Desktop.
Save naota/490897 to your computer and use it in GitHub Desktop.
data Road = Road { src :: Int
, dst :: Int
, cost :: Int
} deriving (Eq)
main :: IO ()
main = interact func
func :: String -> String
func s = let ds = lines s
n = head ds
rs = tail ds
in show (func' (read n) (map toRoad rs))
toRoad :: String -> Road
toRoad s = let ws = words s in Road { src = read $ ws!!0
, dst = read $ ws!!1
, cost = read $ ws!!2
}
func' :: Int -> [Road] -> Int
func' _ rs = if costOne < costAnother
then costOne
else costAnother
where oc = ocf ++ oct
ocf = connectFrom 1 rs
oct = connectTo 1 rs
costOne = cycleCost 1 (oc!!0) rs
costAnother = cycleCost 1 (oc!!1) rs
cycleCost :: Int -> Road -> [Road] -> Int
cycleCost pos road rs = if nextPos == 1
then nowCost
else nowCost + cycleCost nextPos nextRoad rs
where nextRoad = head $ filter (\r -> r /= road) $ connected pos rs
(nextPos, nowCost) = if src nextRoad == pos
then (dst nextRoad, 0)
else (src nextRoad, cost nextRoad)
connected :: Int -> [Road] -> [Road]
connected n rs = connectFrom n rs ++ connectTo n rs
connectFrom :: Int -> [Road] -> [Road]
connectFrom n rs = filter (\r -> src r == n) rs
connectTo :: Int -> [Road] -> [Road]
connectTo n rs = filter (\r -> dst r == n) rs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment