import Control.Applicative ((<$>)) import Control.Monad (replicateM) data Pos = Tokyo | Kyoto deriving Eq flipPos :: Pos -> Pos flipPos Tokyo = Kyoto flipPos Kyoto = Tokyo toIdx :: Pos -> Int toIdx Tokyo = 0 toIdx Kyoto = 1 getNums :: IO [Int] getNums = map read . words <$> getLine {- dp[i][k] := i までで位置 k で何円か dp[i+1][k] := max( dp[i][k]+TK[k][i], dp[i][!k]+Tk[k][i]-d ) -} main :: IO () main = do [n, d] <- getNums :: IO [Int] ([iniT,iniK]:tks) <- replicateM n getNums print $ (\[a,b] -> max a b) $ foldl (f d) [iniT,iniK-d] tks f :: Int -> [Int] -> [Int] -> [Int] f d dps tks = [dp Tokyo, dp Kyoto] where dp pos = (dps!!curIdx + tks!!curIdx) `max` (dps!!revIdx + tks!!curIdx - d) where curIdx = toIdx pos revIdx = toIdx $ flipPos pos