Advertisement
Guest User

Untitled

a guest
Jan 17th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. import Data.List (lines)
  2.  
  3. data Node = Node Road (Maybe Road)
  4. data Road = Road Int Node
  5.  
  6. data Section = Section { getA :: Int
  7. , getB :: Int
  8. , getC :: Int
  9. } deriving (Show)
  10.  
  11. type RoadSystem = [Section]
  12.  
  13. data Label = A | B | C deriving (Show)
  14.  
  15. type Path = [(Label, Int)]
  16.  
  17. heathrowToLondon :: RoadSystem
  18. heathrowToLondon = [Section 50 10 30, Section 5 90 20, Section 40 2 25, Section 10 8 0]
  19.  
  20. roadStep :: (Path, Path) -> Section -> (Path, Path)
  21. roadStep (pathA, pathB) (Section a b c) = (newPathToA, newPathToB)
  22. where
  23. priceA = sum $ map snd pathA
  24. priceB = sum $ map snd pathB
  25. forwardPriceToA = priceA + a
  26. crossPriceToA = priceB + b + c
  27. forwardPriceToB = priceB + b
  28. crossPriceToB = priceA + a + c
  29. newPathToA = if forwardPriceToA <= crossPriceToA
  30. then (A, a) : pathA
  31. else (C, c) : (B, b) : pathB
  32. newPathToB = if forwardPriceToB <= crossPriceToB
  33. then (B, b) : pathB
  34. else (C, c) : (A, a) : pathA
  35.  
  36. optimalPath :: RoadSystem -> Path
  37. optimalPath roadSystem = if sum (map snd bestAPath) <= sum (map snd bestBPath)
  38. then reverse bestAPath
  39. else reverse bestBPath
  40. where
  41. (bestAPath, bestBPath) = foldl roadStep ([],[]) roadSystem
  42.  
  43. groupsOf :: Int -> [a] -> [[a]]
  44. groupsOf 0 _ = error "grouping by 0"
  45. groupsOf _ [] = []
  46. groupsOf n xs = take n xs : groupsOf n (drop n xs)
  47.  
  48. main = do
  49. contents <- getContents
  50. let threes = groupsOf 3 (map read $ lines contents)
  51. roadSystem = map (\[a, b, c] -> Section a b c) threes
  52. path = optimalPath roadSystem
  53. pathString = concatMap (show . fst) path
  54. pathPrice = sum $ map snd path
  55. putStrLn $ "The best path to take is: " ++ pathString
  56. putStrLn $ "The price of that path is: " ++ show pathPrice
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement