{-# LANGUAGE RecordWildCards #-} import Control.Monad.State.Lazy import Data.List data Question = Question { days :: Int, moveCost :: Int, tokyoIncome :: [Int], kyotoIncome :: [Int] } deriving Show data CalcState = CalcState { maxTokyo :: Int, maxKyoto :: Int } deriving Show input :: IO Question input = do [d, c] <- getLineData [tx, kx] <- fmap transpose $ sequence $ replicate d getLineData return Question { days = d, moveCost = c, tokyoIncome = tx, kyotoIncome = kx } where getLineData = fmap (map read . words) getLine process :: Question -> Int process Question {..} = let CalcState {..} = execState (process' 1) $ CalcState { maxTokyo = 0, maxKyoto = -moveCost } in max maxTokyo maxKyoto where process' :: Int -> State CalcState () process' d | d > days = return () | otherwise = do modify $ \CalcState {..} -> let (maxTokyo', maxKyoto') = (tokyoIncome !! (d - 1) + max maxTokyo (maxKyoto - moveCost), kyotoIncome !! (d - 1) + max (maxTokyo - moveCost) maxKyoto) in CalcState { maxTokyo = maxTokyo', maxKyoto = maxKyoto' } process' (d + 1) main :: IO () main = input >>= return . process >>= print