import Data.List (sort) import qualified Data.IntMap as M main = interact $ show . solve . map (map read . words) . lines solve ([n,k]:xs) = ans where xxs = reverse . sort $ xs ans = M.foldl max 0 . foldl f M.empty $ xxs f m [p, d] = M.insertWith max (-p) d mm where mm = M.foldlWithKey g m m g w e c | e > 0 && (p + e) <= k = M.insertWith max (-(p + e)) (c + d) w | e < 0 = M.insertWith max (-e) (c + d) w | otherwise = w