Statistics claims that students sleep no more than three hours a day. But even in the world of their dreams, while they are snoring peacefully, the sense of impending doom is still upon them.A poor student is dreaming that he is sitting the mathematical analysis exam. And he is examined by the most formidable professor of all times, a three times Soviet Union Hero, a Noble Prize laureate in student expulsion, venerable Petr Palych.The poor student couldn't answer a single question. Thus, instead of a large spacious office he is going to apply for a job to thorium mines. But wait a minute! Petr Palych decided to give the student the last chance! Yes, that is possible only in dreams. So the professor began: "Once a Venusian girl and a Marsian boy met on the Earth and decided to take a walk holding hands. But the problem is the girl has al fingers on her left hand and ar fingers on the right one. The boy correspondingly has bl and br fingers. They can only feel comfortable when holding hands, when no pair of the girl's fingers will touch each other. That is, they are comfortable when between any two girl's fingers there is a boy's finger. And in addition, no three fingers of the boy should touch each other. Determine if they can hold hands so that the both were comfortable."The boy any the girl don't care who goes to the left and who goes to the right. The difference is only that if the boy goes to the left of the girl, he will take her left hand with his right one, and if he goes to the right of the girl, then it is vice versa.

The first line contains two positive integers not exceeding 100. They are the number of fingers on the Venusian girl's left and right hand correspondingly. The second line contains two integers not exceeding 100. They are the number of fingers on the Marsian boy's left and right hands correspondingly.

Print YES or NO, that is, the answer to Petr Palych's question.

NoteThe boy and the girl don't really care who goes to the left.

module Main where

import Control.Monad

confortable a b = a <= b+1 && b <= (a+1)*2

main = do
    [al, ar] <- ( map read . words ) `liftM` getLine
    [bl, br] <- ( map read . words ) `liftM` getLine

    putStrLn $ if confortable al br || confortable ar bl
        then "YES"
        else "NO"

readInts :: IO [Int]
readInts = do
  line <- getLine
  return (map read (words line))

ok :: Int -> Int -> Bool
ok girl boy = boy >= girl - 1 && boy <= 2 * (girl + 1)

main = do
  [gl, gr] <- readInts
  [bl, br] <- readInts
  if ok gl br || ok gr bl then putStrLn "YES" else putStrLn "NO"

main = do
    [al, ar] <- map read `fmap` (words `fmap` getLine)
    [bl, br] <- map read `fmap` (words `fmap` getLine)
    let f a b = a - 1 <= b && b <= 2*(a+1)
    putStr (if f al br || f ar bl then "YES" else "NO")

main = do
    line1 <- getLine
    line2 <- getLine
    let
        [gl,gr] = map read $ words line1
        [bl,br] = map read $ words line2
        possible b g = b >= g-1 && (g+1)*2>=b
        result = possible br gl || possible bl gr
        myshow True = "YES"
        myshow False = "NO"
    putStrLn $ myshow result

main = interact $ solve . (map (map (read :: String -> Int))) . (map words) . lines
solve [[al,ar],[bl,br]] = if (al<=br+1 && br<=(al+1)*2) ||
                             (ar<=bl+1 && bl<=(ar+1)*2) then "YES"
                                                        else "NO"

main = interact $ solve . (map (map (read :: String -> Int))) . (map words) . lines
solve [[al,ar],[bl,br]] = if (lr<2 && -3<lr) || (rl<2 && -3<rl) then "YES"
                                                                else "NO"
                                                                where lr=al-br
                                                                      rl=ar-bl


Tomorrow Peter has a Biology exam. He does not like this subject much, but d days ago he learnt that he would have to take this exam. Peter's strict parents made him prepare for the exam immediately, for this purpose he has to study not less than minTimei and not more than maxTimei hours per each i-th day. Moreover, they warned Peter that a day before the exam they would check how he has followed their instructions.So, today is the day when Peter's parents ask him to show the timetable of his preparatory studies. But the boy has counted only the sum of hours sumTime spent him on preparation, and now he wants to know if he can show his parents a timetable sсhedule with d numbers, where each number sсhedulei stands for the time in hours spent by Peter each i-th day on biology studies, and satisfying the limitations imposed by his parents, and at the same time the sum total of all schedulei should equal to sumTime.

The first input line contains two integer numbers d, sumTime (1 ≤ d ≤ 30, 0 ≤ sumTime ≤ 240) — the amount of days, during which Peter studied, and the total amount of hours, spent on preparation. Each of the following d lines contains two integer numbers minTimei, maxTimei (0 ≤ minTimei ≤ maxTimei ≤ 8), separated by a space — minimum and maximum amount of hours that Peter could spent in the i-th day.

In the first line print YES, and in the second line print d numbers (separated by a space), each of the numbers — amount of hours, spent by Peter on preparation in the corresponding day, if he followed his parents' instructions; or print NO in the unique line. If there are many solutions, print any of them.

import Control.Monad

foldTuples :: [(Int, Int)] -> ((Int, Int) -> Int) -> Int
foldTuples l f = foldl (\prev t -> prev + f t) 0 l

getMin :: [(Int, Int)] -> Int
getMin l = foldTuples l fst

getMax :: [(Int, Int)] -> Int
getMax l = foldTuples l snd

getTuple :: IO (Int, Int)
getTuple = do
    s <- getLine
    let l = map read $ words s :: [Int]
    return (l !! 0, l !! 1)

canSolve :: Int -> [(Int, Int)] -> Bool
canSolve acum l = getMin l <= acum && acum <= getMax l

solve :: Int -> [(Int, Int)] -> [Int]
solve goal l = solve' goal l (getMin l)

solve' :: Int -> [(Int, Int)] -> Int -> [Int]
solve' _ [] _ = []
solve' goal (x:xs) curr =
    let delta = snd x - fst x
    in (
        if curr + delta <= goal then (snd x) : solve' goal xs (curr + delta)
        else (fst x + goal - curr) : solve' goal xs (curr + (goal - curr))
    )

main = do
    (d, sumTime) <- getTuple
    l <- replicateM d getTuple
    if canSolve sumTime l
        then do
            putStrLn "YES"
            putStrLn $ unwords $ map show (solve sumTime l)
        else do
            putStrLn "NO"

main = interact $ solve . map (map read . words) . lines

solve :: [[Int]] -> String
solve ([_, goal]:l) =
    let mn = foldr ((+) . head) 0 l in
    let mx = foldr ((+) . (!! 1)) 0 l in
    if mn <= goal && goal <= mx
    then "YES\n" ++ (unwords . map show $ f mn l) ++ "\n"
    else "NO\n"
    where f _ [] = []
          f acum ([a, b]:rest) = if acum + (b-a) <= goal
                                 then b:f (acum + (b-a)) rest
                                 else (a + (goal-acum)):f goal rest

main = interact $ solve . (((read <$>) . words) <$>) . lines
  where
    solve (x:xs)
      | sumof minimum xs > last x || sumof maximum xs < last x = "NO"
      | otherwise = "YES\n" ++ (unwords . (show <$>)) (arrange xs $ last x - sumof minimum xs)
    sumof f = sum . (f <$>)
    arrange [] _ = []
    arrange (p:ps) remn
      | remn > diff = last p : arrange ps (remn - diff)
      | remn <= last p = head p + remn : arrange ps 0
      where
        diff = last p - head p

main = interact $ solve . map (map read . words) . lines
  where
    solve (x:xs)
      | sumof minimum xs > last x || sumof maximum xs < last x = "NO"
      | otherwise =
        "YES\n" ++ (unwords . map show) (arrange xs $ last x - sumof minimum xs)
    sumof f = sum . (f <$>)
    arrange [] _ = []
    arrange (p:ps) remn
      | remn > diff = last p : arrange ps (remn - diff)
      | remn <= last p = head p + remn : arrange ps 0
      where
        diff = last p - head p

import Data.List

solve :: [[Int]] -> String
solve ([_, s] : ts) = if lb <= s && s <= ub then "YES\n" ++ unwords (map show ys) else "NO"
  where
    [lb, ub] = map sum $ transpose ts

    mapper d [l, u] = (d - used, l + used) where used = min (u-l) d
    ys = snd $ mapAccumL mapper (s - lb) ts

main :: IO ()
main = interact $ solve . map (map read . words) . lines

import Data.List (transpose, unfoldr)

solve :: [Int] -> String
solve (_ : s : xs) = if lb <= s && s <= ub then "YES\n" ++ unwords (map show ys) else "NO"
  where
    chunks n = takeWhile (not . null) . unfoldr (Just . splitAt n)
    ts = chunks 2 xs
    [lb, ub] = map sum $ transpose ts

    folder (d, acc) [l, u] = (d - used, l + used : acc)
      where used = min (u-l) d
    ys = reverse . snd $ foldl folder (s - lb, []) ts

main :: IO ()
main = interact $ solve . map read . words

import Data.List

solve :: [Int] -> String
solve (_ : s : xs) = if lb <= s && s <= ub then "YES\n" ++ unwords (map show ys) else "NO"
  where
    chunks n = takeWhile (not . null) . unfoldr (Just . splitAt n)
    ts = chunks 2 xs
    [lb, ub] = map sum $ transpose ts

    mapper d [l, u] = (d - used, l + used) where used = min (u-l) d
    ys = snd $ mapAccumL mapper (s - lb) ts

main :: IO ()
main = interact $ solve . map read . words

{-# LANGUAGE ScopedTypeVariables,TupleSections #-}
import Control.Monad
data State s a = State {runState :: s->(a,s)}
instance Monad (State s) where
        return = State . (,)
        (State f1) >>= f2 = State $ uncurry (runState . f2) . f1
        (State f1) >> (State f2) = State $ f2 .snd . f1

repeatM a = mapM (const a) (repeat 1)
repeatMn a n = mapM (const a) [1..n]
readm::(Read a) => State String a
readm = State (head . reads)
readchar = State (\s->(head s,tail s))
csum  = foldr (\x y -> (x + head y) : y) [0]

runRead x s = fst $ runState x s

solve [] _ _ = []
solve ls l s = x : solve (tail ls) (tail l) (s-x) where
	(smin,smax) = head ls
	(dmin,dmax) = head l
	x = if (s-dmin <= smax) then dmin else (s-smax)

main = reader >>= writer . solver
reader = getContents
writer = putStr
solver = runRead $ do
	d<-readm
	sumTime<-readm
	times::[(Int,Int)] <- mapM (const (liftM2 (,) readm readm)) [1..d]
	let smin = csum . map fst $ times
	let smax = csum . map snd $ times
	let stimes = zip smin smax
	let solution =(solve (tail stimes) times sumTime)
	return (if sumTime >= (fst.head $ stimes) && sumTime <= (snd.head $ stimes) then ("YES\n"++ (unwords . map show $  solution)) else "NO")

module Main where

import Control.Monad

main = do
    [d, sumT] <- ( map read . words ) `liftM` getLine
    insts <- replicateM d $ do
        [a, b] <- ( map read . words ) `liftM` getLine
        return (a, b)

    putStrLn $ maybe "NO" ( ( "YES\n" ++ ) . unwords . map show) $ extract sumT insts

extract :: Int -> [(Int, Int)] -> Maybe [Int]
extract sumT insts = extract' (sumT, sumT) insts >>= return . fst
    where
        extract' (minT, maxT) [] =
            if minT <= 0 && 0 <= maxT
                then Just ([], 0)
                else Nothing
        extract' (minT, maxT) ((minI, maxI) : is) = do
            (res, consume) <- extract' (minT-maxI, maxT-minI) is
            let take = max (minT-consume) minI
            return ( take : res, take + consume )

import Data.List

readPairInt :: String -> (Int, Int)
readPairInt xs = ((read pre)::Int, (read suf)::Int)
    where (pre, suf) = break (== ' ') xs

listAll [] = [[]]
listAll xss = [x:y | x <- (head xss), y <- (listAll (tail xss))]

mySolver :: Int -> [Int] -> [Int] -> [Int]
mySolver 0 _ _ = []
mySolver curSum minList maxsumList = thisDay : (mySolver (curSum - thisDay) (tail minList) (tail maxsumList))
    where thisDay = max (curSum - (head (tail maxsumList))) (head minList)

myFunction :: String -> String
myFunction input = if (sumHours < minHours || sumHours > maxHours)
                   then "NO\n"
                   else "YES\n" ++ aSolution ++ "\n"
    where inputLines = lines input
          (days, sumHours) = readPairInt (head inputLines)
          hourLimits = map readPairInt (tail inputLines)
          minsumList = scanr (+) 0 $ map fst hourLimits
          maxsumList = scanr (+) 0 $ map snd hourLimits
          minHours = head minsumList
          maxHours = head maxsumList
          aSolution' = mySolver sumHours (map fst hourLimits) maxsumList
          aSolution'' = aSolution' ++ (replicate (days - length aSolution') 0)
          aSolution = unwords $ map show $ aSolution''

main = interact $ myFunction

import Data.List

main = interact $ solve . map (map read . words) . lines

solve ([_, sumTime]:rest) =
    let minSumTime = sum $ map head rest in
    let maxSumTime = sum $ map (head . tail) rest in
    if minSumTime <= sumTime && sumTime <= maxSumTime
    then tostr $ f sumTime minSumTime maxSumTime rest
    else "NO"
    where f sum minsum maxsum ([a, b]:rest) =
              let c = min b (sum - minsum + a) in
              c : f (sum - c) (minsum - a) (maxsum - c) rest
          f sum minsum maxsum [] = []
          tostr x = "YES\n" ++ intercalate " " (map show x)

module Main where
main = do
	instr <- getLine
	let [d, sumTime] = map readInt $ words instr
	instr <- getContents
	let pairs = map readInts (lines instr)
	let mins = map (\[x,_] -> x) pairs
	let maxs = map (\[_,x] -> x) pairs
	let res = solve d sumTime mins maxs (sum mins) (sum maxs)
	putStrLn (if null res then "NO" else "YES")
	mapM_ (putStr.(++ " ").show) res
	putStrLn ""

solve :: Int -> Int -> [Int] -> [Int] -> Int -> Int -> [Int]
solve d sumTime mins maxs sumMin sumMax =
	if sumTime >= sumMin && sumTime <= sumMax
	then zipWith (+) mins $
		simpleSolve d (sumTime - sumMin) (zipWith (-) maxs mins)
	else []

simpleSolve :: Int -> Int -> [Int] -> [Int]
simpleSolve 1 time [z] = [minimum [time, z]]
simpleSolve d time (z:zs) =
	minimum [time, z] : simpleSolve (d-1) (time - minimum [time, z]) zs

readInts :: String -> [Int]
readInts s = map readInt (words s)

readInt :: String -> Int
readInt = read

import Control.Monad (replicateM)
import Prelude hiding (reads)

reads :: IO (Int, Int)
reads  =  do
    [x, y]  <-  getLine >>= return . map read . words
    return (x, y)

solve :: Int -> [(Int, Int)] -> Maybe [Int]
solve t xs
  | mn > t || t > mx  =  Nothing
  | otherwise  =  Just (solve' (t - mn) xs)
  where
    mn  =  sum $ map fst xs
    mx  =  sum $ map snd xs
    solve' 0 xs  =  map fst xs
    solve' n []  =  undefined
    solve' n ((a,b):xs)
      | b - a >= n  =  (a + n) : (solve' 0 xs)
      | otherwise  =  b : (solve' (n - (b-a)) xs)

printAns :: Maybe [Int] -> IO ()
printAns Nothing  =  putStrLn "NO"
printAns (Just xs)  =  putStrLn "YES" >> prints xs
  where
    prints [x]  =  print x
    prints (x:xs)  =  putStr (show x ++ " ") >> prints xs

main :: IO ()
main  =  do
    (n, t)  <-  reads
    as  <-  replicateM n reads
    printAns $ solve t as

import Data.List
import Control.Monad
readP s = head $ reads s >>= \(a,s') -> return (a,read s')
main = do
  (d,s) <- liftM readP getLine
  ds <- replicateM d (liftM readP getLine)
  let low = sum $ map fst ds
      high = sum $ map snd ds
  if s < low || s > high
    then putStrLn "NO"
    else do
      putStrLn "YES"
      putStrLn . unwords . map show . snd $ mapAccumL f (s-low) ds
          where f r (l,h) = (r-r',l+r') where r' = min r (h-l)

import Data.Functor
import Data.List
import Control.Monad

data T = T Int Int Int
    deriving (Show)

solve :: T -> ([T], Int) -> ([T], Int)
solve (T minT maxT _) (ts, rest)
    | rest > 0 = (T minT maxT curT : ts, rest - curT)
    | otherwise = (T minT maxT minT : sub minT ts, rest - minT)
  where
    curT = min maxT rest

sub :: Int -> [T] -> [T]
sub 0 ts = ts
sub n (T minT maxT curT : []) = [T minT maxT (curT - n)]
sub n (T minT maxT curT : ts) = T minT maxT (curT - c) : sub (n - c) ts
  where
    c = min n $ curT - minT

overTime :: T -> Bool
overTime (T minT maxT curT) = curT < minT || maxT < curT

getCurT (T _ _ c) = c

main = do
    d:sumT:_ <- map read . words <$> getLine
    ts <- replicateM d $ do
            minT:maxT:_ <- map read . words <$> getLine
            return $ T minT maxT 0
    let (ts', rest) = foldr solve ([], sumT) ts
    case rest > 0 || overTime (last ts') of
        True -> putStrLn "NO"
        _ -> do
            putStrLn "YES"
            putStrLn $ unwords $ map (show . getCurT) ts'

import Control.Applicative
import Data.Array
import Data.List

readInts :: String -> [Int]
readInts = fmap read . words

solve :: [[Int]] -> String
solve ([days, sumTime] : xss)
  | y `inRange` sumTime = "YES\n" ++ concat (intersperse " " answer)
  | otherwise           = "NO"
 where y : ys = fmap conv . reverse $ scanl1 (zipWith (+)) (take days xss)
       answer = reverse . snd $ mapAccumL f sumTime (zip (conv <$> reverse xss) $ snd (unzip ys) ++ [0])
        where f n (b, z) = (n - candidate, show candidate)
               where candidate = head [x | x <- range b, n - x <= z]
       conv [a, b] = (a, b)

main = interact $ solve . fmap readInts . lines

test1 = solve [[1, 48], [5, 7]]
test2 = solve [[2, 5], [0, 1], [3, 5]]
test3 = solve [[3, 10], [2, 2], [2, 4], [4, 5]]
test4 = solve [[5, 16], [2, 2], [2, 4], [4, 5], [1, 2], [1, 2]]
test5 = solve [[5, 3], [0, 2], [0, 4], [0, 5], [0, 2], [0, 2]]

import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.ST
import Data.List

readInts :: String -> [Int]
readInts = fmap read . words

solve :: [[Int]] -> String
solve ([days, sumTime] : xs) = runST $ do
  let hours = days * 8
  a <- newArray ((0, 0), (days, hours)) maxBound :: ST s (STArray s (Int, Int) Int)
  writeArray a (0, 0) 0
  forM_ (zip [1 ..] (take days xs)) $ \(i, [minH, maxH]) -> do
    forM_ [minH .. maxH] $ \h -> do
      forM_ [0 .. hours] $ \j -> do
        ok <- (/= maxBound) <$> readArray a (i - 1, j)
        when ok $ do
          let j' = j + h
          when ((0, hours) `inRange` j') $ do
            v <- readArray a (i, j')
            writeArray a (i, j') (min v j)
  if sumTime > hours
    then return "NO"
    else do
      ok <- (/= maxBound) <$> readArray a (days, sumTime)
      if ok
        then do
          xs@(x : _) <- reverse <$> answer a days sumTime
          let ys = zipWith subtract xs (tail xs)
          let zs = x : ys
          return $ "YES\n" ++ concat (intersperse " " (show <$> zs))
        else return "NO"
 where
  answer _ 0 _ = return []
  answer a i j = do
    j' <- readArray a (i, j)
    (j :) <$> answer a (i - 1) j'

main = interact $ solve . fmap readInts . lines

test1 = solve [[1, 48], [5, 7]]
test2 = solve [[2, 5], [0, 1], [3, 5]]
test3 = solve [[3, 10], [2, 2], [2, 4], [4, 5]]
test4 = solve [[5, 16], [2, 2], [2, 4], [4, 5], [1, 2], [1, 2]]
test5 = solve [[5, 3], [0, 2], [0, 4], [0, 5], [0, 2], [0, 2]]

main = do
	[d, sumTime] <- map read `fmap` (words `fmap` getLine)
	pairs <- mapM (\_ -> map read `fmap` (words `fmap` getLine)) [1..d]
	let (minSum, maxSum) = foldl (\(si, sx) [i, x] -> (si+i, sx+x)) (0,0) pairs
	if sumTime < minSum || sumTime > maxSum then putStr "NO" else do
		let (_, revS) = foldl (\(delta, s) [minI, maxI] ->
				let a = min maxI (delta + minI) in
				(delta - a + minI, a:s)) (sumTime - minSum, []) pairs
		putStr "YES\n"
		putStr $ unwords $ map show $ reverse revS

import Control.Monad

main = do
     d:sumt:[] <- getLine >>= return . (map read :: [String] -> [Int]) . words
     a <- getContents >>= return . map ((map read :: [String] -> [Int]) . words) . lines
     let sum_min = sum $ map (\(x:xs) -> x) a
     let sum_max = sum $ map (\(_:x:xs) -> x) a
     if sumt < sum_min || sum_max < sumt
        then putStrLn "NO"
        else putStrLn "YES" >> foldM_ (\rest [x,y] -> print (x+min rest (y-x)) >> return (rest-min rest (y-x))) (sumt - sum_min) a

module Main where

import Control.Monad (replicateM)
import Data.List (mapAccumL)

data DayLimits = DayLimits {
    minTime :: !Int,
    extraTime :: !Int
  } deriving (Show)

main :: IO ()
main = do
  [d, sum] <- readInts
  limits <- replicateM d readLimits
  case schedule sum limits of
    Nothing -> putStrLn "NO"
    Just t -> do
      putStrLn "YES"
      putStrLn $ unwords (map show t)

schedule :: Int -> [DayLimits] -> Maybe [Int]
schedule sumTime limits
    | sumTime < minTotalTime || remTime /= 0 = Nothing
    | otherwise                               = Just scheduledTime
  where
    minTotalTime = sum $ map minTime limits
    reduceTime rem limit = let used = min rem (extraTime limit) in (rem - used, used + minTime limit)
    (remTime, scheduledTime) = mapAccumL reduceTime (sumTime - minTotalTime) limits

-- schedule 0   []            = Just []
-- schedule sum _  | sum < 0  = Nothing
-- schedule _   []            = Nothing
-- schedule sum (d:rest) = asum $ map tryTime [minTime d .. maxTime d]
--   where
--     tryTime t = (:) t <$> schedule (sum - t) rest

readInts :: IO [Int]
readInts = map read . words <$> getLine

readLimits :: IO DayLimits
readLimits = do
  [minL, maxL] <- readInts
  pure $ DayLimits minL (maxL - minL)

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Debug.Trace
import Data.List

class Scan a where scan' :: String -> a
instance Scan Int where scan' n = read n
instance Scan Char where scan' (x:_) = x
instance Scan Float where scan' f = read f
instance Scan Double where scan' d = read d
instance Scan Integer where scan' n = read n
instance Scan String where scan' x = x
instance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)
                                                 where
                                                   scan'' (x:y:_) = (scan' x,scan' y)
instance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)
                                                          where
                                                            scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)
instance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)
                                                                   where
                                                                     scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)
instance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)
                                                                            where
                                                                              scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)
class Ans a where showans :: a -> String
instance Ans Int where showans x = show x
instance Ans Char where showans x = [x]
instance Ans Float where showans x = show x
instance Ans Double where showans x = show x
instance Ans Integer where showans x = show x
instance Ans String where showans x = x
instance (Ans a, Ans b) => Ans (a,b) where
    showans (x,y) = showans x ++ " " ++ showans y
instance (Ans a, Ans b,Ans c) => Ans (a,b,c) where
    showans (x,y,z) = showans x ++ " " ++ showans y ++ " " ++ showans z

scan :: (Scan a) => IO a
scan = do n <- getLine
          return (scan' n)

scans :: (Scan a) => Int -> IO [a]
scans 0 = return []
scans n = do x <- scan
             xs <- scans (n-1)
             return (x:xs)

scanlist :: (Scan a) => IO [a]
scanlist = do l <- getLine
              return [scan' x|x<-words l]

scanlists :: (Scan a) => Int -> IO [[a]]
scanlists 0 = return []
scanlists n = do x <- scanlist :: (Scan a) => IO [a]
                 xs <- scanlists (n-1)
                 return (x:xs)

putAnsLn :: (Ans a) => a -> IO ()
putAnsLn ans = putStrLn (showans ans)

putAnsLns :: (Ans a) => [a] -> IO ()
putAnsLns (x:xs) = do putAnsLn x
                      putAnsLns xs
putAnsLns [] = return ()

conv :: Int -> [Int] -> [Int] -> String
conv d mins l = let len = d-(length l) in
                (unwords) (map show (zipWith (+) mins ((reverse l)++(replicate len 0))))

solve _ _ _ [] _ = ["NO"]
solve d sumtime mins (m:ms) l = if sumtime <= m then
                                    ("YES":[(conv d mins (sumtime:l))])
                                else
                                    solve d (sumtime-m) mins ms (trace (show (m:l)) (m:l))

solve' d sumtime [] mins newshd = if sumtime<0 then ["NO"] else solve d sumtime (reverse mins) (reverse newshd) []
solve' d sumtime ((min_,max_):ss) mins newshd = solve' d (sumtime-min_) ss (min_:mins) ((max_-min_):newshd)

main = do (d,sumtime) <- scan :: IO (Int,Int)
          shd <- scans d :: IO [(Int,Int)]
          putAnsLns (solve' d sumtime shd [] [])

{-
problem is defined as the pair (sumTime, [(minTime, maxTime)])
solution is a list time :: [Int] such that:
    (1)     minTime_i <= time_i <= maxTime_i AND
    (2)     sum time == sumTime
we start by setting time to minTime.
If sum time > sumTime then we don't have a solution.
else we need to add to some elements of time such that (2) holds.
We need to add a total of diff = sumTime - sum time to elements of time.
Therefore we traverse and create answer :: [Int] with:
            answer_0 = min maxTime_0 diff
            answer_i = min maxTime_i (sumTime - (sum time_{i..N}) - (sum answer_{0..i-1}))
                       where N = length time
-}
import Debug.Trace
import Data.Maybe

create_answer 0 time = Just (map fst time)
create_answer _ [] = Nothing
create_answer diff ((minTime, maxTime):restTimes)
{-    | trace ("diff:" ++ show diff ++
            " minTime:" ++ show minTime ++
            " maxTime:" ++ show maxTime ++
            " restTimes:" ++ show restTimes ++
            " answer:" ++ show answer
            ) False = undefined
-}
    | diff < 0 = Nothing  {- notice that we can "optimize"
                           - this by verifying (< 0) in solve -}
    | otherwise = (create_answer (diff - (answer - minTime)) restTimes) >>=
                        \a -> Just (answer : a)
                  where answer = min maxTime (minTime + diff)

solve (sumTime, times) =
    create_answer diff times
    where diff = sumTime - (sum (map fst times))

verify' :: (Num a, Ord a) => (a, [(a, a)]) -> [a] -> Bool
verify' (0, []) [] = True
verify' (sumTime, ts) as
    | sumTime < 0 || null ts || null as = False
verify' (sumTime, ts@((minTime, maxTime):restTimes)) as@(answer:restAnswers)
    | answer < minTime || answer > maxTime = False
    | otherwise = verify' (sumTime - answer, restTimes) restAnswers

verify problem = show problem ++ ": " ++
                 if isNothing answer then " has no answer\n"
                 else if verify' problem (fromJust answer) then show (fromJust answer) ++ "\n"
                      else " BAD ANSWER!\n"
                 where answer = solve problem

problems =
    [
    (5, [(1,1), (2,2), (0,10), (1,1)]),
    (5, [(0,1), (0,2), (0,2), (0,1)]),
    (5, [(0,1), (0,2), (0,3), (0,1)]),
    (5, [(0,0), (0,0), (0,3), (0,0)]),
    (5, [(1,1), (0,0), (0,3), (0,0)]),
    (0, [(0,1), (0,0), (0,3), (0,0)]),
    (0, [(0,0), (0,0), (0,0), (0,0)]),
    (0, [(0,0)]),
    (1, [(0,1)]),
    (2, [(0,4)]),
    (5, [(1,1), (1,2), (1,3), (1,1)]),
    (50, [(10,10), (10,20), (10,30), (10,10)]),
    (6, [(2,3), (1,2), (0,1), (1,2)])]

testsuite [] = ""
testsuite (x:xs) = verify x ++ testsuite xs

showAnswer' [] = "\n"
showAnswer' (x:xs) = show x ++ " " ++ showAnswer' xs

showAnswer Nothing = "NO\n"
showAnswer (Just x) = "YES\n" ++ showAnswer' x

getPair :: (Read a, Read b) => [String] -> (a, b)
getPair (x:y:[])
--    | trace (show x ++ "," ++ show y) False = undefined
    | otherwise = (read x, read y)
getPair _ = undefined

getTimes 0 = return []
getTimes n = do
    inputLine <- getLine
    rest <- getTimes (n - 1)
    return ((getPair (words inputLine)) : rest)

main = do
    inputLine <- getLine
    times <- getTimes (nrTimes inputLine)
    putStr $ (showAnswer.solve) (sumTime inputLine, times)
    where sumTime = (read.head.tail.words)
          nrTimes = (read.head.words)

import Debug.Trace
import Data.List

parse :: String -> (Int, Int, [(Int, Int)])
parse l =
  let
    ([x, y]:rest) = map (map read) . map words $ lines l
  in
    (x, y, map (\[x,y] -> (x,y)) rest)

solve :: (Int, Int, [(Int, Int)]) -> Maybe [Int]
solve (_, summ, days) =
  if summ >= minSum && summ <= maxSum
  then Just . snd $ mapAccumL f (summ - minSum) days
  else Nothing
  where
    f 0 (d, _) = (0, d)
    f summ (mn, mx)
--      | trace  (unwords [">", show summ, show mn, show mx]) False = undefined
      | summ > mx - mn = (summ - mx + mn, mx)
      | otherwise      = (0, mn + summ)
    minSum = sum . map fst $ days
    maxSum = sum . map snd $ days

present Nothing = "NO"
present (Just res) = unlines ["YES", unwords . map show $ res]

main = interact $ present . solve . parse

import Data.List
main = interact $ f.map (map read.words).lines

f ([_,pam]:xs) =
	let minn = sum $ map head xs in
	let maxx = sum $ map last xs in
	if maxx >= pam && minn <= pam
	then showResult $ g (maxx - pam) xs
	else "NO"

g _ [] = []
g diff xs
	| diff == 0 = two xs : g 0 (tail xs)
	| otherwise = let minn = min diff (two xs - one xs) in (two xs - minn) : g (diff - minn) (tail xs)
	where
	one x = head $ head x
	two x = last $ head x

showResult xs = "YES\n" ++ intercalate " " (map show xs)

import Data.List (transpose, unfoldr)

solve :: [Int] -> String
solve (_ : s : xs) = if lb <= s && s <= ub then "YES\n" ++ unwords (map show ys) else "NO"
  where
    chunks n = takeWhile (not . null) . unfoldr (Just . splitAt n)
    [lbs, ubs] = transpose $ chunks 2 xs
    [lb, ub] = map sum [lbs, ubs]
    ys = zipWith (+) lbs $ replicate (s-lb) 1 ++ repeat 0

main :: IO ()
main = interact $ solve . map read . words

{-# LANGUAGE ScopedTypeVariables,TupleSections #-}
import Control.Monad
data State s a = State {runState :: s->(a,s)}
instance Monad (State s) where
        return = State . (,)
        (State f1) >>= f2 = State $ uncurry (runState . f2) . f1
        (State f1) >> (State f2) = State $ f2 .snd . f1

repeatM a = mapM (const a) (repeat 1)
repeatMn a n = mapM (const a) [1..n]
readm::(Read a) => State String a
readm = State (head . reads)
readchar = State (\s->(head s,tail s))
csum  = foldr (\x y -> (x + head y) : y) [0]

runRead x s = fst $ runState x s

solve _ _ 0 = []
solve ls l s = x : solve (tail ls) (tail l) (s-x) where
	(smin,smax) = head ls
	(dmin,dmax) = head l
	x = if (s-dmin <= smax) then dmin else (s-smax)

main = reader >>= writer . solver
reader = getContents
writer = putStr
solver = runRead $ do
	d<-readm
	sumTime<-readm
	times::[(Int,Int)] <- mapM (const (liftM2 (,) readm readm)) [1..d]
	let smin = csum . map fst $ times
	let smax = csum . map snd $ times
	let stimes = zip smin smax
	let solution =(solve (tail stimes) times sumTime)
	return (if sumTime >= (fst.head $ stimes) && sumTime <= (snd.head $ stimes) then ("YES\n"++ (unwords . map show $  solution)) else "NO")

import Data.List

readPairInt :: String -> (Int, Int)
readPairInt xs = ((read pre)::Int, (read suf)::Int)
    where (pre, suf) = break (== ' ') xs

listAll [] = [[]]
listAll xss = [x:y | x <- (head xss), y <- (listAll (tail xss))]

mySolver :: Int -> [Int] -> [Int] -> [Int]
mySolver 0 _ _ = []
mySolver curSum minList maxsumList = thisDay : (mySolver (curSum - thisDay) (tail minList) (tail maxsumList))
    where thisDay = max (curSum - (head (tail maxsumList))) (head minList)

myFunction :: String -> String
myFunction input = if (sumHours < minHours || sumHours > maxHours)
                   then "NO\n"
                   else "YES\n" ++ aSolution ++ "\n"
    where inputLines = lines input
          (days, sumHours) = readPairInt (head inputLines)
          hourLimits = map readPairInt (tail inputLines)
          minsumList = scanr (+) 0 $ map fst hourLimits
          maxsumList = scanr (+) 0 $ map snd hourLimits
          minHours = head minsumList
          maxHours = head maxsumList
          aSolution' = mySolver sumHours (map fst hourLimits) maxsumList
          aSolution = unwords $ map show $ aSolution'

main = interact $ myFunction

import Control.Monad (replicateM)
import Prelude hiding (reads)

reads :: IO (Int, Int)
reads  =  do
    [x, y]  <-  getLine >>= return . map read . words
    return (x, y)

solve :: Int -> [(Int, Int)] -> Maybe [Int]
solve t xs
  | mn > t || t > mx  =  Nothing
  | otherwise  =  Just $ mn : (solve' (t - mn) xs)
  where
    mn  =  sum $ map fst xs
    mx  =  sum $ map snd xs
    solve' 0 xs  =  map fst xs
    solve' n []  =  undefined
    solve' n ((a,b):xs)
      | b - a >= n  =  (a + n) : (solve' 0 xs)
      | otherwise  =  b : (solve' (n - (b-a)) xs)

printAns :: Maybe [Int] -> IO ()
printAns Nothing  =  putStrLn "NO"
printAns (Just xs)  =  putStrLn "YES" >> prints xs
  where
    prints [x]  =  print x
    prints (x:xs)  =  putStr (show x ++ " ") >> prints xs

main :: IO ()
main  =  do
    (n, t)  <-  reads
    as  <-  replicateM n reads
    printAns $ solve t as

import Control.Monad (replicateM)
import Prelude hiding (reads)

reads :: IO (Int, Int)
reads  =  do
    [x, y]  <-  getLine >>= return . map read . words
    return (x, y)

solve :: Int -> [(Int, Int)] -> Maybe [Int]
solve t xs
  | mn > t || t > mx  =  Nothing
  | otherwise  =  Just $ solve' (t - mn) xs
  where
    mn  =  sum $ map fst xs
    mx  =  sum $ map snd xs
    solve' 0 xs  =  map fst xs
    solve' n []  =  undefined
    solve' n ((a,b):xs)
      | b - a >= n  =  a + n : (solve' 0 xs)
      | otherwise  =  b : (solve' (n-b) xs)

printAns :: Maybe [Int] -> IO ()
printAns Nothing  =  putStrLn "NO"
printAns (Just xs)  =  putStrLn "YES" >> prints xs
  where
    prints [x]  =  print x
    prints (x:xs)  =  putStr (show x ++ " ") >> prints xs

main :: IO ()
main  =  do
    (n, t)  <-  reads
    as  <-  replicateM n reads
    printAns $ solve t as

import Control.Applicative
import Data.Array
import Data.List

readInts :: String -> [Int]
readInts = fmap read . words

solve :: [[Int]] -> String
solve ([days, sumTime] : xss)
  | y `inRange` sumTime = "YES\n" ++ concat (intersperse " " answer)
  | otherwise           = "NO"
 where y : ys = fmap conv . reverse $ scanl1 (zipWith (+)) (take days xss)
        where conv [a, b] = (a, b)
       answer = snd $ mapAccumL f sumTime (snd (unzip ys) ++ [0])
        where f n z | n <= z    = (n, "0")
                    | otherwise = let x = n - z in (z, show x)

main = interact $ solve . fmap readInts . lines

import Control.Applicative
import Data.Array
import Data.List

readInts :: String -> [Int]
readInts = fmap read . words

solve :: [[Int]] -> String
solve ([days, sumTime] : xss)
  | y `inRange` sumTime = "YES\n" ++ concat (intersperse " " answer)
  | otherwise           = "NO"
 where y : ys = fmap conv . reverse $ scanl1 (zipWith (+)) (take days xss)
        where conv [a, b] = (a, b)
       answer = reverse . snd $ mapAccumL f sumTime (snd (unzip ys) ++ [0])
        where f n z | n <= z    = (n, "0")
                    | otherwise = let x = n - z in (z, show x)

main = interact $ solve . fmap readInts . lines

test1 = solve [[1, 48], [5, 7]]
test2 = solve [[2, 5], [0, 1], [3, 5]]
test3 = solve [[3, 10], [2, 2], [2, 4], [4, 5]]
test4 = solve [[5, 16], [2, 2], [2, 4], [4, 5], [1, 2], [1, 2]]
test5 = solve [[5, 3], [0, 2], [0, 4], [0, 5], [0, 2], [0, 2]]

import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.ST
import Data.List

readInts :: String -> [Int]
readInts = fmap read . words

solve :: [[Int]] -> String
solve ([days, sumTime] : xs) = runST $ do
  let hours = days * 8
  a <- newArray ((0, 0), (days, hours)) maxBound :: ST s (STArray s (Int, Int) Int)
  writeArray a (0, 0) 0
  forM_ (zip [1..] (take days xs)) $ \(i, hs) -> do
    forM_ hs $ \h -> do
      forM_ [0 .. hours] $ \j -> do
        ok <- (/= maxBound) <$> readArray a (i - 1, j)
        when ok $ do
          let j' = j + h
          when ((0, hours) `inRange` j') $ do
            j'' <- readArray a (i, j')
            writeArray a (i, j') (min j j'')
  if sumTime > hours
    then return "NO"
    else do
      ok <- (/= maxBound) <$> readArray a (days, sumTime)
      if ok
        then do
          xs@(x : _) <- reverse <$> answer a days sumTime
          let ys = zipWith subtract xs (tail xs)
          let zs = x : ys
          return $ "YES\n" ++ concat (intersperse " " (show <$> zs))
        else return "NO"
 where
  answer _ 0 _ = return []
  answer a i j = do
    j' <- readArray a (i, j)
    (j :) <$> answer a (i - 1) j'

main = interact $ solve . fmap readInts . lines

test1 = solve [[1, 48], [5, 7]]
test2 = solve [[2, 5], [0, 1], [3, 5]]
test3 = solve [[3, 10], [2, 2], [2, 4], [4, 5]]
test4 = solve [[5, 16], [2, 2], [2, 4], [4, 5], [1, 2], [1, 2]]

module Main where

import Control.Monad (replicateM)
import Data.List (mapAccumL)

data DayLimits = DayLimits {
    minTime :: !Int,
    extraTime :: !Int
  } deriving (Show)

main :: IO ()
main = do
  [d, sum] <- readInts
  limits <- replicateM d readLimits
  case schedule sum limits of
    Nothing -> putStrLn "NO"
    Just t -> do
      putStrLn "YES"
      putStrLn $ unwords (map show t)

schedule :: Int -> [DayLimits] -> Maybe [Int]
schedule sumTime limits
    | sumTime < minTotalTime && remTime /= 0 = Nothing
    | otherwise                               = Just scheduledTime
  where
    minTotalTime = sum $ map minTime limits
    reduceTime rem limit = let used = min rem (extraTime limit) in (rem - used, used + minTime limit)
    (remTime, scheduledTime) = mapAccumL reduceTime (sumTime - minTotalTime) limits

-- schedule 0   []            = Just []
-- schedule sum _  | sum < 0  = Nothing
-- schedule _   []            = Nothing
-- schedule sum (d:rest) = asum $ map tryTime [minTime d .. maxTime d]
--   where
--     tryTime t = (:) t <$> schedule (sum - t) rest

readInts :: IO [Int]
readInts = map read . words <$> getLine

readLimits :: IO DayLimits
readLimits = do
  [minL, maxL] <- readInts
  pure $ DayLimits minL (maxL - minL)

module Main where

import Control.Monad (replicateM)
import Data.List (mapAccumL)

data DayLimits = DayLimits {
    minTime :: !Int,
    extraTime :: !Int
  } deriving (Show)

main :: IO ()
main = do
  [d, sum] <- readInts
  limits <- replicateM d readLimits
  case schedule sum limits of
    Nothing -> putStrLn "NO"
    Just t -> do
      putStrLn "YES"
      putStrLn $ unwords (map show t)

schedule :: Int -> [DayLimits] -> Maybe [Int]
schedule sumTime limits
    | remTime == 0 = Just scheduledTime
    | otherwise    = Nothing
  where
    minTotalTime = sum $ map minTime limits
    reduceTime rem limit = let used = min rem (extraTime limit) in (rem - used, used + minTime limit)
    (remTime, scheduledTime) = mapAccumL reduceTime (sumTime - minTotalTime) limits

-- schedule 0   []            = Just []
-- schedule sum _  | sum < 0  = Nothing
-- schedule _   []            = Nothing
-- schedule sum (d:rest) = asum $ map tryTime [minTime d .. maxTime d]
--   where
--     tryTime t = (:) t <$> schedule (sum - t) rest

readInts :: IO [Int]
readInts = map read . words <$> getLine

readLimits :: IO DayLimits
readLimits = do
  [minL, maxL] <- readInts
  pure $ DayLimits minL (maxL - minL)

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Data.List

class Scan a where scan' :: String -> a
instance Scan Int where scan' n = read n
instance Scan Char where scan' (x:_) = x
instance Scan Float where scan' f = read f
instance Scan Double where scan' d = read d
instance Scan Integer where scan' n = read n
instance Scan String where scan' x = x
instance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)
                                                 where
                                                   scan'' (x:y:_) = (scan' x,scan' y)
instance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)
                                                          where
                                                            scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)
instance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)
                                                                   where
                                                                     scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)
instance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)
                                                                            where
                                                                              scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)
class Ans a where showans :: a -> String
instance Ans Int where showans x = show x
instance Ans Char where showans x = [x]
instance Ans Float where showans x = show x
instance Ans Double where showans x = show x
instance Ans Integer where showans x = show x
instance Ans String where showans x = x
instance (Ans a, Ans b) => Ans (a,b) where
    showans (x,y) = showans x ++ " " ++ showans y
instance (Ans a, Ans b,Ans c) => Ans (a,b,c) where
    showans (x,y,z) = showans x ++ " " ++ showans y ++ " " ++ showans z

scan :: (Scan a) => IO a
scan = do n <- getLine
          return (scan' n)

scans :: (Scan a) => Int -> IO [a]
scans 0 = return []
scans n = do x <- scan
             xs <- scans (n-1)
             return (x:xs)

scanlist :: (Scan a) => IO [a]
scanlist = do l <- getLine
              return [scan' x|x<-words l]

scanlists :: (Scan a) => Int -> IO [[a]]
scanlists 0 = return []
scanlists n = do x <- scanlist :: (Scan a) => IO [a]
                 xs <- scanlists (n-1)
                 return (x:xs)

putAnsLn :: (Ans a) => a -> IO ()
putAnsLn ans = putStrLn (showans ans)

putAnsLns :: (Ans a) => [a] -> IO ()
putAnsLns (x:xs) = do putAnsLn x
                      putAnsLns xs
putAnsLns [] = return ()

conv :: Int -> [Int] -> [Int] -> String
conv d mins l = let len = d-(length l) in
                (unwords.reverse) (map show (zipWith (+) mins (l++(replicate len 0))))

solve _ _ _ [] _ = ["NO"]
solve d sumtime mins (m:ms) l = if sumtime <= m then
                                    ("YES":[(conv d mins (sumtime:l))])
                                else
                                    solve d (sumtime-m) mins ms (m:l)

solve' d sumtime [] mins newshd = if sumtime<0 then ["NO"] else solve d sumtime mins newshd []
solve' d sumtime ((min_,max_):ss) mins newshd = solve' d (sumtime-min_) ss (min_:mins) ((max_-min_):newshd)

main = do (d,sumtime) <- scan :: IO (Int,Int)
          shd <- scans d :: IO [(Int,Int)]
          putAnsLns (solve' d sumtime shd [] [])

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Data.List

class Scan a where scan' :: String -> a
instance Scan Int where scan' n = read n
instance Scan Char where scan' (x:_) = x
instance Scan Float where scan' f = read f
instance Scan Double where scan' d = read d
instance Scan Integer where scan' n = read n
instance Scan String where scan' x = x
instance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)
                                                 where
                                                   scan'' (x:y:_) = (scan' x,scan' y)
instance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)
                                                          where
                                                            scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)
instance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)
                                                                   where
                                                                     scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)
instance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)
                                                                            where
                                                                              scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)
class Ans a where showans :: a -> String
instance Ans Int where showans x = show x
instance Ans Char where showans x = [x]
instance Ans Float where showans x = show x
instance Ans Double where showans x = show x
instance Ans Integer where showans x = show x
instance Ans String where showans x = x
instance (Ans a, Ans b) => Ans (a,b) where
    showans (x,y) = showans x ++ " " ++ showans y
instance (Ans a, Ans b,Ans c) => Ans (a,b,c) where
    showans (x,y,z) = showans x ++ " " ++ showans y ++ " " ++ showans z

scan :: (Scan a) => IO a
scan = do n <- getLine
          return (scan' n)

scans :: (Scan a) => Int -> IO [a]
scans 0 = return []
scans n = do x <- scan
             xs <- scans (n-1)
             return (x:xs)

scanlist :: (Scan a) => IO [a]
scanlist = do l <- getLine
              return [scan' x|x<-words l]

scanlists :: (Scan a) => Int -> IO [[a]]
scanlists 0 = return []
scanlists n = do x <- scanlist :: (Scan a) => IO [a]
                 xs <- scanlists (n-1)
                 return (x:xs)

putAnsLn :: (Ans a) => a -> IO ()
putAnsLn ans = putStrLn (showans ans)

putAnsLns :: (Ans a) => [a] -> IO ()
putAnsLns (x:xs) = do putAnsLn x
                      putAnsLns xs
putAnsLns [] = return ()

conv :: Int -> [Int] -> [Int] -> String
conv d mins l = let len = d-(length l) in
                (unwords) (map show (zipWith (+) mins (l++(replicate len 0))))

solve _ _ _ [] _ = ["NO"]
solve d sumtime mins (m:ms) l = if sumtime <= m then
                                    ("YES":[(conv d mins (sumtime:l))])
                                else
                                    solve d (sumtime-m) mins ms (m:l)

solve' d sumtime [] mins newshd = if sumtime<0 then ["NO"] else solve d sumtime (reverse mins) (reverse newshd) []
solve' d sumtime ((min_,max_):ss) mins newshd = solve' d (sumtime-min_) ss (min_:mins) ((max_-min_):newshd)

main = do (d,sumtime) <- scan :: IO (Int,Int)
          shd <- scans d :: IO [(Int,Int)]
          putAnsLns (solve' d sumtime shd [] [])

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Data.List

class Scan a where scan' :: String -> a
instance Scan Int where scan' n = read n
instance Scan Char where scan' (x:_) = x
instance Scan Float where scan' f = read f
instance Scan Double where scan' d = read d
instance Scan Integer where scan' n = read n
instance Scan String where scan' x = x
instance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)
                                                 where
                                                   scan'' (x:y:_) = (scan' x,scan' y)
instance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)
                                                          where
                                                            scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)
instance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)
                                                                   where
                                                                     scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)
instance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)
                                                                            where
                                                                              scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)
class Ans a where showans :: a -> String
instance Ans Int where showans x = show x
instance Ans Char where showans x = [x]
instance Ans Float where showans x = show x
instance Ans Double where showans x = show x
instance Ans Integer where showans x = show x
instance Ans String where showans x = x
instance (Ans a, Ans b) => Ans (a,b) where
    showans (x,y) = showans x ++ " " ++ showans y
instance (Ans a, Ans b,Ans c) => Ans (a,b,c) where
    showans (x,y,z) = showans x ++ " " ++ showans y ++ " " ++ showans z

scan :: (Scan a) => IO a
scan = do n <- getLine
          return (scan' n)

scans :: (Scan a) => Int -> IO [a]
scans 0 = return []
scans n = do x <- scan
             xs <- scans (n-1)
             return (x:xs)

scanlist :: (Scan a) => IO [a]
scanlist = do l <- getLine
              return [scan' x|x<-words l]

scanlists :: (Scan a) => Int -> IO [[a]]
scanlists 0 = return []
scanlists n = do x <- scanlist :: (Scan a) => IO [a]
                 xs <- scanlists (n-1)
                 return (x:xs)

putAnsLn :: (Ans a) => a -> IO ()
putAnsLn ans = putStrLn (showans ans)

putAnsLns :: (Ans a) => [a] -> IO ()
putAnsLns (x:xs) = do putAnsLn x
                      putAnsLns xs
putAnsLns [] = return ()

conv :: Int -> [Int] -> [Int] -> String
conv d mins l = let len = d-(length l) in
                (unwords.reverse) (map show (zipWith (+) mins ((replicate len 0)++l)))

solve _ _ _ [] _ = ["NO"]
solve d sumtime mins (m:ms) l = if sumtime <= m then
                                    ("YES":[(conv d mins (sumtime:l))])
                                else
                                    solve d (sumtime-m) mins ms (m:l)

solve' d sumtime [] mins newshd = if sumtime<0 then ["NO"] else solve d sumtime mins newshd []
solve' d sumtime ((min_,max_):ss) mins newshd = solve' d (sumtime-min_) ss (min_:mins) ((max_-min_):newshd)

main = do (d,sumtime) <- scan :: IO (Int,Int)
          shd <- scans d :: IO [(Int,Int)]
          putAnsLns (solve' d sumtime shd [] [])


We consider a positive integer perfect, if and only if the sum of its digits is exactly $$$10$$$. Given a positive integer $$$k$$$, your task is to find the $$$k$$$-th smallest perfect positive integer.

A single line with a positive integer $$$k$$$ ($$$1 \leq k \leq 10\,000$$$).

A single number, denoting the $$$k$$$-th smallest perfect integer.

NoteThe first perfect integer is $$$19$$$ and the second one is $$$28$$$.

import Data.List

f2::(Int,Int)->(Int,Int)
f2 (a,b)=(a,b)

f::Int->(Int,Int)->[Int]
f k (sum,num)
     |sum>10 || k>8=[]
     |otherwise=let k1=k+1
                    num1=num*10
                in if sum==10 then num:f k1 (sum,num1)
                              else concat (map (f k1) (zip [sum..(sum+9)] [num1..(num1+9)]))

main=do
     e1<-getLine
     let k=read e1::Int
     print $ (nub (sort (concat(map (f 1) (zip [1..9] [1..9])))))!!(k-1)

--
-- Michael V. Antosha
-- 2019
-- Michael.Antosha@gmail.com
-- m.antosha@samsung.com
--
-- Haskell practice.
-- Competitive programming.
--
-- Codeforces Round #460 (Div. 2)
--
-- B. Perfect Number
-- http://codeforces.com/contest/919/problem/B
--

import Prelude

-- import Debug.Trace (trace)

main :: IO ()
main = interact $ ($ "\n") . shows . getByInd . read

data Generator num = St { lastNum :: num }

getByInd :: Int -> Int
getByInd = gbi iniGen  where

  iniGen = St {lastNum=0}  -- the initial state of the generator

  gbi gen 0 = lastNum gen
  gbi gen cnt = gbi (nextPN gen) (cnt - 1)

  -- nextPN state | trace ("nextPN: lastNum="++show (lastNum state)++".") False = undefined
  nextPN state = loop (nextState state)
    where

    loop st = stopIf (isPerfect . lastNum $ st) st

    -- stopIf cond st | trace ("\t"++"stopIf: cond="++show cond++" lastNum="++show (lastNum st)++".") False = undefined
    stopIf True st = st
    stopIf False st = loop (nextState st)

  nextState st = St {lastNum = 1 + (lastNum st)}  -- debug

  isPerfect = (== 10) . digSum

  digSum 0 = 0  -- used explicitly (for recursion only)
  digSum n = digit + digSum rest
    where
    (rest, digit) = n `divMod` 10

--
-- Michael V. Antosha
-- 2019
-- Michael.Antosha@gmail.com
--
-- Haskell practice.
-- Competitive programming.
--
-- Codeforces Round #460 (Div. 2)
--
-- B. Perfect Number
-- http://codeforces.com/contest/919/problem/B
--

import Prelude ((+), (-), divMod)

import Data.Eq ((==))
import Data.Function (($), (.))
import Data.Int (Int)
import Data.List ((!!), filter)
import System.IO (IO, interact)
import Text.Read (read)
import Text.Show (shows)

main :: IO ()
main = interact $ showAnswer . getKth . read
  where
    showAnswer = ($ "\n") . shows

getKth :: Int -> Int
getKth k = perfNums !! (k-1)
  where
    perfNums = filter isPerfect [1..]

    isPerfect = (== 10) . digSum

    digSum 0 = 0
    digSum n = dig + digSum rest
      where
        (rest, dig) = n `divMod` 10

--
-- Michael V. Antosha
-- 2019
-- Michael.Antosha@gmail.com
-- m.antosha@samsung.com
--
-- Haskell practice.
-- Competitive programming.
--
-- Codeforces Round #460 (Div. 2)
--
-- B. Perfect Number
-- http://codeforces.com/contest/919/problem/B
--

import Prelude
-- (TODO) make it minimal (-ddump-minimal-imports)

main :: IO ()
main = interact $ ($ "\n") . shows . getByInd . read

getByInd :: Int -> Int
getByInd = f  where

  g i c | isPerf c  = c
        | otherwise = g i (next c)

  f 0 = 0
  f i = g i (next $ f (i-1))

  next c = c+1
  -- (TODO) try to make it faster by generating queue of candidates, we do not need to check EVERY number

  isPerf n = (10 == digSum n)

  digSum 0 = 0
  digSum n = digit + (digSum rest)  where
    (rest, digit) = n `divMod` 10

import Data.Char
import Control.Monad
perfects :: [[Int]]
perfects = filter ((/= 0) . head) $ concatMap (sumLength 10) [1..] where
  sumLength :: Int -> Int -> [[Int]]
  sumLength i 1 = guard (i >= 0) *> pure [i]
  sumLength i w = concat [ map (f:) (sumLength (i-f) (w-1)) | f <- [0..9] ]
main = interact $ map intToDigit . (perfects !!) . read

import Data.Char

main = readLn >>= print . solve

solve k = head $ drop (k - 1) [n | n <- [19..], check n 0]
  where check n m
          | 10 < m = False
          | n == 0 = m == 10
          | otherwise = check (n `div` 10) (m + n `mod` 10)

{-# OPTIONS_GHC -O2 #-}
import           Data.Char
main=readLn>>=print.f
f :: Int -> Int
f k=[x|x<-[1..],sum(map digitToInt(show x))==10]!!(k-1)

{-# OPTIONS_GHC -O2 #-}
import           Data.Char
main=readLn>>=print.f
f k
  |k<=8000=[x|x<-[1..],sum(map digitToInt(show x))==10]!!(k-1)
  |otherwise=[x|x<-[9010000..],sum(map digitToInt(show x))==10]!!(k-8000)

import Data.Char
import Data.List

listOfAllPossible = iterate (\l -> [sum . take i . drop (i - 10) $ l | i <- [1..11]]) [1,0,0,0,0,0,0,0,0,0,0]

buildNumber' :: [[Int]] -> Int -> Int -> String
buildNumber' _ _ 0 = "19"
buildNumber' a b c = buildNumber a b c

buildNumber :: [[Int]] -> Int -> Int -> String
buildNumber (x:[]) reqSum _ = [intToDigit reqSum]
buildNumber (x:xs) reqSum 0 = '0' : buildNumber xs reqSum 0
buildNumber (x:xs) reqSum n = intToDigit y : buildNumber xs (reqSum - y) (n - z)
  where Just y = findIndex (> n + k) . drop (10 - reqSum) $ x
        k = if reqSum == 10 then 0 else x!!(9 - reqSum)
        z = if y == 0 then 0 else x!!(y + 9 - reqSum) - k

main = do
  n <- fmap (flip (-) 1) readLn
  let l = map (scanl1 (+)) . map reverse . reverse $ takeWhile (\x -> x!!10 < 50000) listOfAllPossible
  putStrLn . dropWhile (== '0') . buildNumber' l 10 $ n

--
-- Michael V. Antosha
-- 2019
-- Michael.Antosha@gmail.com
-- m.antosha@samsung.com
--
-- Haskell practice.
-- Competitive programming.
--
-- Codeforces Round #460 (Div. 2)
--
-- B. Perfect Number
-- http://codeforces.com/contest/919/problem/B
--

main :: IO ()
main = interact $ flip shows "\n" . getByInd . const 9000000 . (read :: String -> Int)

data Gen = St { getNum :: Int }

getByInd :: Int -> Int
getByInd = gbi iniState
  where
    gbi st 0 = getNum st
    gbi st cnt = (gbi $! nextPN st) (cnt - 1)

    iniState = St (-1)

    nextPN st = St $! ((getNum st) + 1)

{--

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs
run-hs: ./hs.exec
	printf '%s\n' 10000 | /usr/bin/time -v ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '10800100'; }
	printf '%s\n' 1 | ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '19'; }
	printf '%s\n' 2 | ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '28'; }
	printf '%s\n' 3 | ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '37'; }
	printf '%s\n' 4 | ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '46'; }
	printf '%s\n' 5 | ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '55'; }
	printf '%s\n' 6 | ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '64'; }
	printf '%s\n' 7 | ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '73'; }
	printf '%s\n' 8 | ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '82'; }
	printf '%s\n' 9 | ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '91'; }
	printf '%s\n' 10 | ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '109'; }
	printf '%s\n' 11 | ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '118'; }
	printf '%s\n' 12 | ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '127'; }
	printf '%s\n' 100 | time ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '1423'; }
	printf '%s\n' 101 | time ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '1432'; }
	printf '%s\n' 1000 | time ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '100036'; }
	printf '%s\n' 10000 | time ./hs.exec | { x="$$(cat)"; echo "$$x"; test "$$x" = '10800100'; }
run-cpp: ./a.out
	printf '%s\n' 1 | ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '19'; }
	printf '%s\n' 2 | ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '28'; }
	printf '%s\n' 3 | ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '37'; }
	printf '%s\n' 4 | ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '46'; }
	printf '%s\n' 5 | ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '55'; }
	printf '%s\n' 6 | ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '64'; }
	printf '%s\n' 7 | ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '73'; }
	printf '%s\n' 8 | ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '82'; }
	printf '%s\n' 9 | ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '91'; }
	printf '%s\n' 10 | ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '109'; }
	printf '%s\n' 11 | ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '118'; }
	printf '%s\n' 12 | ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '127'; }
	printf '%s\n' 100 | time ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '1423'; }
	printf '%s\n' 101 | time ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '1432'; }
	printf '%s\n' 1000 | time ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '100036'; }
	printf '%s\n' 10000 | time ./a.out | { x="$$(cat)"; echo "$$x"; test "$$x" = '10800100'; }

./hs.exec: *.hs
	# ghc -rtsopts=none -Wall -Wextra -Werror -O2 -o '$@' $+
	# ghc -rtsopts=none -Wall -Wextra -O2 -o '$@' $+
	# ghc -rtsopts=none -Wall -Wextra -O2 -fbreak-on-error -o '$@' $+
	ghc -rtsopts=none -Wall -fbreak-on-error -o '$@' $+
	ghc -rtsopts=none -Wall -O2 -o '$@' $+

./a.out: *.cpp
	g++ -D'MIVAEL_DEBUG' -Wall -Wextra -std=c++11 -pedantic -Werror $+
	#g++ -Wall -Wextra -std=c++98 -pedantic -Werror -O3 $+

--}

import qualified Data.Set as S

main :: IO ()
main =
  do
    let l = [1,1,2,2,3,3]
    let s = S.fromList l
    putStrLn $ show s


The only difference between easy and hard versions is constraints.The BerTV channel every day broadcasts one episode of one of the $$$k$$$ TV shows. You know the schedule for the next $$$n$$$ days: a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show, the episode of which will be shown in $$$i$$$-th day.The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $$$d$$$ ($$$1 \le d \le n$$$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $$$d$$$ consecutive days in which all episodes belong to the purchased shows.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test case descriptions follow. The first line of each test case contains three integers $$$n, k$$$ and $$$d$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 100$$$, $$$1 \le d \le n$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show that is broadcasted on the $$$i$$$-th day. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$100$$$.

Print $$$t$$$ integers — the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for $$$d$$$ consecutive days. Please note that it is permissible that you will be able to watch more than $$$d$$$ days in a row.

NoteIn the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription on show $$$1$$$ and on show $$$2$$$. So the answer is two.In the second test case, you can buy a subscription to any show because for each show you can find a segment of three consecutive days, consisting only of episodes of this show.In the third test case in the unique segment of four days, you have four different shows, so you need to buy a subscription to all these four shows.In the fourth test case, you can buy subscriptions to shows $$$3,5,7,8,9$$$, and you will be able to watch shows for the last eight days.

import Data.List
import Data.Maybe
import Control.Monad
import Control.Arrow

unique = map head . group . sort

main = do
  t <- readLn
  replicateM_ t $ do
    [_, _, d] <- map read . words <$> getLine
    ary <- map read . words <$> getLine

    let a = map (head &&& length) . group $ ary
    let r = minimum $ map length $ mapMaybe (itms d) (tails a)

    print r

itms :: Int -> [(Int, Int)] -> Maybe [Int]
itms _   [] = Nothing
itms req (h:hs)
  | req <= snd h  = Just [fst h]
  | otherwise     = (\i -> unique $ fst h:i) <$> itms (req - snd h) hs

import Control.Monad
import Data.List

main :: IO()
main = do
  t <- readLn
  replicateM_ t $ (>>= putStrLn) doQuery

doQuery :: IO(String)
doQuery = do
  [n, k, d] <- (map read . words <$> getLine) :: IO([Int])
  a <- (map read . words <$> getLine) :: IO([Int])
  b <- return [take d $ drop i a | i <- [0..n-d]]
  return $ show $ minimum $ map (length . nub) b

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST
import Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)
import qualified Control.Monad.ST.Lazy as STL
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.STRef
import Data.IORef
import Data.Function
import System.IO
import System.Exit
import Data.Char

main :: IO ()
main = do
  t <- readInt <$> getLine
  replicateM_ t $ do
    [n,k,d] <- map readInt . words <$> getLine
    as <- unfoldr (runStateT rIntS) <$> BS.getLine
    print $ query n d $ A.listArray (0,n-1) as

query :: Int -> Int -> UArray Int Int -> Int
query n d arr = (\ (!store,!now,!minimal) -> minimal)
  $ foldl'
     (\ (!storePrev,!prev,!minimal) !i ->
      let (Just !resRemv, !store1)
            = IM.updateLookupWithKey
              (\_ v -> if v > 1 then Just $! (v-1) else Nothing)
              (arr A.! i) storePrev
          (resAdd, !storeNow)
            = IM.insertLookupWithKey
              (const (+)) (arr A.! (i+d)) 1 store1
          !now = prev - (if resRemv > 1 then 0 else 1)
                      + (maybe 1 (const 0) resAdd)
          !newMin = minimal `min` now
       in (storeNow,now,newMin))
     (initialMap,initialSize,initialSize) [0..n-d-1]
  where
    initialMap = IM.fromListWith (+) $ [(arr A.! i,1::Int) | i <- [0..d-1]]
    initialSize = IM.size initialMap

#define IL(f) {-# INLINE f #-}; f

rInt :: StateT BSL.ByteString Maybe Int
IL(rInt) = StateT $ BSL.readInt . BSL.dropWhile (<'!')
rIntS :: StateT BS.ByteString Maybe Int
IL(rIntS) = StateT $ BS.readInt . BS.dropWhile (<'!')

-- unlessM, whenM :: (Monad m) => m Bool -> m () -> m ()
IL(whenM) = (. flip when) . (>>=)
IL(unlessM) = (. flip unless) . (>>=)

IL(wrA) = A.writeArray
IL(rdA) = A.readArray
IL(mdA) = \arr f !i -> do
  ai <- rdA arr i
  let fai = f ai
  wrA arr i fai
  return (ai,fai)
{-# INLINE mdA' #-}
mdA' = \arr f !i -> do
  !ai <- rdA arr i
  let !fai = f ai
  wrA arr i fai
  return (ai,fai)
IL(swapA) = \arr !i !j -> do
  ai <- rdA arr i
  wrA arr i =<< rdA arr j
  wrA arr j ai

#define D(f,r,d)\
  IL(f) :: Integral a=>a->d; f=fromIntegral;\
  IL(r) :: String->d; r=read
#define C(f,r,g,h,d) D(f,r,d);\
  g,h :: RealFrac a=>a->d; IL(g)=floor; IL(h)=ceiling
C(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)
C(toInt,readInt,floorInt,ceilInt,Int)
C(toI8,readI8,floorI8,ceilI8,Int8)
C(toI16,readI16,floorI16,ceilI16,Int16)
C(toI32,readI32,floorI32,ceilI32,Int32)
C(toI64,readI64,floorI64,ceilI64,Int64)
C(toWord,readWord,floorWord,ceilWord,Word)
C(toW8,readW8,floorW8,ceilW8,Word8)
C(toW16,readW16,floorW16,ceilW16,Word16)
C(toW32,readW32,floorW32,ceilW32,Word32)
C(toW64,readW64,floorW64,ceilW64,Word64)
D(toDouble,readDouble,Double)
D(toFloat,readFloat,Float)
#undef D
#undef C

#define N(f,g,h,a,m)\
  IL(f) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e);\
  f=A.newArray;\
  IL(g) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e);\
  g=A.newArray_;\
  IL(h) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> [e] -> m (a i e);\
  h=A.newListArray
#define C(a,m)
N(newIOA,newIOA_,newIOAL,IOArray,IO)
N(newSTA,newSTA_,newSTAL,STArray s,ST s)
#undef C
#define C(a,m) MArray (a) e (m),
N(newIOUA,newIOUA_,newIOUAL,IOUArray,IO)
N(newSTUA,newSTUA_,newSTUAL,STUArray s,ST s)
#undef C
#undef N

#undef IL


Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0, 0) and Varda's home is located in point (a, b). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (x, y) he can go to positions (x + 1, y), (x - 1, y), (x, y + 1) or (x, y - 1). Unfortunately, Drazil doesn't have sense of direction. So he randomly chooses the direction he will go to in each step. He may accidentally return back to his house during his travel. Drazil may even not notice that he has arrived to (a, b) and continue travelling. Luckily, Drazil arrived to the position (a, b) successfully. Drazil said to Varda: "It took me exactly s steps to travel from my house to yours". But Varda is confused about his words, she is not sure that it is possible to get from (0, 0) to (a, b) in exactly s steps. Can you find out if it is possible for Varda?

You are given three integers a, b, and s ( - 109 ≤ a, b ≤ 109, 1 ≤ s ≤ 2·109) in a single line.

If you think Drazil made a mistake and it is impossible to take exactly s steps and get from his home to Varda's home, print "No" (without quotes). Otherwise, print "Yes".

NoteIn fourth sample case one possible route is: .

main = do
	d <-getLine
	let [a,b,s]=map read $ words d
	putStrLn $ solve (abs a) (abs b) s

solve::Integer->Integer->Integer->String
solve a b s | s<a+b = "No"
            | odd (a+b-s) = "No"
            | otherwise = "Yes"

main = do
  [a, b, c] <- fmap (map read . words) getLine
  putStrLn $ if (a+b) `mod` 2 == c `mod` 2 && (c >= abs a+ abs b) then "Yes" else "No"

import Data.Functor

getInts :: IO [Int]
getInts = map read <$> words <$> getContents

main = getInts >>= putStrLn . (\b -> if b then "Yes" else "No") . solve

solve :: [Int] -> Bool
solve (a:b:s:[])
    | abs a + abs b > s = False
    | mod (abs a + abs b - s) 2 == 0 = True
    | otherwise = False

main = interact $ f . map (abs . read) . words . concat . lines
f [a,b,s] | (a + b > s) || ((s - a - b)`mod`2 /= 0) = "No" | True = "Yes"

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = (solve.concat =<< forM [1 ..1] ( \i -> map (fst.fromJust.C.readInteger).C.words <$> C.getLine))
solve [x,y,z] = if z>=(abs x+ abs y) && (abs x+ abs y)`mod`2==z`mod`2 then putStrLn "Yes" else putStrLn "No"

module Main where
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8  as C
import Data.List
import Data.Maybe

getIntList :: IO [Int]
getIntList = map fst . mapMaybe C.readInt . C.words <$> C.getLine

main :: IO ()
main = do
  a:b:s:_ <- getIntList
  putStrLn $ if sol a b s then "Yes" else "No"

sol :: Integral a => a -> a -> a -> Bool
sol a b s = t >= 0 && even t
  where
  t = s - (abs a + abs b)

solve :: Int -> Int -> Int -> String
solve n m s
    | (abs(n)+abs(m)) == s = "Yes"
    | (abs(n)+abs(m)) > s = "No"
    | abs(abs(n)+abs(m)-s) `mod` 2 == 0 = "Yes"
	| otherwise = "No"

main = do
    line <- getLine
    let xs = words line
    let [n,m,s] = map read xs
    --let a = if ((n+m) == s) then True else False
    --let b = if ((n+m) < s) then True else False
    --let c = if a || b then "Yes" else "No"
    let c = solve n m s
    putStrLn c

solve :: Int -> Int -> Int -> String
solve n m s
    | (abs(n)+abs(m)) > s = "No"
    | abs(abs(n)+abs(m)-s) `mod` 2 == 0 = "Yes"
	| otherwise = "No"

main = do
    line <- getLine
    let xs = words line
    let [n,m,s] = map read xs
    --let a = if ((n+m) == s) then True else False
    --let b = if ((n+m) < s) then True else False
    --let c = if a || b then "Yes" else "No"
    let c = solve n m s
    putStrLn c

import Control.Applicative
import Data.List
import Data.Char

main=do

  [a,b,s]<- map read <$> words <$> getLine ::IO [Integer]
  putStrLn $ if (s>=abs a+ abs b) && (even (s-a-b)) then "YES" else "NO"

main :: IO ()
main = getLine >>= putStrLn . yesno . solve . map read . words

solve :: [Int] -> Bool
solve [a, b, s] = abs a + abs b <= s && even (s - abs a - abs b)
solve _ = undefined

yesno :: Bool -> String
yesno True = "Yes"
yesno _ = "No"

main = interact $ solve . map read . words
solve [a,b,s] | s < abs a + abs b || (s + a + b) `mod` 2 == 1 = "No"
solve _ = "Yes"

import Data.List
import Control.Applicative
import System.IO

main = do
    [a, b, s] <- map read <$> words <$> getLine
    let a' = abs a
        b' = abs b
    let answer =
          if a' + b' > s || (a' + b' - s) `mod` 2 /= 0 then "No"
                                                       else "Yes"
    putStrLn answer

import Control.Applicative
import Data.List

main=do
	[a,b,s]<-map  read.  words<$> getLine::IO [Int]
	putStrLn $ if (s-(abs a)-(abs b))>=0 && even (s-(abs a)-(abs b)) then "Yes" else "No"

main = do
  [a, b, s] <- getLine >>= return. map (abs.read). words :: IO [Integer]
  putStrLn $ let k = s - a - b in if even k && k >= 0 then "YES" else "NO"

import Control.Applicative

main = do
  [a, b, d] <- map read . words <$> getLine
  let dst = abs a + abs b
  if d >= dst && dst `rem` 2 == d `rem` 2
    then putStrLn "YES"
    else putStrLn "NO"

import Data.Char
import Data.List
import Data.Int
import Data.Maybe
import Control.Monad
import qualified Data.Sequence as Seq
import Data.Foldable(toList)
import qualified Data.ByteString.Char8 as B

readInt :: IO Int
readInt = head `liftM` readIntList

readIntList :: IO [Int]
readIntList = do
    line <- B.getLine
    let res = map (fst . fromJust . B.readInt) $ B.words line
    return res

readString :: IO String
readString = do
    line <- B.getLine
    return $ B.unpack line

main = do
    [a, b, s] <- readIntList
    let dist = abs(a) + abs(b)
    let ans = if dist <= s && (s - dist) `mod` 2 == 0 then "Yes" else "No"
    putStrLn $ ans

module Main where

main = do
  c <- getContents
  let (a:b:s:_) = map (read :: String -> Integer) $ words c
  putStrLn $ case solve a b s of
                 True  -> "Yes"
                 False -> "No"

solve :: Integer -> Integer -> Integer -> Bool
solve a' b' s
  | s < a + b                = False
  | (a + b - s) `mod` 2 == 0 = True
  | otherwise                = False
  where a = abs a'
        b = abs b'

main = interact $ f.map read.words.last.lines
f [a,b,s] = let n = abs a + abs b
            in if s>=n && mod (s-n) 2 == 0 then "Yes" else "No"

main = do
	d <-getLine
	let [a,b,s]=map read $ words d
	putStrLn $ solve a b s

solve::Integer->Integer->Integer->String
solve a b s | s<a+b = "No"
            | odd (a+b-s) = "No"
            | otherwise = "Yes"

main = do
	d <-getLine
	let [a,b,s]=map read $ words d
	putStrLn $ solve a b s

solve a b s | s<a+b = "No"
            | odd (a+b-s) = "No"
            | otherwise = "Yes"

main = do
  [a, b, c] <- fmap (map read . words) getLine
  putStrLn $ if (a+b) `mod` 2 == c `mod` 2 && (c >= a+b) then "Yes" else "No"

main = interact $ f . map read . words . concat . lines
f [a,b,s] | (a + b > s) || ((s - a - b)`mod`2 /= 0) = "No" | True = "Yes"

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = (solve.concat =<< forM [1 ..1] ( \i -> map (fst.fromJust.C.readInteger).C.words <$> C.getLine))
solve [x,y,z] = if z>=(x+y) && (x+y)`mod`2==z`mod`2 then putStrLn "Yes" else putStrLn "No"

module Main where
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8  as C
import Data.List
import Data.Maybe

getIntList :: IO [Int]
getIntList = map fst . mapMaybe C.readInt . C.words <$> C.getLine

main :: IO ()
main = do
  a:b:s:_ <- getIntList
  putStrLn $ if sol a b s then "Yes" else "No"

sol :: Int -> Int -> Int -> Bool
sol a b s = t >= 0 && even t
  where
  t = s - (a+b)

solve :: Int -> Int -> Int -> String
solve n m s
    | (abs(n)+abs(m)) == s = "Yes"
    | (abs(n)+abs(m)) < s = "No"
    | abs(abs(n)+abs(m)-s) `mod` 2 == 0 = "Yes"
	| otherwise = "No"

main = do
    line <- getLine
    let xs = words line
    let [n,m,s] = map read xs
    --let a = if ((n+m) == s) then True else False
    --let b = if ((n+m) < s) then True else False
    --let c = if a || b then "Yes" else "No"
    let c = solve n m s
    putStrLn c

main = do
    line <- getLine
    let xs = words line
    let [n,m,s] = map read xs
    let a = if ((n+m) == s) then True else False
    let b = if ((n+m) < s) then True else False
    let c = if a || b then "Yes" else "No"
    putStrLn $ show (c)

import Control.Applicative
import Data.List
import Data.Char

main=do

  [a,b,s]<- map read <$> words <$> getLine ::IO [Integer]
  putStrLn $ if (s>=a+b) && (even (s-a-b)) then "YES" else "NO"

import Control.Applicative
import Data.List
import Data.Char

main=do

  [a,b,s]<- map read <$> words <$> getLine ::IO [Integer]
  putStrLn $ if even (s-a-b) then "YES" else "NO"

main :: IO ()
main = getLine >>= putStrLn . yesno . solve . map read . words

solve :: [Int] -> Bool
solve [a, b, s] = a + b <= s && even (s - a - b)
solve _ = undefined

yesno :: Bool -> String
yesno True = "Yes"
yesno _ = "No"

import Data.List
import Control.Applicative
import System.IO

main = do
    [a, b, s] <- map read <$> words <$> getLine
    let answer =
          if a + b > s || (a + b - s) `mod` 2 /= 0 then "No"
                                                   else "Yes"
    putStrLn answer

import Control.Applicative
import Data.List

main=do
	[a,b,s]<-map  read.  words<$> getLine::IO [Int]
	putStrLn $ if (s-a-b)>=0 && even (s-a-b) then "Yes" else "No"

main = do
  [a, b, s] <- getLine >>= return. map read. words :: IO [Integer]
  putStrLn $ let k = a + b - s in if even k && k >= 0 then "YES" else "NO"

main = do
  [a, b, s] <- getLine >>= return. map read. words :: IO [Integer]
  putStrLn $ let k = s - a - b in if even k && k >= 0 then "YES" else "NO"

import Control.Applicative

main = do
  [a, b, d] <- map read . words <$> getLine
  if d >= a + b && (a+b) `rem` 2 == d `rem` 2
    then putStrLn "YES"
    else putStrLn "NO"

import Data.Char
import Data.List
import Data.Int
import Data.Maybe
import Control.Monad
import qualified Data.Sequence as Seq
import Data.Foldable(toList)
import qualified Data.ByteString.Char8 as B

readInt :: IO Int
readInt = head `liftM` readIntList

readIntList :: IO [Int]
readIntList = do
    line <- B.getLine
    let res = map (fst . fromJust . B.readInt) $ B.words line
    return res

readString :: IO String
readString = do
    line <- B.getLine
    return $ B.unpack line

getSumPerPos :: Int -> [Int] -> Seq.Seq Int
getSumPerPos cnt =
    foldr step init
    where
        init = Seq.fromList $ replicate cnt 0
        step key seq =
            let oldVal = Seq.index seq (key - 1)
            in
                Seq.update (key - 1) (oldVal + 1) seq

main = do
    [s, a, b] <- readIntList
    let dist = abs(a) + abs(b)
    let ans = if dist >= s && (dist - s) `mod` 2 == 0 then "Yes" else "No"
    putStrLn $ ans

import Data.Char
import Data.List
import Data.Int
import Data.Maybe
import Control.Monad
import qualified Data.Sequence as Seq
import Data.Foldable(toList)
import qualified Data.ByteString.Char8 as B

readInt :: IO Int
readInt = head `liftM` readIntList

readIntList :: IO [Int]
readIntList = do
    line <- B.getLine
    let res = map (fst . fromJust . B.readInt) $ B.words line
    return res

readString :: IO String
readString = do
    line <- B.getLine
    return $ B.unpack line

getSumPerPos :: Int -> [Int] -> Seq.Seq Int
getSumPerPos cnt =
    foldr step init
    where
        init = Seq.fromList $ replicate cnt 0
        step key seq =
            let oldVal = Seq.index seq (key - 1)
            in
                Seq.update (key - 1) (oldVal + 1) seq

main = do
    [s, a, b] <- readIntList
    let dist = abs(a) + abs(b)
    let ans = if dist <= s && (dist - s) `mod` 2 == 0 then "Yes" else "No"
    putStrLn $ ans

module Main where

main = do
  c <- getContents
  let (a:b:s:_) = map (read :: String -> Integer) $ words c
  putStrLn $ case solve a b s of
                 True  -> "Yes"
                 False -> "No"

solve :: Integer -> Integer -> Integer -> Bool
solve a b s
  | s < a + b                = False
  | (a + b - s) `mod` 2 == 0 = True
  | otherwise                = False