题解 P1478 【陶陶摘苹果(升级版)】

HoshinoTented

2019-03-10 01:28:25

Solution

# 先说几句 ~~代刷真难, 还要帮忙写题解, 这年头做什么都难啊~~ # 思路 既然是想要更多的苹果。。 自然是贪心~~吧~~ 将苹果从小到大排序所需要的力气, 然后迭代, 累计数目 # [题解(Haskell)](https://github.com/HoshinoTented/LuoGu/blob/master/haskell/src/P1478.hs) ```haskell module P1478 where import Data.List (sortBy) -- 导入 Data.List 包, 需要里面的 sortBy type Height = Int -- 类型别名, 下同 type Force = Int -- 摘苹果 :: 最大高度 (const) -> 剩余力气 -> [苹果] -> 能够摘到的最多苹果 pick :: Height -> Force -> [(Height, Force)] -> Int pick _ _ [] = 0 -- 如果没有任何苹果, 返回 0 pick h f ((nh, nf):as) | h < nh = pick h f as -- 如果高度够不着, 则跳过 | f < nf = 0 -- 如果力气不够, 直接返回 0, 因为传进来的苹果列表是力气升序的 | otherwise = 1 + pick h (f - nf) as -- 如果条件都符合, 则累计一个苹果, 并继续摘剩余的苹果 -- 读取苹果数据 readApples :: Int -> IO [(Height, Force)] readApples 0 = return [] readApples n = do [nh, nf] <- map read . words <$> getLine ((nh, nf):) <$> readApples (n - 1) -- 程序入口 main :: IO () main = do -- [苹果数目, 初始力气] [ac, fs] <- map read . words <$> getLine :: IO [Int] -- [椅子高度, 手伸直的最大高度] [h, l] <- map read . words <$> getLine :: IO [Int] -- 读苹果并排序它们的所需力气 apples <- sortBy (\(_, a) (_, b) -> compare a b) <$> readApples ac -- 计算并输出 print $ pick (h + l) fs apples -- 没有任何作用的 reuturn () return () ```