Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Data.List (lines)
- data Node = Node Road (Maybe Road)
- data Road = Road Int Node
- data Section = Section { getA :: Int
- , getB :: Int
- , getC :: Int
- } deriving (Show)
- type RoadSystem = [Section]
- data Label = A | B | C deriving (Show)
- type Path = [(Label, Int)]
- heathrowToLondon :: RoadSystem
- heathrowToLondon = [Section 50 10 30, Section 5 90 20, Section 40 2 25, Section 10 8 0]
- roadStep :: (Path, Path) -> Section -> (Path, Path)
- roadStep (pathA, pathB) (Section a b c) = (newPathToA, newPathToB)
- where
- priceA = sum $ map snd pathA
- priceB = sum $ map snd pathB
- forwardPriceToA = priceA + a
- crossPriceToA = priceB + b + c
- forwardPriceToB = priceB + b
- crossPriceToB = priceA + a + c
- newPathToA = if forwardPriceToA <= crossPriceToA
- then (A, a) : pathA
- else (C, c) : (B, b) : pathB
- newPathToB = if forwardPriceToB <= crossPriceToB
- then (B, b) : pathB
- else (C, c) : (A, a) : pathA
- optimalPath :: RoadSystem -> Path
- optimalPath roadSystem = if sum (map snd bestAPath) <= sum (map snd bestBPath)
- then reverse bestAPath
- else reverse bestBPath
- where
- (bestAPath, bestBPath) = foldl roadStep ([],[]) roadSystem
- groupsOf :: Int -> [a] -> [[a]]
- groupsOf 0 _ = error "grouping by 0"
- groupsOf _ [] = []
- groupsOf n xs = take n xs : groupsOf n (drop n xs)
- main = do
- contents <- getContents
- let threes = groupsOf 3 (map read $ lines contents)
- roadSystem = map (\[a, b, c] -> Section a b c) threes
- path = optimalPath roadSystem
- pathString = concatMap (show . fst) path
- pathPrice = sum $ map snd path
- putStrLn $ "The best path to take is: " ++ pathString
- putStrLn $ "The price of that path is: " ++ show pathPrice
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement