main :: IO ()
main = do
    [count, amount] <- map read . words <$> getLine
    let cases = execOtoshidama count amount
    let (x, y, z) = head cases
    if not (null cases)
        then putStrLn $ show $ mconcat [show x," ",show y," ", show z]
        else putStrLn "-1 -1 -1"

execOtoshidama :: Int -> Int -> [(Int, Int, Int)]
execOtoshidama num amount =
        let abc = [(a, b, c) | a <- [0 .. num], b <- [0 .. num], c <- [0 .. num], a + b + c == num]
        in  filter (\(a, b, c) ->
                a * 1000 + b * 5000 + c * 10000 == amount
            ) abc


main = do
    [n,y] <- map read . words <$> getLine
    let (a,b,c) = head $ [(a,b,rest) |
                            a <- [0..n],
                            b <- [0..n-a],
                            let rest = n-a-b,
                            10000*a+5000*b+1000*rest==y] ++ [(-1,-1,-1)]
    putStr $ show a ++ " "
    putStr $ show b ++ " "
    putStrLn $ show c

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 300 points

Problem Statement

The commonly used bills in Japan are 10000-yen, 5000-yen and 1000-yen bills. Below, the word "bill" refers to only these.

According to Aohashi, he received an otoshidama (New Year money gift) envelope from his grandfather that contained N bills for a total of Y yen, but he may be lying. Determine whether such a situation is possible, and if it is, find a possible set of bills contained in the envelope. Assume that his grandfather is rich enough, and the envelope was large enough.

Constraints

1 ≤ N ≤ 2000

1000 ≤ Y ≤ 2 × 10^7

N is an integer.

Y is a multiple of 1000.

Input

Input is given from Standard Input in the following format:

N Y

Output

If the total value of N bills cannot be Y yen, print -1 -1 -1.

If the total value of N bills can be Y yen, let one such set of bills be "x 10000-yen bills, y 5000-yen bills and z 1000-yen bills", and print x, y, z with spaces in between. If there are multiple possibilities, any of them may be printed.

Sample Input 1

9 45000

Sample Output 1

4 0 5

If the envelope contained 4 10000-yen bills and 5 1000-yen bills, he had 9 bills and 45000 yen in total. It is also possible that the envelope contained 9 5000-yen bills, so the output 0 9 0 is also correct.

Sample Input 2

20 196000

Sample Output 2

-1 -1 -1

When the envelope contained 20 bills in total, the total value would be 200000 yen if all the bills were 10000-yen bills, and would be at most 195000 yen otherwise, so it would never be 196000 yen.

Sample Input 3

1000 1234000

Sample Output 3

14 27 959

There are also many other possibilities.

Sample Input 4

2000 20000000

Sample Output 4

2000 0 0

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


solve :: Int -> Int -> [(Int, Int, Int)]
solve n y =
  [(a,b,c) |
      a <- [0..n]
    , b <- [0..n-a]
    , let c = n - a - b
    , c >= 0
    , 10000*a + 5000*b + c*1000 == y] ++ [(-1,-1,-1)]

main = do
  [n, y] <- map read . words <$> getLine :: IO [Int]
  let (a,b,c) = head $ solve n y
  putStr $ show a ++ " "
  putStr $ show b ++ " "
  putStrLn $ show c


main = do
  [n,y] <- map read . words <$> getLine :: IO [Int]
  let c = [[k,j,i] | i<-[0..n], j<-[0..(n-i)], let k=n-i-j, (i*1000 + j*5000 + k*10000)==y]
  putStrLn $ unwords $ map show (if not $ null c then head c else [-1,-1,-1])


main = do
  (x:y:xs) <- map read . words <$> getLine
  putStrLn . unwords . map show $ solve 0 0 0 x y

solve m s h x y
  | x == 0 && y == 0 = [m,s,h]
  | x <= 0 || y <= 0 = [-1,-1,-1]
  | otherwise =
      let mr = solve (m+1) s h (x-1) (y-10000)
          sr = solve m (s+1) h (x-1) (y-5000)
          hr = solve m s (h-1) (x-1) (y-1000)
      in if head mr /= -1 then
        mr
      else if head sr /= -1 then
        sr
      else
        hr


import qualified Data.ByteString.Char8 as C
import           Data.Maybe ( fromJust, isNothing )

readInts :: IO [Int]
readInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine

main :: IO ()
main = do
  [n,y] <- readInts
  putStrLn $ f n y

type Mai = Int
type Yen = Int
type Pochi = (Int,Int,Int) -- #s of 10000,5000,1000 bills

minPochi :: Yen -> Pochi -- returns the minimum number of bills
minPochi y = (a,b,c)
  where
    (a,r) = y `quotRem` 10000
    (b,s) = r `quotRem` 5000
    c     = s `quot` 1000

canPay :: Mai -> Yen -> Maybe Pochi
canPay n y = h i
  where
    i@(a,b,c) = minPochi y

    h :: Pochi -> Maybe Pochi
    h p@(a,b,c)
      | m == 0             = Just p
      | m > 3 && b > 0 = h (a,  b-1,c+5) -- 5000 =5*1000
      | m > 0 && a > 0 = h (a-1,b+2,c)   -- 10000=2*5000
      | otherwise          = Nothing
      where
        m = n-(a+b+c)

f :: Mai -> Yen -> String
f n y
  | isNothing p = "-1 -1 -1"
  | otherwise   = show a ++ " " ++ show b ++ " " ++ show c
  where
    p = canPay n y
    Just (a,b,c) = p

otsdm' :: Mai -> Yen -> [Pochi]
otsdm' n y
  = [(a,b,n-a-b) -- double loop
    | let a0 = y `quot` 10000
    , a <- [0 .. a0]
    , let b0 = (y - 10000*a) `quot` 5000
    , b <- [0 .. b0]]

gok :: Pochi -> Yen
gok (a,b,c) = 10000*a +5000*b + 1000*c

otsdm :: Mai -> Yen -> String
otsdm n y
  | null os   = "-1 -1 -1"
  | otherwise = show a ++ " " ++ show b ++ " " ++ show c
  where
    os = filter (\o -> y == gok o) $ otsdm' n y
    (a,b,c) = head os


main = do
    [n, m] <- map read . words <$> getLine
    let xs = [[x, y, n-x-y] | x <- [0..n], y <- [0..n-x], x*10000 + y*5000 + (n-x-y)*1000 == m]
    putStrLn $ if null xs then "-1 -1 -1" else unwords $ map show $ head xs


pat :: Int -> Int -> [[Int]]
pat n y = [[a,b,c]| a <- [0..n], b <- [0..n-a], let c = n - a - b, 10000*a+5000*b+1000*c == y]

main :: IO ()
main = do
  [n,y] <- map read . words <$> getLine
  let ps = pat n y
  let xs = if null ps then [-1,-1,-1] else head ps
  putStrLn $ unwords $ map show xs


import Text.Printf (printf)

pat :: Int -> Int -> [(Int, Int, Int)]
pat n y = [(a,b,c)| a <- [0..n], b <- [0..n-a], let c = n - a - b, 10000*a+5000*b+1000*c == y]

main :: IO ()
main = do
  [n,y] <- (map read . words) <$> getLine
  let ps = pat n y
  let (a,b,c) = if null ps then (-1,-1,-1) else head ps
  printf "%d %d %d\n" a b c


main = do
    [n,u] <- map read . words <$> getLine :: IO [Int]
    putStrLn . unwords . map show . head $
        [ [x, y, z] |
          x <- [0..n],
          y <- [0..n-x],
          let z = n-x-y,
          10000 * x + 5000 * y + 1000 * z == u
        ] ++ [replicate 3 (-1)]


main :: IO ()
main = do
  [n,y] <- map (read :: String -> Int) . words <$> getLine
  putStrLn $ app $ ans n y

app :: (Int,Int,Int) -> String
app (a,b,c) = show a ++ ' ' : show b ++ ' ' : show c

ans :: Int -> Int -> (Int,Int,Int)
ans n y = foldl func (-1,-1,-1) (allComb n) where
  func acc k@(a,b,c)
    | acc /= (-1,-1,-1) = acc
    | y == a*10000+b*5000+c*1000 = k
    | otherwise = acc

allComb :: Int -> [(Int,Int,Int)]
allComb n = concat $ map func [0..n] where
  func k = map (\(a,b) -> (k,a,b)) $ allPair (n-k)
  allPair m = zip [0..m] [m,m-1..0]


main = do
  [n, y] <- map read . words <$> getLine
  let ny = [[a, b, c] | a <- [0..n], b <- [0..(n - a)], let c = n - (a + b), 10000 * a + 5000 * b + 1000 * c == y]
  putStrLn $ if null ny then "-1 -1 -1" else unwords $ map show $ head ny


import Data.Maybe

main :: IO ()
main =do
  [n,y] <- map read . words <$> getLine :: IO [Int]
  let list = [if (a*10+b*5+c)*1000==y then Just [a,b,c] else Nothing
           | a <- [0..n], b <- [0..n-a], let c = n-a-b ] :: [Maybe [Int]]
  putStr . unwords . map show . fromJust . head $ filter isJust list ++ [Just [-1,-1,-1]]


main :: IO ()
main = do
  [n, y] <- map read . words <$> getLine :: IO [Int]
  let ans = filter (not . null) $ solve n (y `div` 1000)
  if null ans
    then putStrLn "-1 -1 -1"
    else putStrLn $ unwords $ map show $ head ans

solve n y = let max' = head $ filter ((<= y) . (* 10))
                       [n, n-1 .. 0]
            in do
  i <- [0 .. max']
  j <- [0 .. n - i]
  if y == (10 * i) + 5 * j + (n - i - j)
    then return [i, j, n-i-j]
    else return []


import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)

main :: IO ()
main = do
    [n, y] <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
    let ans = [[a, b, n - a - b] | a <- [0..2000], b <- [0..2000], 9 * a + 4 * b == y `div` 1000 - n && n - a - b >= 0]
    if null ans
        then putStrLn "-1 -1 -1"
        else do
            let [a, b, c] = head ans
            putStrLn $ show a ++ " " ++ show b ++ " " ++ show c


main :: IO ()
main = do
    line <- getLine
    let n = read (head (splitOn ' ' line)) :: Int
    let y = read (last (splitOn ' ' line)) :: Int
    putStrLn $ showRes $ calc n y

calc :: Int -> Int -> (Int, Int, Int)
calc n y = if length res == 0 then (-1, -1, -1) else snd $ head res
    where
        res = filter (\x -> y == fst x) $ map calcSum [(a, b, n - a - b) | a <- [0..n], b <- [0..(n - a)]]
        calcSum (a, b, c) = (a * 10000 + b * 5000 + c * 1000, (a, b, c))

showRes :: (Int, Int, Int) -> String
showRes (a, b, c) = show a ++ " " ++ show b ++ " " ++ show c

splitOn :: Char -> String -> [String]
splitOn c s
    = current "" [] c $ reverse s
    where
        current :: String -> [String] -> Char -> String -> [String]
        current cur lis c [] = cur:lis
        current cur lis c (x:ss)
            = if c == x then
                  current "" (cur:lis) c ss
              else
                  current (x:cur) lis c ss


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}

main :: IO ()
main = putStrLn . showResult =<< solve <$> getInput

showResult :: Maybe (Int, Int, Int) -> String
showResult Nothing          = "-1 -1 -1"
showResult (Just (a, b, c)) = show a ++ " " ++ show b ++ " " ++ show c

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

solve :: (Int, Int) -> Maybe (Int, Int, Int)
solve (n, y) = headMaybe [(a, b, c)
                         | a <- [0 .. n]
                         , b <- [0 .. n]
                         , let c = n - a - b
                         , c >= 0
                         , 10000 * a + 5000 * b + 1000 * c == y
                         ]

headMaybe :: [a] -> Maybe a
headMaybe []     = Nothing
headMaybe (x:xs) = Just x


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}

main :: IO ()
main = putStrLn . showResult =<< solve <$> getInput

showResult :: Maybe (Int, Int, Int) -> String
showResult Nothing          = "-1 -1 -1"
showResult (Just (a, b, c)) = show a ++ " " ++ show b ++ " " ++ show c

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

solve :: (Int, Int) -> Maybe (Int, Int, Int)
solve (n, y) = headMaybe [(x, y, z)
                         | x <- [0 .. n]
                         , y <- [0 .. n]
                         , z <- [0 .. n]
                         , x + y + z == n
                         , 10000 * x + 5000 * y + 1000 + z == y
                          ]

headMaybe :: [a] -> Maybe a
headMaybe []     = Nothing
headMaybe (x:xs) = Just x


import Control.Monad
main = do
  [n, y] <- (map read . words) <$> getLine
  putStrLn $ unwords $ map show $ resolve n y

co [] = [-1, -1, -1]
co (w:_) = w

resolve:: Int -> Int -> [Int]
resolve n y = w
  where
    w = co [[m, g, s] | m <- [0..n], g <- [0..(n - m)], s <- [n - m - g], m + g + s == n, m * 10000 + g * 5000 + s * 1000 == y]


{-
     9 * a + 5 * b =  10 * N - Y
         a +     b <= N

-}

isInt :: (RealFrac a) => a -> Bool
isInt x = x == fromInteger (round x)

main = do
    input <- fmap words getLine
    let (n, y) = (read $ head input, (read $ input!!1) / 1000)
    let pairs = [(a, b) | a <- [0..n], b <- [0..n], a + b <= n]
    let satisfiesEquation = filter (\(a ,b) -> 9 * a + 5 * b == 10 * n - y) pairs
    let (t, f) = head $ filter (\(a, b) -> isInt a && isInt b) satisfiesEquation
    let (thousand, fiveThousand) = (round t, round f)
    putStr $ show thousand
    putStr " "
    putStr $ show  fiveThousand
    putStr " "
    putStrLn $ show $ (round $ n - t - f)


import Data.Int (Int64)

findCand :: Integral a => a -> a -> Maybe (a, a, a)
findCand n y
    | null cands = Nothing
    | otherwise = Just $ head cands
    where
        y0 = div y 1000
        cands = [(a, b, c) | a <- [0 .. n], b <- [0 .. n],
                             let c = n - a - b, c >= 0,
                             10 * a + 5 * b + c == y0]

main :: IO ()
main = do
    [n, y] <- fmap read . words <$> getLine :: IO [Int64]
    let res = case findCand n y of
                Just (a, b, c) -> [a, b, c]
                Nothing -> [-1, -1, -1]
    putStrLn $ unwords $ fmap show res


import Data.List
import qualified Data.IntMap as M
import Data.Maybe(fromJust)

main = do
  [n,y] <- map read . words <$> getLine :: IO [Int]
  let patten = [(i, j) | i <- [0..n], j <- [0..n-i]]
      m = foldl (solve n y) M.empty patten
      ans = M.lookup y m
  if ans /= Nothing
    then let (a, b) = fromJust ans
         in putStrLn $ show a ++ " " ++ show b ++ " " ++ show (n-a-b)
    else putStrLn "-1 -1 -1"

solve :: Int -> Int -> M.IntMap (Int, Int) -> (Int, Int) -> M.IntMap (Int, Int)
solve n y m (i, j) = M.insert (i*10000+j*5000+(n-i-j)*1000) (i, j) m


module Main(main) where
import Data.List

comb n y = filter (\(a,b,c) -> y == (a*10) + (b*5) + c) $ [0 .. n] >>= (\y -> map (\a -> (a,y,n-y-a)) [0 .. n-y])

ans [] = "-1 -1 -1"
ans ((a,b,c):_) = (show (floor a)) ++ " " ++ (show (floor b)) ++ " " ++ (show (floor c))

main :: IO ()
main = do
  [n,y] <- map read . words <$> getLine :: IO [Double]
  putStrLn $ ans $ comb n (y / 1000)


import Control.Applicative
import Data.List
import Control.Monad
strToInt s = (read :: String -> Int) s

main :: IO ()
main = do
    -- スペース区切り整数の入力
    [n, y] <- map strToInt . words <$> getLine
    -- 出力
    putStrLn . (\[a, b, c] -> show a ++ " " ++ show b ++ " " ++ show c)$ (if null $ func n y then [-1, -1, -1] else head $ func n y)

func :: Int -> Int -> [[Int]]
func n y = [[a, b, c] | a <- [0..n], b <- [0..n], c <- [0..n], a + b + c == n, a * 1000 + b * 5000 + c * 10000 == y]


import Data.List

main = do
  [n,y] <- map read . words <$> getLine :: IO [Int]
  let patten = [(i, j, n-i-j) | i <- [0..n], j <- [0..n-i]]
      ans = map (solve y) patten
      flag = or ans
  if flag
    then let idx = head $ elemIndices True ans
             (a, b, c) = patten !! idx
         in putStrLn $ show a ++ " " ++ show b ++ " " ++ show c
    else putStrLn "-1 -1 -1"

solve :: Int -> (Int, Int, Int) -> Bool
solve y (i,j,k)
  | i * 10000 + j * 5000 + k * 1000 == y = True
  | otherwise = False


import Data.List

main = do
    [n,h] <- map read . words <$> getLine :: IO[Int]
    co <- getContents
    let (a,bs) = foldl (\ (a,bs) [a',b] -> (max a a', b:bs)) (0,[]) $ map (map read) $ map words $ lines co
    let xs = foldr (\ x' all@(x:xs) -> if x' >= x then x':all else all) [a] $ sortBy (flip compare) bs
    print $ solve xs h

solve :: [Int] -> Int -> Int
solve [x] h = (h+x-1) `div` x
solve (x:xs) h = if x >= h then 1 else 1 + solve xs (h-x)

Score : 400 points

Problem Statement

You are going out for a walk, when you suddenly encounter a monster. Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and can perform the following two kinds of attacks in any order:

Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.

Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.

The monster will vanish when the total damage it has received is H points or more. At least how many attacks do you need in order to vanish it in total?

Constraints

1 ≤ N ≤ 10^5

1 ≤ H ≤ 10^9

1 ≤ a_i ≤ b_i ≤ 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N H
a_1 b_1
:
a_N b_N

Output

Print the minimum total number of attacks required to vanish the monster.

Sample Input 1

1 10
3 5

Sample Output 1

3

You have one katana. Wielding it deals 3 points of damage, and throwing it deals 5 points of damage. By wielding it twice and then throwing it, you will deal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing the monster.

Sample Input 2

2 10
3 5
2 6

Sample Output 2

2

In addition to the katana above, you also have another katana. Wielding it deals 2 points of damage, and throwing it deals 6 points of damage. By throwing both katana, you will deal 5 + 6 = 11 points of damage in two attacks, vanishing the monster.

Sample Input 3

4 1000000000
1 1
1 10000000
1 30000000
1 99999999

Sample Output 3

860000004

Sample Input 4

5 500
35 44
28 83
46 62
31 79
40 43

Sample Output 4

9


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
import qualified Data.ByteString.Char8 as BS
import           Data.List             (sortOn, transpose)
import           Data.Maybe            (fromJust)
import           Data.Ord              (Down (Down))

main :: IO ()
main = do
  [n, h] <- readInts <$> BS.getLine
  abs' <- map readInts . BS.lines <$>  BS.getContents
  print $ solve n h abs'

solve :: Int -> Int -> [[Int]] -> Int
solve _ h abs' = c + d where
  [as, bs] = transpose abs'
  maxA = maximum as
  (c, h') = throwSword (0, h) . sortOn Down $ filter (maxA <) bs
  d = (h' + maxA - 1) `div` maxA

throwSword :: (Int, Int) -> [Int] -> (Int, Int)
throwSword ch [] = ch
throwSword (!c, !h) (b:bs)
  | h <= 0 = (c, 0)
  | otherwise = throwSword (c + 1, h - b) bs

readInt :: BS.ByteString -> Int
readInt = fst . fromJust . BS.readInt

readInts :: BS.ByteString -> [Int]
readInts = map readInt . BS.words


import Data.List
import Data.Maybe

main = do
  (n:h:_) <- getLine >>= return . map read . words :: IO [Int]
  ktn <- getContents >>= return . map (map read . words) . lines :: IO [[Int]]

  let
    (a:_) = maximumBy (\(x:_) (y:_) -> compare x y) ktn
    b = scanl (+) 0 $ reverse $ sort $ map (\(x:y:_) -> y) $ filter (\(_:x:_) -> x > a) ktn

    c = findIndex (>=h) b

    d =
      if c == Nothing then
        ceiling ((fromIntegral (h-last b)) / (fromIntegral a)) + (length b - 1)
      else
        fromJust c

  print $ d


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
import           Control.Monad         (replicateM)
import qualified Data.ByteString.Char8 as BC
import           Data.List             (sort)
import           Data.Maybe            (fromJust)

main :: IO ()
main = print =<< solve <$> getInput

getInput :: IO (Int, Int, [(Int, Int)])
getInput = do
  [n, h] <- readInts
  abs <- replicateM n readInt2
  return (n, h, abs)

readInts = map (fst . fromJust . BC.readInt) . BC.words <$> BC.getLine

readInt2 = do
  [a, b] <- readInts
  return (a, b)

solve (n, h, abs) = nAttack + mAttack
  where maxA = maximum $ map fst abs
        (nAttack, restHP) = throwAttack maxA (map snd abs) h
        mAttack = swingAttack maxA restHP

throwAttack :: Int -> [Int] -> Int -> (Int, Int)
throwAttack a bs h = if null powerfulBs
  then (0, h)
  else if null rest
       then (length throwns, h - last throwns)
       else (length throwns + 1, h - head rest)
  where powerfulBs = filter (> a) bs
        (throwns, rest) = span (< h) . scanl1 (+) . reverse $ sort powerfulBs

swingAttack a h
  | h <= 0   = 0
  | otherwise = h `div` a + if h `mod` a == 0 then 0 else 1
      --ceiling $ fromIntegral h / fromIntegral a


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
import           Control.Monad         (replicateM)
import qualified Data.ByteString.Char8 as BC
import           Data.List             (sort)
import           Data.Maybe            (fromJust)

main :: IO ()
main = print =<< solve <$> getInput

getInput :: IO (Int, Int, [(Int, Int)])
getInput = do
  [n, h] <- readInts
  abs <- replicateM n readInt2
  return (n, h, abs)

readInts = map (fst . fromJust . BC.readInt) . BC.words <$> BC.getLine

readInt2 = do
  [a, b] <- readInts
  return (a, b)

solve (n, h, abs) = nAttack + mAttack
  where maxA = maximum $ map fst abs
        (nAttack, restHP) = throwAttack maxA (map snd abs) h
        mAttack = swingAttack maxA restHP

throwAttack :: Int -> [Int] -> Int -> (Int, Int)
throwAttack a bs h = if null powerfulBs
  then (0, h)
  else if null rest
       then (length throwns, h - last throwns)
       else (length throwns + 1, h - head rest)
  where powerfulBs = filter (> a) bs
        (throwns, rest) = span (<= h) . scanl1 (+) . reverse $ sort powerfulBs

swingAttack a h
  | h <= 0   = 0
  | otherwise = h `div` a + if h `mod` a == 0 then 0 else 1
      --ceiling $ fromIntegral h / fromIntegral a


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
import           Control.Monad (replicateM)
import           Data.List     (sort)
import           Debug.Trace
main :: IO ()
main = print =<< solve <$> getInput

getInput :: IO (Int, Int, [(Int, Int)])
getInput = do
  [n, h] <- readInts
  abs <- replicateM n readInt2
  return (n, h, abs)

readInts = map read . words <$> getLine

readInt2 = do
  [a, b] <- readInts
  return (a, b)

solve (n, h, abs) = nAttack + mAttack
  where maxA = maximum $ map fst abs
        (nAttack, restHP) = throwAttack maxA (map snd abs) h
        mAttack = swingAttack maxA restHP

throwAttack :: Int -> [Int] -> Int -> (Int, Int)
throwAttack a bs h = if null rest
                       then (length throwns, h - last throwns)
                       else (length throwns + 1, h - head rest)
  where powerfulBs = filter (> a) bs
        (throwns, rest) = span (< h) . sort $ scanl1 (+) powerfulBs

swingAttack a h
  | h <= 0   = 0
  | otherwise = ceiling $ fromIntegral h / fromIntegral a


import Control.Monad
import Data.List

main :: IO ()
main = do
  [n, h] <- readInts
  ks <- replicateM n readInts
  print $ solve h ks

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

solve :: Int -> [[Int]] -> Int
solve h ks = solve' h 0 $ bs ++ repeat a
  where
    a = maximum [ _a | [_a, _] <- ks ]
    bs = sortOn negate $ [ b | [_, b] <- ks, b > a ]

solve' :: Int -> Int -> [Int] -> Int
solve' h n (x:xs)
  | h <= 0 = n
  | otherwise = solve' (h - x) (n + 1) xs


import           Control.Monad
import           Data.List
import           Debug.Trace

main :: IO ()
main = do
    [n, h] <- getInts
    ab <- replicateM n $ do
        [a, b] <- getInts
        return (a, b)
    let as = map fst ab
        bs = map snd ab
    print $ solve h as bs

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

solve :: Int -> [Int] -> [Int] -> Int
solve h as = go 0 0 . sortBy (flip compare) . filter (> maxA)
  where
    maxA = maximum as
    go n x [] = (h - x + maxA - 1) `div` maxA + n
    go n x (y:ys)
        | y + x >= h = n + 1
        | otherwise = go (n+1) (x + y) ys


import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Functor
import Data.Function
import Data.Monoid
import Data.Maybe
import Data.List
import qualified Data.Foldable as Foldable
import qualified Data.Set as Set
import qualified Data.Sequence as Sequence
import Data.List.Split
import Data.Bits
import Data.Char
import Data.Ix
import Data.Ratio
import Data.Ord
import Data.Tuple
--import Data.Array
import Data.Array.IArray
--import Data.Array.Unboxed
import Data.Array.MArray
import Data.Array.IO
import Data.Array.ST
import Data.IORef
import Data.STRef
-- import System.IO.Unsafe

readInt = read :: String -> Int
readInteger = read :: String -> Integer
readDouble = read :: String -> Double
getInt = readLn :: IO Int
getInts = map readInt . words <$> getLine
getInteger = readLn :: IO Integer
getIntegers = map readInteger . words <$> getLine
getDouble = readLn :: IO Double
sjoin :: (Show a) => [a] -> String
sjoin = unwords . map show
cond :: a -> a -> Bool -> a
cond t f c = if c then t else f
apply2 :: (a -> a -> b) -> [a] -> b
apply2 f [x,y] = f x y
apply3 :: (a -> a -> a -> b) -> [a] -> b
apply3 f [x,y,z] = f x y z
apply4 :: (a -> a -> a -> a -> b) -> [a] -> b
apply4 f [x,y,z,w] = f x y z w
fnBin :: (b -> c -> d) -> (a -> b) -> (a -> c) -> a -> d
fnBin op f g x = op (f x) $ g x
fnTuple :: (a -> b, a -> c) -> a -> (b, c)
fnTuple (f,g) a = (f a, g a)
replace :: (Eq a) => a -> a -> [a] -> [a]
replace x y = map (\z -> if z==x then y else z)
modifyArray :: (Ix i, MArray a e m) => a i e -> i -> (e -> e) -> m ()
modifyArray arr ix f = readArray arr ix >>= writeArray arr ix . f
dictCompare :: [a -> a -> Ordering] -> a -> a -> Ordering
dictCompare [] _ _ = EQ
dictCompare (f:fs) x y = let c = f x y in if c==EQ then dictCompare fs x y else c
binMap :: (a -> a -> b) -> [a] -> [b]
binMap f (x:xs@(y:_)) = f x y : binMap f xs
binMap _ _ = []
splitRec :: Int -> [a] -> [[a]]
splitRec _ [] = []
splitRec n xs = let (y,ys) = splitAt n xs in y : splitRec n ys
infixl 7 `divCeil`
divCeil :: Integral a => a -> a -> a
x `divCeil` y = (x+y-1) `div` y
-- end of templete

main = do
    [n,h] <- getInts
    xs <- map (apply2 (,)) <$> replicateM n getInts
    print $ let da = maximum $ map fst xs in let fd = scanl (-) h $ sortBy (flip compare) $ filter (>=da) $ map snd xs in let r = last fd in if r>0 then length fd - 1 + r `divCeil` da else length $ filter (>0) fd


module Main(main) where
import Data.List

attack katana h =
  let as = map head katana
      bs = map (head . tail) katana
      ma = foldl max 1 as
      tk = sort $ filter (> ma) bs
      simulate :: Int -> Int -> [Int] -> Int
      simulate cnt rest [] =
        if rest >= ma then simulate (cnt+1) (rest - ma) []
        else cnt+1
      simulate cnt rest (x:xs) =
        if rest >= x then simulate (cnt+1) (rest - x) xs
        else cnt+1
  in simulate 0 h tk

main :: IO ()
main = do
  [n,h] <- map read . words <$> getLine :: IO [Int]
  katana <- (map $ map read . words) <$> (sequence $ replicate n getLine) :: IO [[Int]]
  print $ attack katana h


import Control.Applicative
import Data.List
import Control.Monad
strToInteger s = (read :: String -> Integer) s

main :: IO ()
main = do
    -- スペース区切り整数の入力
    [n, h] <- map strToInteger . words <$> getLine
    ns <- replicateM (fromInteger n) $ do
        [a, b] <- map strToInteger . words <$> getLine
        return (a, b)
    -- 出力
    putStrLn . show $ func ns n h

func :: [(Integer, Integer)] -> Integer -> Integer -> Integer
func ns n h = if sum bs <= h then damage `div` amax + (fromIntegral $ length bs) + c
                             else fromIntegral $ length $ takeWhile (> h) $ scanl (+) 0 bs
    where
        amax = maximum $ map fst ns
        bs = takeWhile (amax <) $ reverse . sort $ map snd ns
        damage = if h - (sum bs) > 0 then h - (sum bs) else 0
        c = if damage `mod` amax == 0 then 0 else 1


module Main(main) where
import Data.List

takeawh h [] = []
takeawh h (x:xs) = if x < h then x:takeawh (h-x) xs
                   else [x]

attack katana h =
  let as = map head katana
      bs = map (head . tail) katana
      ma = foldl max 1 as
      tk = takeawh h $ sort $ filter (> ma) bs
      h' = fromIntegral $ max 0 (h - (foldl (+) 0 tk))
      al = length tk + (floor (((h' / (fromIntegral ma)) :: Double) + 0.5))
  in al

main :: IO ()
main = do
  [n,h] <- map read . words <$> getLine :: IO [Int]
  katana <- (map $ map read . words) <$> (sequence $ replicate n getLine) :: IO [[Int]]
  print $ attack katana h


import Control.Applicative ((<$>))
import Control.Arrow ((***))
import Control.Monad
import Data.List

main :: IO ()
main = do
  [n,h] <- map read . words <$> getLine
  (a,bs) <- fmap (maximum *** sortBy (flip compare)) $ fmap unzip $ replicateM n $ do
    [a,b] <- map read . words <$> getLine
    return (a,b)
  let bs' = takeWhile (>a) bs
      (ans,rest) = foldl' (\(aans,arest) b -> if arest == 0 then (aans,arest) else (aans+1,arest-b)) (0,h) bs'
      ans' = if rest > 0 then ans + ceiling (fromIntegral rest / fromIntegral a) else ans

  print ans'


import Data.List
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Data.Ord

main :: IO ()
main = breads >>= main'
    where
        main' [n, h] = replicateM n breads >>= print . solve h

solve :: Int -> [[Int]] -> Int
solve h xs = an + calc (h - an * fa) bs
    where
        bs = sortBy (flip compare) . filter (> fa) $ fmap last xs
        fa = head $ maximumBy (\x y -> comparing head x y) xs
        bsum = sum bs
        (ar, am) = (h - bsum) `divMod` fa
        an
            | am > 0 = ar + 1
            | otherwise = ar
        calc r (y : ys)
            | r <= 0 = 0
            | otherwise = 1 + calc (r - y) ys
        calc r _
            | r > 0 = h * 2
            | otherwise = 0

breads :: IO [Int]
breads = unfoldr uff <$> B.getLine
    where
        uff b = check <$> B.readInt b
        check (a, b)
            | B.null b = (a, b)
            | otherwise = (a, B.tail b)


module Main where

import           Data.List

toInt :: String -> Int
toInt s = read s :: Int

strToIntList :: String -> [Int]
strToIntList = map toInt . words

getIntList :: IO [Int]
getIntList = getLine >>= return . strToIntList

main :: IO ()
main = do
  nab <- getIntList
  print
    .   sum
    .   map fst
    .   filter (\(_, b) -> nab !! 1 <= b && b <= nab !! 2)
    $   zip
    <$> id
    <*> map (sum . tt)
    $   [1 .. head nab]

tt :: Int -> [Int]
tt = unfoldr fnc where
  fnc 0 = Nothing
  fnc n = Just (n `mod` 10, n `div` 10)

Score : 200 points

Problem Statement

Find the sum of the integers between 1 and N (inclusive), whose sum of digits written in base 10 is between A and B (inclusive).

Constraints

1 \leq N \leq 10^4

1 \leq A \leq B \leq 36

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the sum of the integers between 1 and N (inclusive), whose sum of digits written in base 10 is between A and B (inclusive).

Sample Input 1

20 2 5

Sample Output 1

84

Among the integers not greater than 20, the ones whose sums of digits are between 2 and 5, are: 2,3,4,5,11,12,13,14 and 20. We should print the sum of these, 84.

Sample Input 2

10 1 2

Sample Output 2

13

Sample Input 3

100 4 16

Sample Output 3

4554


main :: IO ()
main = do
  [n,a,b] <- map read . words <$> getLine  :: IO [Int]
  let xs = filter (\x -> let d = digs x in d>=a && d<=b) [1..n]
  print $ sum xs

digs :: Int -> Int
digs = sum . map (read . return) . show


digitSum :: Int -> Int
digitSum 0 = 0
digitSum x = (x `mod` 10) + digitSum (x `div` 10)

solve :: [Int] -> Int
solve (n:a:b:_) = sum $ filter inInterval $ map digitSum [1..n]
	where inInterval x = a <= x && x <= b

main = interact $ show . solve . map read . words


import           Data.Char
main :: IO ()
main = do
    [n, a, b] <- map read . words <$> getLine
    let sum' = sum . map digitToInt . show
    print . sum . filter (\x -> a <= sum' x && sum' x <= b) $ [1..n]


import Data.List (unfoldr)
import Data.Tuple (swap)

toDigits :: Int -> [Int]
toDigits = unfoldr phi
  where
    phi n = if n /= 0 then Just (swap (n `divMod` 10)) else Nothing

calc :: [Int] -> Int
calc [n,a,b] = sum $ filter p [1..n]
  where
    p m = a <= s && s <= b where s = sum (toDigits m)

main :: IO ()
main = print . calc =<< fmap read . words <$> getLine


import           Control.Monad
import           Data.List
import           Data.Ord
import           Data.List.Split
import qualified Data.Vector.Unboxed as V

main :: IO ()
main = do
  [n, a, b] <- map read . words <$> getLine
  let as = [map (\a -> read [a] :: Integer) (show x) | x <- [0, 1 .. n]]
  print
    $ sum . map (read . concatMap show)
    $ filter (\l -> sum l >= a && sum l <= b) as


import Data.Char (digitToInt)

main :: IO ()
main = do
    [n,a,b] <- map read .words <$> getLine
    print . sum $ nums n a b

nums :: Int -> Int -> Int -> [Int]
nums n a b = filter (between a b . sumDigits) [1..n]

between :: Ord a => a -> a -> a -> Bool
between a b s = a <= s && s <= b

sumDigits :: Int -> Int
sumDigits = sum . map digitToInt . show


import Control.Monad
import Data.Char
import Data.List
main=do
    [n,a,b]<-map read.words<$>getLine
    print $ sum [x|x<-[1..n], s<-[sum $ map digitToInt $ show x], s>=a && s<=b]


import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)
import Data.Char

f :: Int -> Int -> Int -> Bool
f a b n =
    let s x = foldr ((+) . digitToInt) 0 (show x)
    in a <= s n && s n <= b

main :: IO ()
main = do
    [n, a, b] <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
    print $ sum $ filter (f a b) [1..n]


digitSum n = inner n 0
  where inner 0 rv = rv
        inner m rv = let (q, r) = quotRem m 10
                     in
                       inner q (r + rv)

sums n = [ (k, digitSum k) | k <- [1 .. n]]

sums10000 = sums 10000

filterSums n a b = filter (\(_, x) -> a <= x && x <= b) $ take n sums10000

answer n a b = foldr (\(x, _) y -> x + y) 0
               $ filterSums n a b

main = interact $ (++ "\n")
       . show
       . (\[x, y, z] -> answer x y z)
       . map read
       . take 3
       . words
       . head
       . lines


import Control.Applicative

main = getLine >>= print.length.filter(=='1')

Score : 100 points

Problem Statement

Snuke has a grid consisting of three squares numbered 1, 2 and 3.
In each square, either 0 or 1 is written. The number written in Square i is s_i.

Snuke will place a marble on each square that says 1.
Find the number of squares on which Snuke will place a marble.

Constraints

Each of s_1, s_2 and s_3 is either 1 or 0.

Input

Input is given from Standard Input in the following format:

s_{1}s_{2}s_{3}

Output

Print the answer.

Sample Input 1

101

Sample Output 1

2

A marble will be placed on Square 1 and 3.

Sample Input 2

000

Sample Output 2

0

No marble will be placed on any square.


--{-# LANGUAGE BangPatterns #-}
--{-# LANGUAGE ScopedTypeVariables #-}
--{-# LANGUAGE FlexibleContexts #-}
--{-# LANGUAGE ViewPatterns #-}
--{-# LANGUAGE OverloadedStrings #-}
--{-# LANGUAGE Strict #-}
--{-# LANGUAGE NumericUnderscores #-}
--{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE MultiWayIf #-}

import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.ByteString.Char8 as BC
import qualified Data.Map.Strict as MPS
import qualified Data.Map as MP
import qualified Data.Set as ST
import qualified Data.Sequence as SQ
import Data.Array
import Data.Array.Unboxed
import Data.Array.ST
import Data.Array.IO
import Data.Maybe
import Data.Ord
import Data.Ratio
import Data.Char
import Data.Bits
import Data.List
import Data.Tuple
import Data.Functor
import Data.IORef
import Data.STRef
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Control.Monad.State.Strict
import Debug.Trace
-- import qualified Data.Vector.Algorithms.Merge as VAM
-- import qualified Data.Heap as HP
-- import Numeric.Extra
-- import Data.Tuple.Extra
-- import Data.List.Extra

--------------------------------------------------------------------------
main = str >>= print . sum . map digitToInt
--------------------------------------------------------------------------

-- Input Util
int :: IO Int
int = bsToInt <$> BC.getLine

double :: IO Double
double = bsToDouble <$> BC.getLine

str :: IO String
str = BC.unpack <$> BC.getLine

strBS :: IO BC.ByteString
strBS = BC.getLine

-- convert
bsToInt :: BC.ByteString -> Int
bsToInt = fst . fromJust . BC.readInt

bsToDouble :: BC.ByteString -> Double
bsToDouble = read . BC.unpack

bsToIntTuple :: BC.ByteString -> (Int, Int)
bsToIntTuple bs = (a,b)
    where
        Just (a,bs') = parseInt bs
        Just (b,_) = parseInt bs'

bsToIntTriple :: BC.ByteString -> (Int, Int, Int)
bsToIntTriple bs = (a,b,c)
    where
        Just (a,bs') = parseInt bs
        Just (b,bs'') = parseInt bs'
        Just (c,_) = parseInt bs''

parseInt :: BC.ByteString -> Maybe (Int, BC.ByteString)
parseInt = BC.readInt . BC.dropWhile isSpace

-- single line
fromSLineL :: (BC.ByteString -> a) -> IO [a]
fromSLineL f =  map f . BC.words <$> strBS

-- from single line to List / VU.Vector
sLineToIntL :: IO [Int]
sLineToIntL = fromSLineL bsToInt

sLineToDoubleL :: IO [Double]
sLineToDoubleL = fromSLineL bsToDouble

sLineToStrL :: IO [String]
sLineToStrL = fromSLineL BC.unpack

sLineToStrBSL :: IO [BC.ByteString]
sLineToStrBSL = fromSLineL id

sLineToIntV :: Int -> IO (VU.Vector Int)
sLineToIntV n = VU.unfoldrN n parseInt <$> BC.getLine

sLineToDoubleV :: IO (VU.Vector Double)
sLineToDoubleV = VU.fromList . map bsToDouble . BC.words <$> BC.getLine

-- multiple lines
fromMLinesL :: Int -> (BC.ByteString -> a) -> IO [a]
fromMLinesL n f = replicateM n (f <$> strBS)

fromMLinesV :: VU.Unbox a => Int -> (BC.ByteString -> a) -> IO (VU.Vector a)
fromMLinesV n f = VU.replicateM n (f <$> strBS)

-- from multiple lines to List / VU.Vector
mLinesToIntL :: Int -> IO [Int]
mLinesToIntL n = fromMLinesL n bsToInt

mLinesToDoubleL :: Int -> IO [Double]
mLinesToDoubleL n = fromMLinesL n bsToDouble

mLinesToStrL :: Int -> IO [String]
mLinesToStrL n = fromMLinesL n BC.unpack

mLinesToStrBSL :: Int -> IO [BC.ByteString]
mLinesToStrBSL n = fromMLinesL n id

mLinesToTupleL :: Int -> IO [(Int, Int)]
mLinesToTupleL n = fromMLinesL n bsToIntTuple

mLinesToTripleL :: Int -> IO [(Int, Int, Int)]
mLinesToTripleL n = fromMLinesL n bsToIntTriple

mLinesToIntV :: Int -> IO (VU.Vector Int)
mLinesToIntV n = fromMLinesV n bsToInt

mLinesToDoubleV :: Int -> IO (VU.Vector Double)
mLinesToDoubleV n = fromMLinesV n bsToDouble

mLinesToTupleV :: Int -> IO (VU.Vector (Int, Int))
mLinesToTupleV n = fromMLinesV n bsToIntTuple

mLinesToTripleV :: Int -> IO (VU.Vector (Int, Int, Int))
mLinesToTripleV n = fromMLinesV n bsToIntTriple

-- output
yesnoL :: Bool -> IO ()
yesnoL cond
    | cond = putStrLn "Yes"
    | otherwise = putStrLn "No"

yesnoU :: Bool -> IO ()
yesnoU cond
    | cond = putStrLn "YES"
    | otherwise = putStrLn "NO"

-- others
strToChr :: String -> Char
strToChr [x] = x

chrToStr :: Char -> String
chrToStr x = [x]

m1 :: Int -> Int
m1 = subtract 1

toDouble :: Int -> Double
toDouble = fromIntegral

toInt :: Double -> Int
toInt = floor

sqToList :: SQ.Seq a -> [a]
sqToList sq =
    case SQ.viewl sq of
        l SQ.:< sq' -> l : sqToList sq'
        SQ.EmptyL -> []


{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE TypeSynonymInstances #-}

import           Control.Applicative
import           Control.DeepSeq
import           Control.Monad
import           Control.Monad.ST
import qualified Data.Array                  as A
import qualified Data.Array.IArray           as IA
import qualified Data.Array.IO               as AI
import qualified Data.Array.MArray           as MA
import qualified Data.Array.ST               as STA
import qualified Data.Array.Unboxed          as AU
import           Data.Bits
import qualified Data.ByteString.Char8       as BS
import           Data.Char
import qualified Data.Graph                  as G
import           Data.Int
import qualified Data.IntMap                 as IM
import qualified Data.IntSet                 as IS
import           Data.List
import qualified Data.Map.Strict             as M
import           Data.Maybe
import           Data.Ord
import qualified Data.Sequence               as SQ
import qualified Data.Set                    as S
import           Data.Time
import qualified Data.Tree                   as T
import qualified Data.Vector                 as V
import qualified Data.Vector.Mutable         as VM
import qualified Data.Vector.Unboxed         as VU
import qualified Data.Vector.Unboxed.Mutable as VUM

readInt :: IO [Int]
readInt = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine

readInts :: Int -> IO [[Int]]
readInts n = replicateM n readInt

readInteger :: IO [Integer]
readInteger = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine

readIntegers :: Int -> IO [[Integer]]
readIntegers n = replicateM n readInteger

readString :: IO [String]
readString = map BS.unpack . BS.words <$> BS.getLine

readStrings :: Int -> IO [[String]]
readStrings n = replicateM n <$> readString

toPair :: [a] -> (a, a)
toPair [x, y] = (x, y)

count :: Eq a => a -> [a] -> Int
count a as = length $ filter (== a) as

put :: Show a => a -> IO ()
put = putStr . show

putLn :: Show a => a -> IO ()
putLn = print

putList :: Show a => [a] -> IO ()
putList [n] = put n
putList (n:ns) = do
  put n
  putStr " "
  putList ns

putStrList :: [String] -> IO ()
putStrList [n] = putStr n
putStrList (n:ns) = do
  putStr n
  putStr " "
  putStrList ns

main = do
  s <- getLine
  put $ '1' `count` s


module Main (main) where

import qualified Data.ByteString.Char8     as C8
import           Data.Maybe

main :: IO ()
main = do
  [n] <- readInts
  print . showAnswer $ solve n

type Input  = (Int)
type Output = Int

solve :: Input -> Output
solve = length . filter (=='1') . show

showAnswer :: Output -> Answer
showAnswer = Number

-- utils
readInts :: IO [Int]
readInts = map (fst . fromJust . C8.readInt) . C8.words <$> C8.getLine

data Answer
  = YesNo Bool
  | YESNO Bool
  | AB Bool
  | Number Int
  | Compare Ordering

instance Show Answer where
  show (YesNo b)   = if b then "Yes" else "No"
  show (YESNO b)   = if b then "YES" else "NO"
  show (AB b)      = if b then "A"   else "B"
  show (Number i)  = show i
  show (Compare o)
    | o == EQ = "="
    | o == LT = "<"
    | o == GT = ">"


main :: IO ()
main = do
    result <- (length . filter (== '1')) <$> getLine
    print result


import Data.Char

main = do
    t <- getLine
    let a = sum $ map digitToInt t
    putStrLn $ show a


main = do
--  ns <- fmap (fmap (read :: String -> Int) . words) . lines <$> getContents
--  n <- fmap (read :: String -> Int) . words <$> getLine
  n <- getLine
  let c = length $ filter (\x ->  x == '1') n
  putStrLn $ show c


main = do
    x <- getLine
    print $ length $ filter (=='1') x


main = do
  s <- getLine
  print . sum $ map (\c -> if c == '1' then 1 else 0) s


main = getLine >>= print . length . filter (=='1')


import Data.Char
main = print =<< sum . map digitToInt <$> getLine


main :: IO ()
main = do
  str <- getLine
  putStrLn $ show $ f str '1'
  where
    f :: String -> Char -> Int
    f [] _ = 0
    f (x:xs) needle = if x == needle then 1 + f xs needle else 0 + f xs needle


import Data.List

main = do
    s <- getLine
    print $ length $ filter (=='1') s


main = getLine >>= print.solve

solve :: String -> Int
solve [] = 0
solve (a:x)
	| a == '1' = 1 + solve x
    | otherwise = solve x


import Data.Char

main = print . sum . map digitToInt =<< getLine


main = interact $ (++ "\n") . show . length . filter (== '1') . head . lines


{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as B
import Text.Printf

readInt = ( readLn :: IO Int )
readInts = map ( read :: String -> Int ) . words <$> getLine

getList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

main = getLine >>= print . length . filter ( == '1' )


--{-# LANGUAGE BangPatterns #-}
--{-# LANGUAGE ScopedTypeVariables #-}
--{-# LANGUAGE FlexibleContexts #-}
--{-# LANGUAGE ViewPatterns #-}
--{-# LANGUAGE OverloadedStrings #-}
--{-# LANGUAGE Strict #-}
--{-# LANGUAGE NumericUnderscores #-}
--{-# LANGUAGE BlockArguments #-}
--{-# LANGUAGE MultiWayIf #-}

import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.ByteString.Char8 as BC
import qualified Data.Map as MP
import qualified Data.Map.Strict as MPS
import qualified Data.Set as ST
import qualified Data.Sequence as SQ
import Data.Array
-- import Data.Array.Unboxed
-- import Data.Array.ST
import Data.Array.IO
import Data.Maybe
import Data.Ord
import Data.Ratio
import Data.Char
import Data.Bits
import Data.List
import Data.Tuple
import Data.Functor
import Data.IORef
import Data.STRef
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Control.Monad.State.Strict
import Debug.Trace
-- import qualified Data.Vector.Algorithms.Merge as VAM
-- import qualified Data.Heap as HP
-- import Numeric.Extra
-- import Data.Tuple.Extra
-- import Data.List.Extra

--------------------------------------------------------------------------
f :: Char -> Char -> Bool
f a b = (a==b) || (a=='?')

make :: String -> String -> Int -> Maybe String -> Int -> Maybe String
make xs ys d acc i
    | cond =
        case acc of
            Just a -> Just $ min a stu
            Nothing -> Just stu
    | otherwise = acc
    where
        l = length ys
        s = take i xs
        t = take l $ drop i xs
        u = drop (l+i) xs
        cond = and $ zipWith f t ys
        stu = map (\c -> if c == '?' then 'a' else c) $ reverse $ s ++ ys ++ u

solve :: String -> String -> String
solve xs ys =
    case res of
        Just x -> x
        Nothing -> "UNRESTORABLE"
    where
        d = length xs - length ys
        res = foldl' (make xs ys d) Nothing [0..d]

main = do
    xs <- reverse <$> str
    ys <- reverse <$> str
    putStrLn $ solve xs ys
--------------------------------------------------------------------------

-- Input Util
int :: IO Int
int = BC.getLine >>= return . bsToInt

double :: IO Double
double = BC.getLine >>= return . bsToDouble

str :: IO String
str = BC.getLine >>= return . BC.unpack

strBS :: IO BC.ByteString
strBS = BC.getLine

-- convert
bsToInt :: BC.ByteString -> Int
bsToInt = fst . fromJust . BC.readInt

bsToDouble :: BC.ByteString -> Double
bsToDouble = read . BC.unpack

bsToIntTuple :: BC.ByteString -> (Int, Int)
bsToIntTuple bs = (a,b)
    where
        Just (a,bs') = parseInt bs
        Just (b,_) = parseInt bs'

bsToIntTriple :: BC.ByteString -> (Int, Int, Int)
bsToIntTriple bs = (a,b,c)
    where
        Just (a,bs') = parseInt bs
        Just (b,bs'') = parseInt bs'
        Just (c,_) = parseInt bs''

parseInt :: BC.ByteString -> Maybe (Int, BC.ByteString)
parseInt = BC.readInt . BC.dropWhile isSpace

-- single line
fromSLineL :: (BC.ByteString -> a) -> IO [a]
fromSLineL f = strBS >>= return . map f . BC.words

-- from single line to List / VU.Vector
sLineToIntL :: IO [Int]
sLineToIntL = fromSLineL bsToInt

sLineToDoubleL :: IO [Double]
sLineToDoubleL = fromSLineL bsToDouble

sLineToStrL :: IO [String]
sLineToStrL = fromSLineL BC.unpack

sLineToStrBSL :: IO [BC.ByteString]
sLineToStrBSL = fromSLineL id

sLineToIntV :: Int -> IO (VU.Vector Int)
sLineToIntV n = BC.getLine >>= return . VU.unfoldrN n parseInt

sLineToDoubleV :: IO (VU.Vector Double)
sLineToDoubleV = BC.getLine >>= return . VU.fromList . map bsToDouble . BC.words

-- multiple lines
fromMLinesL :: Int -> (BC.ByteString -> a) -> IO [a]
fromMLinesL n f = replicateM n (strBS >>= return . f)

fromMLinesV :: VU.Unbox a => Int -> (BC.ByteString -> a) -> IO (VU.Vector a)
fromMLinesV n f = VU.replicateM n (strBS >>= return . f)

-- from multiple lines to List / VU.Vector
mLinesToIntL :: Int -> IO [Int]
mLinesToIntL n = fromMLinesL n bsToInt

mLinesToDoubleL :: Int -> IO [Double]
mLinesToDoubleL n = fromMLinesL n bsToDouble

mLinesToStrL :: Int -> IO [String]
mLinesToStrL n = fromMLinesL n BC.unpack

mLinesToStrBSL :: Int -> IO [BC.ByteString]
mLinesToStrBSL n = fromMLinesL n id

mLinesToTupleL :: Int -> IO [(Int, Int)]
mLinesToTupleL n = fromMLinesL n bsToIntTuple

mLinesToTripleL :: Int -> IO [(Int, Int, Int)]
mLinesToTripleL n = fromMLinesL n bsToIntTriple

mLinesToIntV :: Int -> IO (VU.Vector Int)
mLinesToIntV n = fromMLinesV n bsToInt

mLinesToDoubleV :: Int -> IO (VU.Vector Double)
mLinesToDoubleV n = fromMLinesV n bsToDouble

mLinesToTupleV :: Int -> IO (VU.Vector (Int, Int))
mLinesToTupleV n = fromMLinesV n bsToIntTuple

mLinesToTripleV :: Int -> IO (VU.Vector (Int, Int, Int))
mLinesToTripleV n = fromMLinesV n bsToIntTriple

-- output
yesnoL :: Bool -> IO ()
yesnoL cond
    | cond = putStrLn "Yes"
    | otherwise = putStrLn "No"

yesnoU :: Bool -> IO ()
yesnoU cond
    | cond = putStrLn "YES"
    | otherwise = putStrLn "NO"

-- others
strToChr :: String -> Char
strToChr [x] = x

chrToStr :: Char -> String
chrToStr x = [x]

m1 :: Int -> Int
m1 x = subtract 1 x

toDouble :: Int -> Double
toDouble x = fromIntegral x

toInt :: Double -> Int
toInt x = floor x

sqToList :: SQ.Seq a -> [a]
sqToList sq =
    case SQ.viewl sq of
        SQ.EmptyL -> []
        x SQ.:< sq' -> x : sqToList sq'

Score : 300 points

Problem Statement

E869120 found a chest which is likely to contain treasure.

However, the chest is locked. In order to open it, he needs to enter a string S consisting of lowercase English letters.

He also found a string S', which turns out to be the string S with some of its letters (possibly all or none) replaced with ?.

One more thing he found is a sheet of paper with the following facts written on it:

Condition 1: The string S contains a string T as a contiguous substring.

Condition 2: S is the lexicographically smallest string among the ones that satisfy Condition 1.

Print the string S.

If such a string does not exist, print UNRESTORABLE.

Constraints

1 \leq |S'|, |T| \leq 50

S' consists of lowercase English letters and ?.

T consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T'

Output

Print the string S.

If such a string does not exist, print UNRESTORABLE instead.

Sample Input 1

?tc????
coder

Sample Output 1

atcoder

There are 26 strings that satisfy Condition 1: atcoder, btcoder, ctcoder,..., ztcoder.
Among them, the lexicographically smallest is atcoder, so we can say S = atcoder.

Sample Input 2

??p??d??
abc

Sample Output 2

UNRESTORABLE

There is no string that satisfies Condition 1, so the string S does not exist.


{-# LANGUAGE OverloadedStrings #-}

import qualified Data.ByteString.Char8 as B
import Data.List

solve :: B.ByteString -> B.ByteString -> B.ByteString -> B.ByteString
solve s t acc
    | B.null s = "UNRESTORABLE"
    | lt /= ls = "UNRESTORABLE"
    | res = B.append (conv ds) $ B.append (B.reverse t) (conv acc)
    | otherwise = solve (B.tail s) t (B.cons (B.head s) acc)
    where
        res = and $ B.zipWith search ts t
        ts = B.take lt s
        ds = B.drop lt s
        lt = B.length t
        ls = B.length ts
        search a b
            | a == '?' = True
            | a == b = True
            | otherwise = False
        conv xs = B.foldl' (\acc x -> if x == '?' then B.cons 'a' acc else B.cons x acc) "" xs

main = do
    s <- B.getLine
    t <- B.getLine
    B.putStrLn $ solve (B.reverse s) (B.reverse t) ""


main = do
  s <- getLine :: IO String
  t <- getLine :: IO String
  let f = find s t 0 []
  let rsl = if null f
         then "UNRESTORABLE"
         else minimum $ [remake s t i | i<-f]
  putStrLn rsl

find :: String -> String -> Int -> [Int] -> [Int]
find s t i xs
  | length s < lt = xs
  | complete || contain || allq = find (tail s) t (i+1) (i:xs)
  | otherwise = find (tail s) t (i+1) xs
    where
      lt = length t
      taken = take lt s
      contain = or $ zipWith (==) t taken
      allq = taken == (replicate lt '?')
      complete = taken == t

remake :: String -> String -> Int -> String
remake s t i = (replace prev) ++ t ++ (replace front)
  where
    prev = take i s
    front = drop (length prev+length t) s
    replace :: String -> String
    replace [] = []
    replace (x:xs)
      | x == '?' = 'a' : replace xs
      | otherwise = x : replace xs


main :: IO ()
main = do
  s' <- getLine
  t <- getLine
  putStrLn $ solve s' t

solve :: String -> String -> String
solve s' t = let ans = filter (isConvertible s') $ candidates s' t
             in if null ans
                then "UNRESTORABLE"
                else toAns . last $ ans

toAns [] = []
toAns (s:ss)
  | s == '?' = 'a':toAns ss
  | otherwise = s:toAns ss

isConvertible :: String -> String -> Bool
isConvertible s candidate = all (\(x,y) -> x == y || x == '?') $ zip s candidate

candidates :: String -> String -> [String]
candidates s' t = encode s' t 0
encode :: String -> String -> Int -> [String]
encode s' t i
  | slength < tlength + i = []
  | otherwise = (top ++ t ++ bottom):encode s' t (i+1)
  where
    slength = length s'
    tlength = length t
    (top, middle) = splitAt i s'
    (_, bottom) = splitAt tlength middle


my_equal::Char->Char->Bool
my_equal c d = case (c,d) of
              ('?',_) -> True
              (_,'?') -> True
              (a,b)   -> a==b

try_gen::String->String->Maybe String
try_gen rest   []      = Just rest
try_gen []     (y:rest)  = Nothing
try_gen (x:xs) (y:ys)  = if my_equal x y then case try_gen xs ys of
                                                Nothing   -> Nothing
                                                Just rest -> Just (y:rest)
                                         else Nothing

total_case::String->String->[Maybe String]
total_case [] t = []
total_case (s:ss) t = (try_gen (s:ss) t):(map (\x -> case x of
                                                      Nothing -> Nothing
                                                      Just st -> Just (s:st)) (total_case ss t))

solver::String->String->String
solver s t = let ls =  filter (Nothing/=) (total_case s t) in
             case ls of
                []        -> "UNRESTORABLE"
                otherwise -> let Just str = last ls in map (\c-> if c =='?' then 'a' else c) str

main::IO()
main=do
  s<-getLine
  t<-getLine
  putStr (solver s t)
  putStr "\n"


main :: IO ()
main = do
  s' <- getLine
  t <- getLine
  putStrLn $ restore s' t

restore :: String -> String -> String
restore s' t =
  _restoreLoop (length s' - length t)
  where
    _restoreLoop :: Int -> String
    _restoreLoop start
      | start < 0 = "UNRESTORABLE"
      | otherwise = if isContained s' t start
                      then
                        let s'' = take start s' ++ t ++ drop (start + length t) s'
                        in map (replace 'a') s''
                      else
                        _restoreLoop (start - 1)

isContained :: String -> String -> Int -> Bool
isContained s' t start =
  all (\i -> t!!i == s'!!(start + i) || s'!!(start + i) == '?') [0..length t　- 1]

replace :: Char -> Char -> Char
replace c '?' = c
replace _ c0 = c0


import Data.List

main = do
    s' <- getLine
    t  <- getLine
    let s = restore (reverse s') (reverse t)
    putStrLn $ if canRestore s' t
        then reverse $ map (\c->if c=='?' then 'a' else c) s
        else "UNRESTORABLE"

restore s' t = let
    s = restore' s' t
    in if s == s' then s
                  else restore s t

canRestore [] _ = False
canRestore (s:ss) key = canReplace (s:ss) key || canRestore ss key

restore' [] _ = []
restore' s' t = if canReplace s' t
 then t ++ drop (length t) s'
 else head s' : restore' (tail s') t

canReplace _ [] = True
canReplace [] _ = False
canReplace (x:xs) (y:ys) = (x=='?' || y=='?' || x==y) && canReplace xs ys


main = do
    s' <- getLine
    t  <- getLine
    let s = restore s' t
    putStrLn $ if s' /= s then map (\c->if c=='?' then 'a' else c) s
                          else "UNRESTORABLE"

restore s' t = let
    s = restore' s' t
    in if s == s' then s else restore' s t

restore' [] _ = []
restore' s' t = if canReplace s' t && length s' >= length t
 then t ++ drop (length t) s'
 else head s' : restore' (tail s') t
 where
 canReplace _ [] = True
 canReplace [] _ = False
 canReplace (x:xs) (y:ys) = (x=='?' || x==y) && canReplace xs ys


newtype FazzyChar   = FazzyChar {getFazzyChar :: Char}
type FazzyString = [FazzyChar]

instance Eq FazzyChar where
    FazzyChar '?' == FazzyChar _   = True
    FazzyChar _   == FazzyChar '?' = True
    FazzyChar c   == FazzyChar c'  = c == c'

main :: IO ()
main = do
    s <- getLine :: IO String
    t <- fromString <$> getLine :: IO FazzyString
    let str = map getFazzyChar $ restore (fromString s) t
    putStrLn $ if s == str then "UNRESTORABLE" else minString str

fromString :: String -> FazzyString
fromString = map FazzyChar

minString :: String -> String
minString = map (\c -> if c == '?' then 'a' else c)

restore s k = let
    ans = restore' s k
    in if ans == s then ans else restore ans k

restore' :: FazzyString -> FazzyString -> FazzyString
restore' [] _ = []
restore' fs key = if canConcertaion fs key
    then key ++ drop (length key) fs
    else head fs : restore' (tail fs) key
    where
    canConcertaion _ [] = True
    canConcertaion [] _ = False
    canConcertaion (f:fs) (k:key) = (f == k) && canConcertaion fs key


import Control.Applicative
import Control.Monad
import Data.List
import Data.Char
strToInt s = (read :: String -> Int) s

main :: IO ()
main = do
    -- 文字列の入力
    ss <- getLine
    ts <- getLine
    -- 出力
    putStrLn $ solve ss ts

isPre :: String -> String -> Bool
isPre [] _ = False
isPre _ [] = True
isPre (s:ss) (t:ts) = if s == '?' || s == t then isPre ss ts else False

replace :: String -> Int -> String -> String
replace ss k ts = map (\c -> if c == '?' then 'a' else c) (present ++ ts ++ latter)
    where
        present = take (length ss - k) ss
        latter  = drop (length present + length ts) ss

solve :: String -> String -> String
solve ss ts = if null cands then "UNRESTORABLE" else replace ss (length $ head cands) ts
    where
        cands = dropWhile (not . flip isPre ts) (tails ss)


import Control.Applicative
import Control.Monad
import Data.List
import Data.Char
strToInt s = (read :: String -> Int) s

main :: IO ()
main = do
    -- 文字列の入力
    ss <- getLine
    ts <- getLine
    -- 出力
    putStrLn $ solve ss ts

isPre :: String -> String -> Bool
isPre [] _ = False
isPre _ [] = True
isPre (s:ss) (t:ts) = if s == '?' || s == t then isPre ss ts else False

replace :: String -> Int -> String -> String
replace ss k ts = map (\c -> if c == '?' then 'a' else c) (take (length ss - k) ss ++ ts)

solve :: String -> String -> String
solve ss ts = if null cands then "UNRESTORABLE" else replace ss (length $ head cands) ts
    where
        cands = dropWhile (not . flip isPre ts) (tails ss)


import Data.Maybe
import Data.List

data Dubious a = Fixed a | Unfixed deriving Show

main = do
  s <- getLine >>= return . (map (\x -> if x=='?' then Unfixed else (Fixed x))) :: IO [Dubious Char]
  t <- getLine >>= return . (map (\x -> Fixed x)) :: IO [Dubious Char]

  let
    lent = length t
    lens = length s

  putStrLn $ func3 (sort (map (map func2) (catMaybes [func s t i | i<-[0..lens-lent]])))

  where
    equalDubious :: Eq a => Dubious a -> Dubious a -> Bool
    equalDubious Unfixed y = True
    equalDubious x Unfixed = True
    equalDubious (Fixed x) (Fixed y) = if x/=y then False else True

    fix :: Eq a => Dubious a -> Dubious a -> Dubious a
    fix Unfixed (Fixed a) = Fixed a
    fix (Fixed a) Unfixed = Fixed a
    fix Unfixed Unfixed = Unfixed
    fix (Fixed a) (Fixed b) = if a/=b then Unfixed else Fixed a

    func s t i = if and (zipWith equalDubious t s') then (Just r) else Nothing
      where
        lt = length t
        ls = length s
        s' = take lt (drop i s)
        r = zipWith fix s ((take i (repeat Unfixed)) ++ t ++ (take (ls-i-lt) (repeat Unfixed)))

    func2 :: Dubious Char -> Char
    func2 (Fixed x) = x
    func2 Unfixed = 'a'

    func3 :: [String] -> String
    func3 [] = "UNRESTORABLE"
    func3 xs = head xs


module Main where
import Control.Monad
import Control.Applicative
import Data.Maybe
import Data.List
import qualified Text.Printf
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString as BC

------------------------------------------

main :: IO ()
main = do
  s' <- getLine
  trg <- getLine
  let find [] = []
      find xx@(x:xs) =
        case match xx of
          Nothing -> map (x':) (find xs)
          Just xx' -> xx' : map (x':) (find xs)
        where x' = if x == '?' then 'a' else x

      match str = go trg str
        where go [] ys = Just $ trg ++ fillA ys
              go _ [] = Nothing
              go (x:xs) (y:ys) = guard (y == '?' || x == y) >> go xs ys

              fillA = map (\x -> if x == '?' then 'a' else x)

      cands = find s'

  case sort cands of
    []    -> putStrLn "UNRESTORABLE"
    (x:_) -> putStrLn x

------------------------------------------

{- Int input -}

parseInt :: BC.ByteString -> Int
parseInt = fst . fromJust . BC.readInt

parseInts :: BC.ByteString -> [Int]
parseInts = map parseInt <$> BC.words

readInt :: IO Int
readInt = parseInt <$> BC.getLine

readInts :: IO [Int]
readInts = parseInts <$> BC.getLine

{- Double Formatting -}

doubleFmt :: Double -> String
doubleFmt = Text.Printf.printf "%.12f"


import Control.Monad
import Data.Monoid
import Data.List

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

f s t 0
    | slen < tlen = Nothing
    | any (\(x, y) -> x/='?' && x/=y) pairs = Nothing
    | otherwise = Just (t ++ (map g $ drop tlen s))
    where
        slen = length s
        tlen = length t
        pairs = zip s t
        g c = if c=='?' then 'a' else c
f [] t n = Nothing
f (c:s) t n = (c':) <$> f s t (n-1)
    where c' = if c=='?' then 'a' else c

main = do
    s' <- getLine
    t <- getLine
    putStrLn $ maybe "UNRESTORABLE" id $ getLast $ foldMap Last $ map (\n -> f s' t n) [0..(length s')]


import Data.Bool
import Data.Maybe
import Data.List

main = putStrLn . solve . lines =<< getContents

solve :: [String] -> String
solve [s,t] = maybe "UNRESTORABLE" (rpl s t) $ rfnd s t (length s - length t)

rpl s t i = f ++ t ++ b
    where
        f = map rpl' $ take i s
        b = map rpl' $ drop (length t + i) s

rpl' '?' = 'a'
rpl' x = x

rfnd s t i
    | i < 0 = Nothing
    | otherwise = bool (rfnd s t (i-1)) (return i) $ isMatched s' t
    where
        s' = drop i s

isMatched s t = and $ zipWith (\s' t' -> s' == '?' || s' == t') s t


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

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

f s t 0
    | slen < tlen = Nothing
    | any (\(x, y) -> x/='?' && x/=y) pairs = Nothing
    | otherwise = Just (t ++ drop tlen s)
    where
        slen = length s
        tlen = length t
        pairs = zip s t
f [] t n = Nothing
f (c:s) t n = (c':) <$> f s t (n-1)
    where c' = if c=='?' then 'a' else c

main = do
    s' <- getLine
    t <- getLine
    let list = sort $ catMaybes $ map (\n -> f s' t n) [1..(length s')]
    putStrLn $ if null list then "UNRESTORABLE" else head list


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, BinaryLiterals, CPP, DerivingStrategies  #-}
{-# LANGUAGE DerivingVia, FlexibleContexts, FlexibleInstances       #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, KindSignatures, LambdaCase #-}
{-# LANGUAGE MagicHash, MultiParamTypeClasses, MultiWayIf           #-}
{-# LANGUAGE NumericUnderscores, OverloadedStrings, PatternSynonyms #-}
{-# LANGUAGE RankNTypes, RecordWildCards, ScopedTypeVariables       #-}
{-# LANGUAGE StandaloneDeriving, TupleSections, TypeApplications    #-}
{-# LANGUAGE TypeFamilies, TypeInType, UnboxedTuples, ViewPatterns  #-}

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.Reader
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Data.Bifunctor
import           Data.Bool
import qualified Data.ByteString                   as B
import qualified Data.ByteString.Builder           as B
import qualified Data.ByteString.Char8             as C
import qualified Data.ByteString.Internal          as B
import qualified Data.ByteString.Unsafe            as B
import           Data.Char
import qualified Data.Foldable                     as F
import           Data.Function
import           Data.Functor.Identity
import qualified Data.IntMap.Strict                as IM
import qualified Data.IntSet                       as IS
import qualified Data.List                         as L
import qualified Data.Map.Strict                   as M
import           Data.Monoid
import           Data.Ord
import           Data.Primitive
import           Data.Proxy
import           Data.Ratio
import           Data.Semigroup
import qualified Data.Set                          as S
import           Data.Tuple
import qualified Data.Vector                       as V
import qualified Data.Vector.Algorithms.Intro      as Intro
import qualified Data.Vector.Fusion.Stream.Monadic as MS
import qualified Data.Vector.Fusion.Bundle.Monadic as MB
import           Data.Vector.Fusion.Util
import qualified Data.Vector.Generic               as G
import qualified Data.Vector.Generic.Mutable       as GM
import qualified Data.Vector.Mutable               as VM
import qualified Data.Vector.Primitive             as P
import qualified Data.Vector.Primitive.Mutable     as PM
import qualified Data.Vector.Unboxed               as U
import qualified Data.Vector.Unboxed.Mutable       as UM
import           Debug.Trace
import           Foreign                           hiding (void)
import           GHC.Exts
import           GHC.TypeLits
import           System.IO
import           Unsafe.Coerce

#define MOD 1000000007

main :: IO ()
main = do
    [h, w] <- map read.words <$> getLine
    cs <- U.unfoldrN (h*w) (runParser char) . C.filter (not.isSpace)
        <$> C.getContents
    let res = solve h w cs
    putStr$unlines[U.toList $ U.slice (i * w) w res|i<-[0..h-1]]

conv '.' = '0'
conv c = c

solve :: Int -> Int -> U.Vector Char -> U.Vector Char
solve h w (U.map conv -> mat0) = U.create $ do
    mat <- U.thaw mat0
    rep h $ \i -> do
        rep w $ \j -> do
            mij <- UM.unsafeRead mat (ix i j)
            when (mij == '#') $ do
                neighbor8 i j $ \i' j' -> when (inGrid h w i' j' ) $ do
                    mij' <- UM.unsafeRead mat (ix i' j')
                    when (mij' /= '#') $ do
                        UM.unsafeModify mat succ (ix i' j')
    return mat
  where
    ix x y = x * w + y
    {-# INLINE ix #-}

inGrid :: Int -> Int -> Int -> Int -> Bool
inGrid h w x y = 0 <= x && x < h && 0 <= y && y < w
{-# INLINE inGrid #-}

neighbor4 :: (Applicative f) => Int -> Int -> (Int -> Int -> f ()) -> f ()
neighbor4 x y f = f (x - 1) y *> f x (y - 1) *> f x (y + 1) *> f (x + 1) y
{-# INLINE neighbor4 #-}

neighbor8 :: (Applicative f) => Int -> Int -> (Int -> Int -> f ()) -> f ()
neighbor8 x y f
    =  f (x - 1) (y - 1) *> f (x - 1) y *> f (x - 1) (y + 1)
    *> f (x    ) (y - 1)                *> f (x    ) (y + 1)
    *> f (x + 1) (y - 1) *> f (x + 1) y *> f (x + 1) (y + 1)
{-# INLINE neighbor8 #-}

-------------------------------------------------------------------------------
-- Utils
-------------------------------------------------------------------------------
rep :: (Monad m) => Int -> (Int -> m ()) -> m ()
rep n = flip MS.mapM_ (stream 0 n)
{-# INLINE rep #-}
rev :: (Monad m) => Int -> (Int -> m ()) -> m ()
rev !n = flip MS.mapM_ (streamR 0 n)
{-# INLINE rev #-}
stream :: (Monad m) => Int -> Int -> MS.Stream m Int
stream !l !r = MS.Stream step l where { step x | x < r = return $ MS.Yield x (x + 1) | otherwise = return MS.Done; {-# INLINE [0] step #-}}
{-# INLINE [1] stream #-}
streamR :: (Monad m) => Int -> Int -> MS.Stream m Int
streamR !l !r = MS.Stream step (r - 1) where { step x | x >= l = return $ MS.Yield x (x - 1) | otherwise = return MS.Done; {-# INLINE [0] step #-}}
{-# INLINE [1] streamR #-}
stream' :: (Monad m) => Int -> Int -> Int -> MS.Stream m Int
stream' !l !r !d = MS.Stream step l where { step x | x < r = return $ MS.Yield x (x + d) | otherwise = return MS.Done; {-# INLINE [0] step #-}}
{-# INLINE [1] stream' #-}
infixl 8 `shiftRL`, `unsafeShiftRL`
shiftRL :: Int -> Int -> Int
shiftRL = unsafeShiftRL
{-# INLINE shiftRL #-}
unsafeShiftRL :: Int -> Int -> Int
unsafeShiftRL (I# x#) (I# i#) = I# (uncheckedIShiftRL# x# i#)
{-# INLINE unsafeShiftRL #-}
type Parser a = StateT C.ByteString Maybe a
runParser :: Parser a -> C.ByteString -> Maybe (a, C.ByteString)
runParser = runStateT
{-# INLINE runParser #-}
int :: Parser Int
int = coerce $ C.readInt . C.dropWhile isSpace
{-# INLINE int #-}
int1 :: Parser Int
int1 = fmap (subtract 1) int
{-# INLINE int1 #-}
char :: Parser Char
char = coerce C.uncons
{-# INLINE char #-}
byte :: Parser Word8
byte = coerce B.uncons
{-# INLINE byte #-}
skipSpaces :: Parser ()
skipSpaces = modify' (C.dropWhile isSpace)
{-# INLINE skipSpaces #-}
lowerBoundM :: (Monad m) => Int -> Int -> (Int -> m Bool) -> m Int
lowerBoundM low high p = go low high where { go !low !high | high <= low = return high | otherwise = p mid >>= bool (go (mid + 1) high) (go low mid) where { mid = low + unsafeShiftRL (high - low) 1}}
{-# INLINE lowerBoundM #-}
upperBoundM :: (Monad m) => Int -> Int -> (Int -> m Bool) -> m Int
upperBoundM low high p = do { flg <- p high; if flg then return high else subtract 1 <$!> lowerBoundM low high (fmap not . p)}
{-# INLINE upperBoundM #-}
lowerBound :: Int -> Int -> (Int -> Bool) -> Int
lowerBound low high p = runIdentity (lowerBoundM low high (return . p))
{-# INLINE lowerBound #-}
upperBound :: Int -> Int -> (Int -> Bool) -> Int
upperBound low high p = runIdentity (upperBoundM low high (return . p))
{-# INLINE upperBound #-}

Score : 200 points

Problem Statement

You are given an H × W grid.

The squares in the grid are described by H strings, S_1,...,S_H.

The j-th character in the string S_i corresponds to the square at the i-th row from the top and j-th column from the left (1 \leq i \leq H,1 \leq j \leq W).

. stands for an empty square, and # stands for a square containing a bomb.

Dolphin is interested in how many bomb squares are horizontally, vertically or diagonally adjacent to each empty square.

(Below, we will simply say "adjacent" for this meaning. For each square, there are at most eight adjacent squares.)

He decides to replace each . in our H strings with a digit that represents the number of bomb squares adjacent to the corresponding empty square.

Print the strings after the process.

Constraints

1 \leq H,W \leq 50

S_i is a string of length W consisting of # and ..

Input

Input is given from Standard Input in the following format:

H W
S_1
:
S_H

Output

Print the H strings after the process.

The i-th line should contain a string T_i of length W, where the j-th character in T_i corresponds to the square at the i-th row from the top and j-th row from the left in the grid (1 \leq i \leq H, 1 \leq j \leq W).

Sample Input 1

3 5
.....
.#.#.
.....

Sample Output 1

11211
1#2#1
11211

For example, let us observe the empty square at the first row from the top and first column from the left.

There is one bomb square adjacent to this empty square: the square at the second row and second column.

Thus, the . corresponding to this empty square is replaced with 1.

Sample Input 2

3 5
#####
#####
#####

Sample Output 2

#####
#####
#####

It is possible that there is no empty square.

Sample Input 3

6 6
#####.
#.#.##
####.#
.#..#.
#.##..
#.#...

Sample Output 3

#####3
#8#7##
####5#
4#65#2
#5##21
#4#310


import Control.Monad
import Data.Array
import qualified Data.ByteString.Char8 as BS
import Data.Maybe

readInt = fst . fromJust . BS.readInt

readIntList = map readInt . BS.words

readString = map BS.unpack . BS.words

getIntList = readIntList <$> BS.getLine

getString = readString <$> BS.getLine

getNString n = map readString <$> replicateM n BS.getLine

getNeibor :: Int -> Int -> Int -> Int -> [[Int]]
getNeibor w' h' w h = do
  let hs  = [h' - 1, h', h' + 1]
  let ws  = [w' - 1, w', w' + 1]
  filter (\x -> x /= [h', w']) (sequence [hs, ws])

sumBomb :: Array (Int, Int) Char -> [[Int]] -> Int
sumBomb sss [] = 0
sumBomb sss (ns : nss)
  | rc == '#' = 1 + sumBomb sss nss
  | otherwise = sumBomb sss nss
  where
    rc = sss ! (head (ns), last (ns))

calc sss h w i = do
  let i' = i + 1
  let h' = i' `div` w
  let w' = i' `mod` w
  let w''
        | w' == 0 = w
        | otherwise = w'
  let h''
        | w' == 0 = h'
        | otherwise = h' + 1
  if sss ! (h'', w'') == '#'
    then putStr "#"
    else do
      let nss = getNeibor w'' h'' w h
      putStr $ show (sumBomb sss nss)
  if w'' == w
    then do
      putStr "\n"
      when (i' /= h * w) $ calc sss h w (i + 1)
    else calc sss h w (i + 1)

main = do
  [h, w] <- getIntList
  sss <- getNString h
  let dots = replicate (w + 2) "."
  let sss' = concat (dots ++ (map (\x -> "." ++ x ++ ".") (map head sss)) ++ dots)
  let sss'' = listArray ((0, 0), (h + 1, w + 1)) sss'
  calc sss'' h w 0


import Control.Monad
import Data.Array
import qualified Data.ByteString.Char8 as BS
import Data.Maybe

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
readString = map BS.unpack . BS.words

getIntList = readIntList <$> BS.getLine
getString = readString <$> BS.getLine
getNString n = map readString <$> replicateM n BS.getLine

getNeibor :: Int -> Int -> Int -> Int -> [[Int]]
getNeibor w' h' w h = do
  let hs
        | h' == 1 = [h', h' + 1]
        | h' == h = [h' - 1, h']
        | otherwise = [h' - 1, h', h' + 1]
  let ws
        | w' == 1 = [w', w' + 1]
        | w' == w = [w' - 1, w']
        | otherwise = [w' - 1, w', w' + 1]
  filter (\x -> x /= [h', w']) (sequence [hs, ws])

sumBomb :: Array (Int, Int) Char -> [[Int]] -> Int
sumBomb sss [] = 0
sumBomb sss (ns : nss)
  | rc == '#' = 1 + sumBomb sss nss
  | otherwise = sumBomb sss nss
  where
    rc = sss ! (head (ns), last (ns))

calc sss h w i = do
  let i' = i + 1
  let h' = i' `div` w
  let w' = i' `mod` w
  let w''
        | w' == 0 = w
        | otherwise = w'
  let h''
        | w' == 0 = h'
        | otherwise = h' + 1
  if sss ! (h'', w'') == '#'
    then putStr "#"
    else do
      let nss = getNeibor w'' h'' w h
      putStr $ show (sumBomb sss nss)
  if w'' == w
    then do
      putStr "\n"
      when (i' /= h * w) $ calc sss h w (i + 1)
    else calc sss h w (i + 1)

calcable :: String -> [Int]
calcable [] = []
calcable (s : ss)
  | s == '#' = 1 : calcable ss
  | otherwise = 0 : calcable ss

calcSingle :: Array Int Int -> Int -> Int -> String
calcSingle ss n' n
  | n' == (n + 1) = []
  | otherwise = v ++ calcSingle ss (n' + 1) n
  where
    v
      | ss ! n' == 1 = "#"
      | n' == 1 = show $ ss ! 2
      | n' == n = show $ ss ! (n - 1)
      | otherwise = show $ (ss ! (n' - 1)) + (ss ! (n' + 1))

putCharLn :: Char -> IO()
putCharLn c = putStrLn $ [c]

main = do
  [h, w] <- getIntList
  if h == 1
    then do
      [sss] <- getString
      if w == 1
        then if sss == "#" then putStrLn "#" else putStrLn "0"
        else do
          let sss' = calcable sss
          let sss'' = listArray (1, w) sss'
          putStrLn $ calcSingle sss'' 1 w
    else do
      if w == 1
        then do
          sss <- getNString h
          let sss' = calcable (concat (map head sss))
          let sss'' = listArray (1, h) sss'
          let result = calcSingle sss'' 1 h
          mapM_ putCharLn result
          putStr "\n"
        else do
          sss <- getNString h
          let sss' = concat (map head sss)
          let sss'' = listArray ((1, 1), (h, w)) sss'
          calc sss'' h w 0


import Data.List

main :: IO ()
main = do
  [h,w] <- map read . words <$> getLine :: IO [Int]
  l <- lines <$> getContents
  let bs = concat $ map (\g -> boms (fst g) (snd g)) $ zip [1..h] l
  let grid =  [c |i <- [1..h],
                  j <- [1..w],
                  let v = (l !! (i-1)) !! (j-1),
                  let c = if v == '#' then v else head $ show $ length $ filter (`elem` bs) $ around (i,j)]
  putStr $ aligne grid w
    where around (i,j) = [(i-1,j-1), (i-1,j), (i-1,j+1), (i,j-1), (i,j+1), (i+1,j-1), (i+1,j), (i+1,j+1)]
          boms h l = map (\i -> (h,i+1)) $ elemIndices '#' l

aligne :: String -> Int -> String
aligne [] _ = ""
aligne xs w = take w xs ++ "\n" ++ aligne (drop w xs) w


import Data.List

main :: IO ()
main = do
  [h,w] <- map read . words <$> getLine :: IO [Int]
  l <- lines <$> getContents
  let bs = concat $ map (\g -> boms (fst g) (snd g)) $ zip [1..h] l
  let grid =  [((i,j),v) | i <- [1..h], j <- [1..w], let v = (l !! (i-1)) !! (j-1)]
  putStr $ split (makeLine grid bs)  w

boms :: Int -> String -> [(Int, Int)]
boms h l = map (\i -> (h,i+1)) $ elemIndices '#' l

around :: (Int, Int) -> [(Int,Int)]
around (i,j) = [(i-1,j-1), (i-1,j), (i-1,j+1), (i,j-1), (i,j+1), (i+1,j-1), (i+1,j), (i+1,j+1)]

makeLine :: [((Int,Int),Char)] -> [(Int,Int)]-> String
makeLine [] _ = ""
makeLine (x:xs) bs
  |snd x == '#'= ['#'] ++ (makeLine xs bs)
  |otherwise =
    let number = length $ filter (`elem` bs) $ around (fst x)
      in show number ++ makeLine xs bs

split :: String -> Int -> String
split "" _ = ""
split xs w = take w xs ++ "\n" ++ split (drop w xs) w


main=print.solve.map(map read.words).lines=<<getContents
solve=sum.map f.tail
f[l,r]=r-l+1

Score : 200 points

Problem Statement

Joisino is working as a receptionist at a theater.

The theater has 100000 seats, numbered from 1 to 100000.

According to her memo, N groups of audiences have come so far, and the i-th group occupies the consecutive seats from Seat l_i to Seat r_i (inclusive).

How many people are sitting at the theater now?

Constraints

1≤N≤1000

1≤l_i≤r_i≤100000

No seat is occupied by more than one person.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
l_1 r_1
:
l_N r_N

Output

Print the number of people sitting at the theater.

Sample Input 1

1
24 30

Sample Output 1

7

There are 7 people, sitting at Seat 24,25,26,27,28,29 and 30.

Sample Input 2

2
6 8
3 3

Sample Output 2

4


import qualified Data.ByteString.Char8 as C
import Data.Vector.Unboxed
import Prelude hiding (tail)

main = C.interact $ put . sol . get
get = unfoldr (C.readInt . C.dropWhile (<'0'))
put = C.pack . show
sol = ifoldl' (\s i a -> if even i then s-a+1 else s+a) 0 . tail


import Control.Monad
main=do
 n<-readLn
 a<-replicateM n (map read.words<$>getLine)
 print(sum[(x!!1)-(x!!0)+1|x<-a])


import Control.Monad

main :: IO ()
main = do
  n <- readLn :: IO Int
  ds <- concat <$> replicateM n (map read . words <$> getLine)  :: IO [Int]
  print $ solve ds

solve :: [Int] -> Int
solve [] = 0
solve (x:y:ys) = (y-x+1) + solve ys


import Control.Monad
main = do
  n <- readLn :: IO Int
  s <- replicateM n (map read . words <$> getLine) :: IO [[Int]]
  print $ sum $ map (\x -> abs (head x - last x) + 1) s


sAdd :: [String] -> Int -> Int
sAdd [] acc = acc
sAdd src acc = sAdd (tail src) acc'
  where
    cs = words (head src)
    l = read (head cs)
    r = read (last cs)
    acc' = acc + r  + (-l) + 1

main = do
  ns <- lines <$> getContents
  putStrLn $ show $ sAdd (tail ns) 0


import Control.Applicative
import Control.Monad
import Data.List.Split

myRead :: String -> (Int, Int)
myRead s = (l, r)
    where
        [a, b] = splitOn " " s
        l = read a
        r = read b

solve :: [(Int, Int)] -> Int
solve = sum . ( map (\(l, r) -> r-l+1) )

main :: IO ()
main = do
    n <- read <$> getLine
    contents <- map myRead <$> replicateM n getLine
    print $ solve contents


module Main where

import Control.Applicative
import Control.Monad
import Data.List

main :: IO ()
main = do
    n <- readLn
    xss <- replicateM n $ fmap read . words <$> getLine :: IO [[Int]]
    let f [l, r] = r - l + 1
    print $ sum $ fmap f xss


import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as B

main = do
    n <- read <$> getLine :: IO Int
    ns <- replicateM n ((\[a,b]->(b-a)+1) . map (fst . fromJust . B.readInt) . B.words <$> B.getLine) :: IO [Int]
    print $ sum ns


import Control.Monad
import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)

main :: IO ()
main = do
    n <- fst . fromJust . B.readInt <$> B.getLine
    as <- replicateM n $ do
        [l, r] <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
        return $ r - l + 1
    print $ sum as


import Control.Monad

main :: IO ()
main = do
  n <- readLn :: IO Int
  rows <- replicateM n $ (map read . words) <$> getLine :: IO [[Int]]
  print =<< foldM (\acc [l, r] -> return (acc + r - l + 1)) 0 rows


main = do
  getLine
  input <- map ((\[l,r] -> (read l, read r)) . words) . lines <$> getContents :: IO [(Int, Int)]
  putStrLn . show . sum $ map (\(l, r) -> r - l + 1) input


import Data.List
import Data.Ord
import Data.Char
import Data.Ratio
import Data.Maybe

main = do
  s<-getLine
  putStrLn $maybe "None" (:[]) $lookup False $zip (elemList ['a'..'z'] s) ['a'..'z']

elemList [] _ = []
elemList (x:xs) list  = elem x list : elemList xs list

Score : 200 points

Problem Statement

You are given a string S consisting of lowercase English letters.
Find the lexicographically (alphabetically) smallest lowercase English letter that does not occur in S.
If every lowercase English letter occurs in S, print None instead.

Constraints

1 \leq |S| \leq 10^5 (|S| is the length of string S.)

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the lexicographically smallest lowercase English letter that does not occur in S.
If every lowercase English letter occurs in S, print None instead.

Sample Input 1

atcoderregularcontest

Sample Output 1

b

The string atcoderregularcontest contains a, but does not contain b.

Sample Input 2

abcdefghijklmnopqrstuvwxyz

Sample Output 2

None

This string contains every lowercase English letter.

Sample Input 3

fajsonlslfepbjtsaayxbymeskptcumtwrmkkinjxnnucagfrg

Sample Output 3

d


import Data.List
f k x = if k == fromEnum 'z' +1 then "None" else if head x == toEnum k then f (k+1) (tail x) else [toEnum k]
main=getLine>>=putStrLn.(\x-> if null x then "a" else f (fromEnum 'a') x).sort.nub


import Data.List
import Data.Maybe

main = getLine >>= putStrLn . fromMaybe "None" . fmap return . listToMaybe . map fst . dropWhile (uncurry (==)) . zip ['a'..'z'] . map head . group . sort . ('|':)


{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}

import qualified Data.ByteString.Char8 as B

main :: IO ()
main = do
    s <- map B.head . B.group . B.sort <$> B.getLine
    putStrLn $ diff s ['a'..'z']
    where
        diff [] [] = "None"
        diff (_:_) [] = "None"
        diff [] (y:_) = [y]
        diff (x:xs) (y:ys)
            | x /= y = [y]
            | otherwise = diff xs ys


{-# LANGUAGE FlexibleContexts, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)
import Text.Printf
import Debug.Trace

f [] [] = "None"
f [] (c:_) = [c]
f (c1:s1) (c2:s2) = if c1 /= c2 then [c2] else f s1 s2

main = do
  s <- map B.head . B.group . B.sort <$> B.getLine
  putStrLn $ f s "abcdefghijklmnopqrstuvwxyz"


main :: IO()
main = do
  s <- getLine
  print $ solve2 s
solve2 = solve2' ['a' .. 'z']
solve2' [] _ = "None"
solve2' (x : xs) [] = [x]
solve2' (x : xs) ys = let ys' = filter (/= x) ys in if length ys == length ys' then [x    ] else solve2' xs ys'


main = do
    s <- getLine
    putStrLn $ case filter (\c -> not $ elem c s) ['a' .. 'z'] of
        [] -> "None"
        c:_ -> c:[]


main = interact $ f 'a'

f 'z' s
  | 'z' `elem` s = "None"
  | otherwise = "z"
f c s
  | c `elem` s = f (succ c) s
  | otherwise = [c]


main :: IO ()
main = do
  s <- getLine
  let ans = [x | x <- ['a'..'z'], not ( x `elem` s)]
  if (ans == []) then putStrLn "None" else putChar $ head ans


import Control.Applicative
import qualified Data.Set as S

alphabetset = S.fromList "abcdefghijklmnopqrstuvwxyz"

solver0 s = S.toList $ S.difference alphabetset $ S.fromList s

solver s
    |length s2 == 0 = "None"
    |otherwise = (minimum s2):[]
    where
        s2 = solver0 s

main :: IO ()
main = do
    s <- getLine
    putStrLn $ solver s


import Data.List

main = do
  s <- getLine
  putStr . f $ ['a'..'z'] \\ s

f [] = "None"
f xs = [head xs]


--{-# LANGUAGE BangPatterns #-}
--{-# LANGUAGE ScopedTypeVariables #-}
--{-# LANGUAGE FlexibleContexts #-}
--{-# LANGUAGE ViewPatterns #-}
--{-# LANGUAGE OverloadedStrings #-}
--{-# LANGUAGE Strict #-}
--{-# LANGUAGE NumericUnderscores #-}
--{-# LANGUAGE BlockArguments #-}
--{-# LANGUAGE MultiWayIf #-}

import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.ByteString.Char8 as BC
import qualified Data.Map as MP
import qualified Data.Set as ST
import qualified Data.Sequence as SQ
-- import Data.Array
import Data.Array.Unboxed
-- import Data.Array.ST
-- import Data.Array.IO
import Data.Maybe
import Data.Ord
import Data.Ratio
import Data.Char
import Data.Bits
import Data.List
import Data.Tuple
import Data.Functor
import Data.IORef
import Data.STRef
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Debug.Trace
-- import qualified Data.Vector.Algorithms.Merge as VAM
-- import qualified Data.Heap as HP
-- import Numeric.Extra
-- import Data.Tuple.Extra
-- import Data.List.Extra

--------------------------------------------------------------------------
step (a,b,c) x
    | x `mod` 4 == 0 = (a+1,b,c)
    | x `mod` 2 == 0 = (a,b+1,c)
    | otherwise = (a,b,c+1)

main = do
    n <- int
    xs <- sLineToIntV n
    let
        (a,b,c) = VU.foldl' step (0,0,0) xs
        cond
            | even $ a + c = c == a
            | (odd $ a + c) && b > 0 = a >= (c+1)
            | otherwise = a >= c-1
    yesnoL $ cond || (a+b == n)
--------------------------------------------------------------------------

-- Input Util
int :: IO Int
int = BC.getLine >>= return . bsToInt

double :: IO Double
double = BC.getLine >>= return . bsToDouble

str :: IO String
str = BC.getLine >>= return . BC.unpack

strBS :: IO BC.ByteString
strBS = BC.getLine

-- convert
bsToInt :: BC.ByteString -> Int
bsToInt = fst . fromJust . BC.readInt

bsToDouble :: BC.ByteString -> Double
bsToDouble = read . BC.unpack

bsToIntTuple :: BC.ByteString -> (Int, Int)
bsToIntTuple bs = (a,b)
    where
        Just (a,bs') = parseInt bs
        Just (b,_) = parseInt bs'

bsToIntTriple :: BC.ByteString -> (Int, Int, Int)
bsToIntTriple bs = (a,b,c)
    where
        Just (a,bs') = parseInt bs
        Just (b,bs'') = parseInt bs'
        Just (c,_) = parseInt bs''

parseInt :: BC.ByteString -> Maybe (Int, BC.ByteString)
parseInt = BC.readInt . BC.dropWhile isSpace

-- single line
fromSLineL :: (BC.ByteString -> a) -> IO [a]
fromSLineL f = strBS >>= return . map f . BC.words

-- from single line to List / VU.Vector
sLineToIntL :: IO [Int]
sLineToIntL = fromSLineL bsToInt

sLineToDoubleL :: IO [Double]
sLineToDoubleL = fromSLineL bsToDouble

sLineToStrL :: IO [String]
sLineToStrL = fromSLineL BC.unpack

sLineToStrBSL :: IO [BC.ByteString]
sLineToStrBSL = fromSLineL id

sLineToIntV :: Int -> IO (VU.Vector Int)
sLineToIntV n = BC.getLine >>= return . VU.unfoldrN n parseInt

sLineToDoubleV :: IO (VU.Vector Double)
sLineToDoubleV = BC.getLine >>= return . VU.fromList . map bsToDouble . BC.words

-- multiple lines
fromMLinesL :: Int -> (BC.ByteString -> a) -> IO [a]
fromMLinesL n f = replicateM n (strBS >>= return . f)

fromMLinesV :: VU.Unbox a => Int -> (BC.ByteString -> a) -> IO (VU.Vector a)
fromMLinesV n f = VU.replicateM n (strBS >>= return . f)

-- from multiple lines to List / VU.Vector
mLinesToIntL :: Int -> IO [Int]
mLinesToIntL n = fromMLinesL n bsToInt

mLinesToDoubleL :: Int -> IO [Double]
mLinesToDoubleL n = fromMLinesL n bsToDouble

mLinesToStrL :: Int -> IO [String]
mLinesToStrL n = fromMLinesL n BC.unpack

mLinesToStrBSL :: Int -> IO [BC.ByteString]
mLinesToStrBSL n = fromMLinesL n id

mLinesToTupleL :: Int -> IO [(Int, Int)]
mLinesToTupleL n = fromMLinesL n bsToIntTuple

mLinesToTripleL :: Int -> IO [(Int, Int, Int)]
mLinesToTripleL n = fromMLinesL n bsToIntTriple

mLinesToIntV :: Int -> IO (VU.Vector Int)
mLinesToIntV n = fromMLinesV n bsToInt

mLinesToDoubleV :: Int -> IO (VU.Vector Double)
mLinesToDoubleV n = fromMLinesV n bsToDouble

mLinesToTupleV :: Int -> IO (VU.Vector (Int, Int))
mLinesToTupleV n = fromMLinesV n bsToIntTuple

mLinesToTripleV :: Int -> IO (VU.Vector (Int, Int, Int))
mLinesToTripleV n = fromMLinesV n bsToIntTriple

-- output
yesnoL :: Bool -> IO ()
yesnoL cond
    | cond = putStrLn "Yes"
    | otherwise = putStrLn "No"

yesnoU :: Bool -> IO ()
yesnoU cond
    | cond = putStrLn "YES"
    | otherwise = putStrLn "NO"

-- others
strToChr :: String -> Char
strToChr [x] = x

chrToStr :: Char -> String
chrToStr x = [x]

m1 :: Int -> Int
m1 x = subtract 1 x

toDouble :: Int -> Double
toDouble x = fromIntegral x

toInt :: Double -> Int
toInt x = floor x

Score : 400 points

Problem Statement

We have a sequence of length N, a = (a_1, a_2, ..., a_N).
Each a_i is a positive integer.

Snuke's objective is to permute the element in a so that the following condition is satisfied:

For each 1 ≤ i ≤ N - 1, the product of a_i and a_{i + 1} is a multiple of 4.

Determine whether Snuke can achieve his objective.

Constraints

2 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

If Snuke can achieve his objective, print Yes; otherwise, print No.

Sample Input 1

3
1 10 100

Sample Output 1

Yes

One solution is (1, 100, 10).

Sample Input 2

4
1 2 3 4

Sample Output 2

No

It is impossible to permute a so that the condition is satisfied.

Sample Input 3

3
1 4 1

Sample Output 3

Yes

The condition is already satisfied initially.

Sample Input 4

2
1 1

Sample Output 4

No

Sample Input 5

6
2 7 1 8 2 8

Sample Output 5

Yes


main :: IO ()
main = do
 n <- readLn :: IO Int
 as <- map read . words <$> getLine
 let cnt4 = length $ filter ((0 ==).(`mod`4)) as
     cnt2 = length $ filter (\x -> 0 == (x`mod`2) && 0 /= (x`div`4)) as
     cnt0 = length $ filter ((/=0).(`mod`2)) as
 if cnt4 >= cnt0 then putStrLn "Yes"
   else if odd (length as) && cnt4+1 == cnt0 then putStrLn "Yes" else putStrLn "No"


two n | n `mod` 2 == 0  = 1 + two (n `div` 2)
      | otherwise       = 0

main = do ln1 <- getLine
          ln2 <- getLine
          let n = read ln1
              ar = map (two .read) (words ln2)
              two_cnt = length (filter (>= 2) ar)
              zero_cnt = length (filter (== 0) ar)
              ans = if two_cnt >= zero_cnt || two_cnt == zero_cnt - 1 && two_cnt + zero_cnt == n then "Yes" else "No"
              in putStrLn ans


import Data.List.Split
import Data.Maybe
import qualified Data.ByteString.Char8 as B
main=mapM_(putStrLn.solve).chunksOf 2.map(map(fst.fromJust.B.readInt).B.words).B.lines=<<B.getContents
solve[[n],as]=if(c+(if b==1||b>1&&c/=0 then 1 else 0)<=(if a/=0 then a+1 else 0))then"Yes"else"No"
  where(a,b,c)=foldr f(0,0,0)as
f v(a,b,c)
  |v`mod`4==0=(a+1,b,c)
  |v`mod`2==0=(a,b+1,c)
  |otherwise=(a,b,c+1)


{-# LANGUAGE MultiWayIf #-}

main :: IO ()
main = do
  n <- read <$> getLine :: IO Int
  as <- map read.words <$> getLine :: IO [Int]
  let l4 = length $ filter (\a -> a`mod`4==0) as
      lo = length $ filter odd as
      le = n - l4 - lo
  putStrLn $ if | lo <= l4 -> "Yes"
                | (lo - l4)==1 && le==0 -> "Yes"
                | otherwise -> "No"


import Data.List.Split
import Data.Maybe
import qualified Data.ByteString.Char8 as B
main=mapM_(putStrLn.solve).chunksOf 2.map(map(fst.fromJust.B.readInt).B.words).B.lines=<<B.getContents
solve[[n],as]=if(b`mod`2+c)-a*2<=0 then"Yes"else"No"
  where(a,b,c)=foldr f(0,0,0)as
f v(a,b,c)
  |v`mod`4==0=(a+1,b,c)
  |v`mod`2==0=(a,b+1,c)
  |otherwise=(a,b,c+1)


main=do
    [n,a,b]<-map read.words<$>getLine::IO[Int]
    print $ s n a b
s n a b
    | a>b = 0
    | a==b = 1
    | n==1 = 0
    | n==2 = 1
    | otherwise = b*(n-2)-a*(n-2)+1

Score : 200 points

Problem Statement

Snuke has N integers. Among them, the smallest is A, and the largest is B.
We are interested in the sum of those N integers. How many different possible sums there are?

Constraints

1 ≤ N,A,B ≤ 10^9

A and B are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the number of the different possible sums.

Sample Input 1

4 4 6

Sample Output 1

5

There are five possible sums: 18=4+4+4+6, 19=4+4+5+6, 20=4+5+5+6, 21=4+5+6+6 and 22=4+6+6+6.

Sample Input 2

5 4 3

Sample Output 2

0

Sample Input 3

1 7 10

Sample Output 3

0

Sample Input 4

1 3 3

Sample Output 4

1


main :: IO ()
main = do
  param <- reads2List :: IO [Int]
  let n = head param
  let a = param !! 1
  let b = last param
  print $ solve n a b

s2List :: Read a => String -> [a]
s2List = fmap read . words

reads2List :: Read a => IO [a]
reads2List = do
  s <- getLine
  return (s2List s)

solve :: Int -> Int -> Int -> Int
solve 1 a b = if a == b then 1 else 0
solve n a b | a > b = 0
            | otherwise = (sum maxi - sum mini) + 1 where
              mini = b : replicate (n - 1) a
              maxi = a : replicate (n - 1) b


main = do
  [n,a,b] <- map read . words <$> getLine
  print $ if a>b&&n==1&&a/=b
    then 0
    else (b*(n-1)+a)-(a*(n-1)+b)+1


import Control.Applicative
import Data.List

main = do
  [n, a, b] <- map read . words <$> getLine
  print $ f n a b

f :: Int -> Int -> Int -> Int
f n a b
  | n <= 0 = 0
  | n == 1 && a /= b = 0
  | a > b = 0
  | otherwise = g n a b

g :: Int -> Int -> Int -> Int
g n a b = length $ h n a b

h :: Int -> Int -> Int -> [Int]
h 1 a b = [a .. b]
h n a b = nub $ (+) <$> [a .. b] <*> h (n-1) a b


import Control.Applicative( (<$>))

main = do
    [n_, a_, b_] <- map (read::String->Integer) . words <$> getLine
    let
	combi n r = let
			numerator = product [n-r+1..n]
			denominator = product [1..r]
		    in
			numerator `quot` denominator

    print $ if a_>b_ || (a_<b_&&n_==1)
		then 0
		else combi (b_-a_+n_-2) (n_-2)


main :: IO ()
main = do
    [n, a, b] <- map read . words <$> getLine
    print $ solve n a b

solve :: Integral a => a -> a -> a -> a
solve n a b
    | a > b = 0
    | a == b = 1
    | n == 1 && a /= b = 0
    | otherwise = (b - a) * (n - 2)


main = do
 [n,a,b] <- map read . words <$> getLine
 print (abp n a b)

abp n a b = max 0 ((b*(n-1)+a) - (a*(n-1)+b) + 1)


import Data.Maybe (fromJust)
import qualified Data.ByteString.Char8 as B

main :: IO ()
main = do
    n <- readLn
    as <- (map readInt . B.words) <$> B.getLine
    print $ solve n as

-- |
--
-- >>> solve 2 [3,1,4,1,5,9]
-- 1
--
-- >>> solve 1 [1,2,3]
-- -1
--
-- >>> solve 3 [8,2,2,7,4,6,5,3,8]
-- 5
solve :: Int -> [Int] -> Int
solve n as = maximum $ zipWith diff y1s y2s
  where
    diff (lh,_) (rh,_) = lh - negate rh
    (a1s, cs) = splitAt n as
    (bs, a2s) = splitAt n cs
    bs' = map negate bs
    a2s' = map negate a2s
    q1 = foldl push Empty a1s
    q2 = foldl push Empty a2s'
    lh0 = sum a1s
    rh0 = sum a2s'
    y1s = scanl (flip pushpop) (lh0,q1) bs
    y2s = scanr pushpop (rh0,q2) bs'

-- Util
readInt :: B.ByteString -> Int
readInt = fst . fromJust . B.readInt

-- Heap
data SkewHeap a = Empty | Node a (SkewHeap a) (SkewHeap a)
            deriving (Show, Read, Eq)

singleton :: a -> SkewHeap a
singleton x = Node x Empty Empty

(+@+) :: Ord a => SkewHeap a -> SkewHeap a -> SkewHeap a
Empty               +@+ t2                  = t2
t1                  +@+ Empty               = t1
t1@(Node x1 l1 r1)  +@+ t2@(Node x2 l2 r2)
   | x1 <= x2   = Node x1 (t2 +@+ r1) l1
   | otherwise  = Node x2 (t1 +@+ r2) l2

push :: Ord a => SkewHeap a -> a -> SkewHeap a
heap `push` x = singleton x +@+ heap

pop :: Ord a => SkewHeap a -> (a, SkewHeap a)
pop Empty         = undefined
pop (Node x l r)  = (x, l +@+ r)

pushpop :: (Num a, Ord a) => a -> (a, SkewHeap a) -> (a, SkewHeap a)
x `pushpop` (y, h) = (y + x - x', h')
  where (x', h') = pop $ push h x

Score : 500 points

Problem Statement

Let N be a positive integer.

There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}).
Snuke is constructing a new sequence of length 2N, a', by removing exactly N elements from a without changing the order of the remaining elements.
Here, the score of a' is defined as follows: (the sum of the elements in the first half of a') - (the sum of the elements in the second half of a').

Find the maximum possible score of a'.

Constraints

1 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Partial Score

In the test set worth 300 points, N ≤ 1000.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the maximum possible score of a'.

Sample Input 1

2
3 1 4 1 5 9

Sample Output 1

1

When a_2 and a_6 are removed, a' will be (3, 4, 1, 5), which has a score of (3 + 4) - (1 + 5) = 1.

Sample Input 2

1
1 2 3

Sample Output 2

-1

For example, when a_1 are removed, a' will be (2, 3), which has a score of 2 - 3 = -1.

Sample Input 3

3
8 2 2 7 4 6 5 3 8

Sample Output 3

5

For example, when a_2, a_3 and a_9 are removed, a' will be (8, 7, 4, 6, 5, 3), which has a score of (8 + 7 + 4) - (6 + 5 + 3) = 5.


import qualified Data.Foldable as F

main :: IO ()
main = do
    n <- readLn
    as <- (map read . words) <$> getLine
    print $ solve n as

-- |
--
-- >>> solve 2 [3,1,4,1,5,9]
-- 1
--
-- >>> solve 1 [1,2,3]
-- -1
solve :: Int -> [Int] -> Int
solve n as = maximum $ zipWith (-) y1s y2s
  where
    (a1s,bs,a2s) = split3 as n
    y1s = map (F.foldl1 (+)) $ scanl (-<-) (fromListMin a1s) (reverse bs)
    y2s = map (F.foldl1 (+)) $ reverse $ scanl (->-) (fromListMax a2s) bs

split3 :: [a] -> Int -> ([a], [a], [a])
split3 zs n = (xs,ys,zs'')
  where
    (xs, zs') = split2 ([], zs) n
    (ys, zs'') = split2 ([], zs') n

split2 :: ([a], [a]) -> Int -> ([a], [a])
split2 (_,[]) _ = undefined
split2 (xs,ys) 0 = (xs,ys)
split2 (xs,y0:ys) n = split2 (y0:xs,ys) (n - 1)

-- Heap
data SkewHeap a = Empty | Node a (SkewHeap a) (SkewHeap a)
            deriving (Show, Read, Eq)

singleton :: a -> SkewHeap a
singleton x = Node x Empty Empty

(+<+) :: Ord a => SkewHeap a -> SkewHeap a -> SkewHeap a
Empty               +<+ t2                  = t2
t1                  +<+ Empty               = t1
t1@(Node x1 l1 r1)  +<+ t2@(Node x2 l2 r2)
   | x1 <= x2   = Node x1 (t2 +<+ r1) l1
   | otherwise  = Node x2 (t1 +<+ r2) l2

(+>+) :: Ord a => SkewHeap a -> SkewHeap a -> SkewHeap a
Empty               +>+ t2                  = t2
t1                  +>+ Empty               = t1
t1@(Node x1 l1 r1)  +>+ t2@(Node x2 l2 r2)
   | x1 >= x2   = Node x1 (t2 +>+ r1) l1
   | otherwise  = Node x2 (t1 +>+ r2) l2

(+<) :: Ord a => SkewHeap a -> a -> SkewHeap a
heap +< x = singleton x +<+ heap

(+>) :: Ord a => SkewHeap a -> a -> SkewHeap a
heap +> x = singleton x +>+ heap

popMin :: Ord a => SkewHeap a -> (Maybe a, SkewHeap a)
popMin Empty        = (Nothing, Empty)
popMin (Node x l r) = (Just x, l +<+ r)

popMax :: Ord a => SkewHeap a -> (Maybe a, SkewHeap a)
popMax Empty        = (Nothing, Empty)
popMax (Node x l r) = (Just x, l +>+ r)

fromListMin :: Ord a => [a] -> SkewHeap a
fromListMin = foldl (+<) Empty

fromListMax :: Ord a => [a] -> SkewHeap a
fromListMax = foldl (+>) Empty

(-<-) :: Ord a => SkewHeap a -> a -> SkewHeap a
(-<-) heap x = snd . popMin $ heap +< x

(->-) :: Ord a => SkewHeap a -> a -> SkewHeap a
(->-) heap x = snd . popMax $ heap +> x

instance Foldable SkewHeap where
    foldMap _ Empty = mempty
    foldMap f (Node x l r) = foldMap f l `mappend` f x `mappend` foldMap f r