toFloat :: Int -> Float
toFloat = fromRational . toRational

solve :: Int -> Int -> [Int] -> Int
solve a b [] = -1
solve a b (s:ss)
    | a == a' && b == b' = s
    | otherwise = solve a b ss
        where
            s' = toFloat s
            a' = floor $ s' * 0.08
            b' = floor $ s' * 0.1

main = do
    [a,b] <- map read . words <$> getLine :: IO [Int]
    print $ solve a b [1..1000]

Score : 300 points

Problem Statement

Find the price of a product before tax such that, when the consumption tax rate is 8 percent and 10 percent, the amount of consumption tax levied on it is A yen and B yen, respectively. (Yen is the currency of Japan.)

Here, the price before tax must be a positive integer, and the amount of consumption tax is rounded down to the nearest integer.

If multiple prices satisfy the condition, print the lowest such price; if no price satisfies the condition, print -1.

Constraints

1 \leq A \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If there is a price that satisfies the condition, print an integer representing the lowest such price; otherwise, print -1.

Sample Input 1

2 2

Sample Output 1

25

If the price of a product before tax is 25 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 25 \times 0.08 \rfloor = \lfloor 2 \rfloor = 2 yen.

When the consumption tax rate is 10 percent: \lfloor 25 \times 0.1 \rfloor = \lfloor 2.5 \rfloor = 2 yen.

Thus, the price of 25 yen satisfies the condition. There are other possible prices, such as 26 yen, but print the minimum such price, 25.

Sample Input 2

8 10

Sample Output 2

100

If the price of a product before tax is 100 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 100 \times 0.08 \rfloor = 8 yen.

When the consumption tax rate is 10 percent: \lfloor 100 \times 0.1 \rfloor = 10 yen.

Sample Input 3

19 99

Sample Output 3

-1

There is no price before tax satisfying this condition, so print -1.


toFloat :: Int -> Float
toFloat = fromRational . toRational

solve :: Int -> Int -> [Int] -> Int
solve a b [] = -1
solve a b (s:ss)
    | a == a' && b == b' = s
    | otherwise = solve a b ss
        where
            s' = toFloat s
            a' = floor $ s' * 0.08
            b' = floor $ s' * 0.1

main = do
    [a,b] <- map read . words <$> getLine :: IO [Int]
    print $ solve a b [1..100]

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

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.


{-# LANGUAGE BangPatterns #-}

module Main
  ( main
  )
where

import           Control.Applicative
import           Control.Monad
import           Data.Bits
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import           Data.List
import           Data.Maybe
import qualified Data.Vector                   as V
import qualified Data.Vector.Mutable           as MV
import           Control.Monad.ST
import           Data.Ord

parse = fst . fromJust
parseInt = parse . BS.readInt
parseInteger = parse . BS.readInteger
readInt = parseInt <$> BS.getLine
readInteger = parseInteger <$> BS.getLine
readIntList = map parseInt . BS.words <$> BS.getLine
readIntegerList = map parseInteger . BS.words <$> BS.getLine

main = do
  [a, b] <- map (read::String -> Float) . words <$> getLine
  let (la, ua) = (ceiling $ a / 0.08, floor $ (a + 1) / 0.08)
      (lb, ub) = (ceiling $ b / 0.1, floor $ (b + 1) / 0.1)
  print $ if ua > lb && ub > la then max la lb else -1


{-# LANGUAGE OverloadedStrings #-}
import Data.Char
import Data.List
import Control.Monad
import qualified Data.ByteString.Char8 as BS

main :: IO ()
main = do
  [a,b] <- parseLine <$> BS.getLine
  BS.putStrLn . BS.pack . show $ solve a b
  where
     parseLine = unfoldr (BS.readInt . BS.dropWhile isSpace)

solve :: Int -> Int -> Int
solve a b
  | null candidates = -1
  | otherwise = head candidates
  where
    makeCandidates x rate = takeWhile ((==x).floor.(*rate).fromIntegral) [(ceiling ((fromIntegral x)/rate))..]
    candidatesA = makeCandidates a 0.08
    candidatesB = makeCandidates b 0.1
    candidates = intersect candidatesA candidatesB


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

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

#if __GLASGOW_HASKELL__ >= 808
import qualified Data.OrdPSQ as PSQ
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

data OrdQ = Ascending | Descending
#endif

--------------------------------------------------------------------------
f (l,r,cnt) xs
    | head xs == "1" = (l,r,cnt+1)
    | otherwise =
        case xs of
            ["2","1",c] ->
                if even cnt
                    then let l' = c SQ.<| l in (l',r,cnt)
                    else let r' = r SQ.|> c in (l,r',cnt)
            ["2","2",c] ->
                if even cnt
                    then let r' = r SQ.|> c in (l,r',cnt)
                    else let l' = c SQ.<| l in (l',r,cnt)

main = do
    xs <- str
    q <- int
    xss <- (replicateM q $ do
        xs <- words <$> str
        return xs) :: IO [[String]]
    let (l,r,c) = foldl' f (SQ.empty, SQ.empty, 0) xss
    putStrLn $
        if even c
            then (concat $ sqToList l) ++ xs ++ (concat $ sqToList r)
            else (concat $ reverse $ sqToList r) ++ xs ++ (concat $ reverse $ sqToList l)
--------------------------------------------------------------------------

-- 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 -> []

#if __GLASGOW_HASKELL__ >= 808
sortV :: (Ord a, VU.Unbox a) => VU.Vector a -> VU.Vector a
sortV v = VU.create $ do
    w <- VU.thaw v
    VAM.sort w
    return w

buildPQL :: Ord a => OrdQ -> [a] -> PSQ.OrdPSQ Int Int a
buildPQL oq xs =
    case oq of
        Ascending -> f $ zip3 [1..l] [1..l] $ sort xs
        Descending -> f $ zip3  [1..l] (map negate [1..l]) $ sort xs
    where
        l = length xs
        f = foldl' g PSQ.empty
        g acc (k,p,v) = PSQ.insert k p v acc

buildPQV :: (Ord a, VU.Unbox a) => OrdQ -> VU.Vector a -> PSQ.OrdPSQ Int Int a
buildPQV oq xs =
    case oq of
        Ascending -> f $ VU.zip3 (VU.generate l (+1)) (VU.generate l (+1)) $ sortV xs
        Descending -> f $ VU.zip3  (VU.generate l (+1)) (VU.generate l $ negate . (+1)) $ sortV xs
    where
        l = VU.length xs
        f = VU.foldl' g PSQ.empty
        g acc (k,p,v) = PSQ.insert k p v acc
#endif

Score : 400 points

Problem Statement

Takahashi has a string S consisting of lowercase English letters.

Starting with this string, he will produce a new one in the procedure given as follows.

The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following:

If T_i = 1: reverse the string S.

If T_i = 2: An integer F_i and a lowercase English letter C_i are additionally provided.

If F_i = 1 : Add C_i to the beginning of the string S.

If F_i = 2 : Add C_i to the end of the string S.

Help Takahashi by finding the final string that results from the procedure.

Constraints

1 \leq |S| \leq 10^5

S consists of lowercase English letters.

1 \leq Q \leq 2 \times 10^5

T_i = 1 or 2.

F_i = 1 or 2, if provided.

C_i is a lowercase English letter, if provided.

Input

Input is given from Standard Input in the following format:

S
Q
Query_1
:
Query_Q

In the 3-rd through the (Q+2)-th lines, Query_i is one of the following:

1

which means T_i = 1, and:

2 F_i C_i

which means T_i = 2.

Output

Print the resulting string.

Sample Input 1

a
4
2 1 p
1
2 2 c
1

Sample Output 1

cpa

There will be Q = 4 operations. Initially, S is a.

Operation 1: Add p at the beginning of S. S becomes pa.

Operation 2: Reverse S. S becomes ap.

Operation 3: Add c at the end of S. S becomes apc.

Operation 4: Reverse S. S becomes cpa.

Thus, the resulting string is cpa.

Sample Input 2

a
6
2 2 a
2 1 b
1
2 2 c
1
1

Sample Output 2

aabc

There will be Q = 6 operations. Initially, S is a.

Operation 1: S becomes aa.

Operation 2: S becomes baa.

Operation 3: S becomes aab.

Operation 4: S becomes aabc.

Operation 5: S becomes cbaa.

Operation 6: S becomes aabc.

Thus, the resulting string is aabc.

Sample Input 3

y
1
2 1 x

Sample Output 3

xy


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

main = do
    [s] <- getLine :: IO String
    q <- readLn :: IO Int
    switch <- newIORef False
    res <- newIORef 0

    let
        solve :: B.ByteString -> Int -> IO B.ByteString
        solve bs n
            | n == 0 = return bs
            | otherwise = do
                s <- words <$> getLine
                case (length s) of
                    1 -> do
                        modifyIORef' res (+1)
                        solve bs (n-1)
                    _ -> do
                        res' <- readIORef res
                        let [_,i,[c]] = s
                        case (i, even res') of
                            ("1", True) -> solve (B.cons c bs) (n-1)
                            ("1", False) -> solve (B.snoc bs c) (n-1)
                            ("2", True) -> solve (B.snoc bs c) (n-1)
                            ("2", False) -> solve (B.cons c bs) (n-1)
    b <- solve (B.singleton s) q
    res' <- readIORef res
    putStrLn $
        if even res'
            then B.unpack b
            else B.unpack $ B.reverse b


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

readInt = fst . fromJust . BS.readInt
getInt = readInt <$> BS.getLine

main = do
    s <- getLine
    q <- getInt
    queues <- map words <$> replicateM q getLine
    putStrLn $ foldl' solve s queues

solve s queue | queue !! 0 == "1" = reverse s
              | queue !! 1 == "1" = (queue !! 2) ++ s
              | otherwise = s ++ (queue !! 2)


import Data.List
main=do
 [n,p]<-map read.words<$>getLine
 s<-map(\c->fromEnum c-48).reverse<$>getLine
 let a=group$sort$0:(f 0 1 s p)
 print$sum$if 10`mod`p==0 then(map(\(c,i)->if c`mod`p==0 then i else 0)$zip(reverse s)[1..])else map(\l->(length l)*(-1+length l)`div`2)a
f w k[]p=[]
f w k(c:s)p=t:f t(k*10`mod`p)s p where t=(w+k*c)`mod`p

Score : 500 points

Problem Statement

Takahashi has a string S of length N consisting of digits from 0 through 9.

He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten.

Here substrings starting with a 0 also count, and substrings originated from different positions in S are distinguished, even if they are equal as strings or integers.

Compute this count to help Takahashi.

Constraints

1 \leq N \leq 2 \times 10^5

S consists of digits.

|S| = N

2 \leq P \leq 10000

P is a prime number.

Input

Input is given from Standard Input in the following format:

N P
S

Output

Print the number of non-empty (contiguous) substrings of S that are divisible by P when regarded as an integer written in base ten.

Sample Input 1

4 3
3543

Sample Output 1

6

Here S = 3543. There are ten non-empty (contiguous) substrings of S:

3: divisible by 3.

35: not divisible by 3.

354: divisible by 3.

3543: divisible by 3.

5: not divisible by 3.

54: divisible by 3.

543: divisible by 3.

4: not divisible by 3.

43: not divisible by 3.

3: divisible by 3.

Six of these are divisible by 3, so print 6.

Sample Input 2

4 2
2020

Sample Output 2

10

Here S = 2020. There are ten non-empty (contiguous) substrings of S, all of which are divisible by 2, so print 10.

Note that substrings beginning with a 0 also count.

Sample Input 3

20 11
33883322005544116655

Sample Output 3

68


import           Control.Monad
import qualified Data.ByteString.Char8       as BS
import           Data.Char
import           Data.Maybe
import qualified Data.Vector.Unboxed.Mutable as VM

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

main = do
  [n, p] <- getIntList
  s <- BS.getLine

  v <- VM.new p
  VM.set v (0::Int)
  VM.write v 0 1 -- U0 `mod` p == 0
  let solve25 i a | i > n = print a
                  | otherwise = do
                      let c = BS.index s (n-i)
                          di = ord c - ord '0'
                          x = if di `mod` p == 0 then n - i + 1 else 0
                      solve25 (i+1) (a+x)

      solve i a md m10 | i > n = print a
                       | otherwise = do
                           let c = BS.index s (n-i)
                               di = ord c - ord '0'
                               md' = (md + di * m10) `mod` p
                               m10' = (m10 * 10) `mod` p
                           y <- VM.read v md'
                           VM.write v md' (y+1)
                           solve (i+1) (a+y) md' m10'

  if 10 `mod` p == 0
    then solve25 1 0
    else solve 1 0 0 1


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

readInt = fst . fromJust . BS.readInt

getInt = readInt <$> BS.getLine

main = do
  n <- getInt
  print $ (n + 1) `div` 2

Score : 100 points

Problem Statement

Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper.

At least how many sheets of paper does he need?

Constraints

N is an integer.

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

5

Sample Output 1

3

By printing the 1-st, 2-nd pages on the 1-st sheet, 3-rd and 4-th pages on the 2-nd sheet, and 5-th page on the 3-rd sheet, we can print all the data on 3 sheets of paper.

Sample Input 2

2

Sample Output 2

1

Sample Input 3

100

Sample Output 3

50


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

main :: IO ()
main = BS.getLine >>= print . solve . fst . fromJust . BS.readInt
    where solve n
            | odd n     = (n+1) `div` 2
            | otherwise = n `div` 2


module Main where

main :: IO ()
main = do
 n <- read <$> getLine
 putStrLn $ show $ ceiling $ n / 2


main = do
  n <- readLn
  print $ f n

f :: Int -> Int
f n = if n `mod` 2 == 0 then
          n `div` 2
      else
          n `div` 2 + 1


import Data.Bool
import Data.List
import Data.Maybe
import Data.Vector.Generic ((!))
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM

main = interact $ sub . lines

sub (l1:l2:l3:ls) = sol v bs
  where
  v = V.fromListN 3 $ V.fromListN 3 . fmap (read::String->Int) . words <$> [l1,l2,l3]
  bs = fmap read $ tail ls :: [Int]

sol v bs = bool "No" "Yes" . bingo $ V.map (\u -> foldl' mark u bs) v

bingo v = V.any (V.all (==0)) v
  || any (\j -> V.all (\u -> u!j==0) v) [0..2]
  || all (\i -> v!i!i==0) [0..2]
  || all (\i -> v!i!(2-i)==0) [0..2]

mark u b = maybe u (\i -> V.modify (\w -> VM.write w i 0) u) $ V.findIndex (==b) u

Score : 200 points

Problem Statement

We have a bingo card with a 3\times3 grid. The square at the i-th row from the top and the j-th column from the left contains the number A_{i, j}.

The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet contains some of those numbers, we will mark them on our sheet.

Determine whether we will have a bingo when the N numbers are chosen, that is, the sheet will contain three marked numbers in a row, column, or diagonal.

Constraints

All values in input are integers.

1 \leq A_{i, j} \leq 100

A_{i_1, j_1} \neq A_{i_2, j_2} ((i_1, j_1) \neq (i_2, j_2))

1 \leq N \leq 10

1 \leq b_i \leq 100

b_i \neq b_j (i \neq j)

Input

Input is given from Standard Input in the following format:

A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N

Output

If we will have a bingo, print Yes; otherwise, print No.

Sample Input 1

84 97 66
79 89 11
61 59 7
7
89
7
87
79
24
84
30

Sample Output 1

Yes

We will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal from the top-left to the bottom-right.

Sample Input 2

41 7 46
26 89 2
78 92 8
5
6
45
16
57
17

Sample Output 2

No

We will mark nothing.

Sample Input 3

60 88 34
92 41 43
65 73 48
10
60
43
88
11
48
73
65
41
92
34

Sample Output 3

Yes

We will mark all the squares.


import Control.Applicative
import Control.Monad
import Data.List
import Data.Bool (bool)
import Data.Vector (Vector, (!), (//))
import qualified Data.Vector as V

main :: IO ()
main = do
  xs <- f
  ys <- f
  zs <- f
  n <- readLn
  solve (V.fromList (xs ++ ys ++ zs)) <$> replicateM n readLn >>= putStrLn
  where
    f = map read <$> words <$> getLine

solve :: Vector Int -> [Int] -> String
solve v xs = bool "No" "Yes" $ vv ! 0 == 0 && vv ! 1 == 0 && vv ! 2 == 0 ||
                               vv ! 3 == 0 && vv ! 4 == 0 && vv ! 5 == 0 ||
                               vv ! 6 == 0 && vv ! 7 == 0 && vv ! 8 == 0 ||
                               vv ! 0 == 0 && vv ! 3 == 0 && vv ! 6 == 0 ||
                               vv ! 1 == 0 && vv ! 4 == 0 && vv ! 7 == 0 ||
                               vv ! 2 == 0 && vv ! 5 == 0 && vv ! 8 == 0 ||
                               vv ! 0 == 0 && vv ! 4 == 0 && vv ! 8 == 0 ||
                               vv ! 2 == 0 && vv ! 4 == 0 && vv ! 6 == 0
  where
    vv = foldl' f v xs
    f t x = case V.findIndex (== x) t of
             Just i -> t // [(i, 0)]
             Nothing -> t


import Control.Monad

main = do
  [str1, str2, str3] <- sequence [getLine, getLine, getLine]
  let a1 = map read (words str1) ::[Int]
  let a2 = map read (words str2) ::[Int]
  let a3 = map read (words str3) ::[Int]
  str <- getLine
  let n = read str ::Int
  bs <- forM [1..n] $ \i -> do
    str <- getLine
    let b = read str ::Int
    return b
  let ans1 = map (`elem` bs) a1
  let ans2 = map (`elem` bs) a2
  let ans3 = map (`elem` bs) a3
  if ck ans1 ans2 ans3 == True
    then putStrLn "Yes"
    else putStrLn "No"

ck :: [Bool] -> [Bool] -> [Bool] -> Bool
ck lt1 lt2 lt3
  | and lt1 == True = True
  | and lt2 == True = True
  | and lt3 == True = True
  | and [lt1 !! 0, lt2 !! 0, lt3 !! 0] == True = True
  | and [lt1 !! 1, lt2 !! 1, lt3 !! 1] == True = True
  | and [lt1 !! 2, lt2 !! 2, lt3 !! 2] == True = True
  | and [lt1 !! 0, lt2 !! 1, lt3 !! 2] == True = True
  | and [lt1 !! 2, lt2 !! 1, lt3 !! 0] == True = True
  | otherwise = False


import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.List
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM

newUF n = VUM.replicate n (-1 :: Int)

root uf x = do
    p <- VUM.read uf x
    if p < 0
        then return x
        else do
            r <- root uf p
            VUM.write uf x r
            return r

same uf x y = liftM2 (==) (root uf x) (root uf y)

unite uf x y = do
    px <- root uf x
    py <- root uf y
    when (px /= py) $ do
        sx <- VUM.read uf px
        sy <- VUM.read uf py
        let (par, chld) = if sx < sy then (px, py)　else (py, px)
        VUM.write uf chld par
        VUM.write uf par (sx + sy)

size uf x = do
    px <- root uf x
    s <- VUM.read uf px
    return $ abs s

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

main = do
    [n,m,k] <- getIntList
    ab <- replicateM m $ do
        [a,b] <- getIntList
        return (a-1,b-1)
    cd <- replicateM k $ do
        [c,d] <- getIntList
        return (c-1,d-1)
    let friends = VU.create $ do
            count <- VUM.replicate n (-1 :: Int)
            uf <- newUF n
            forM_ ab $ \(a,b) -> do
                unite uf a b
                VUM.modify count pred a
                VUM.modify count pred b
            forM_ [0..n-1] $ \i -> do
                s <- size uf i
                VUM.modify count (+ s) i
            forM_ cd $ \(c,d) -> do
                b <- same uf c d
                when b $ do
                    VUM.modify count pred c
                    VUM.modify count pred d
            return count
    putStrLn . unwords . map show $ VU.toList friends

Score : 400 points

Problem Statement

An SNS has N users - User 1, User 2, \cdots, User N.

Between these N users, there are some relationships - M friendships and K blockships.

For each i = 1, 2, \cdots, M, there is a bidirectional friendship between User A_i and User B_i.

For each i = 1, 2, \cdots, K, there is a bidirectional blockship between User C_i and User D_i.

We define User a to be a friend candidate for User b when all of the following four conditions are satisfied:

a \neq b.

There is not a friendship between User a and User b.

There is not a blockship between User a and User b.

There exists a sequence c_0, c_1, c_2, \cdots, c_L consisting of integers between 1 and N (inclusive) such that c_0 = a, c_L = b, and there is a friendship between User c_i and c_{i+1} for each i = 0, 1, \cdots, L - 1.

For each user i = 1, 2, ... N, how many friend candidates does it have?

Constraints

All values in input are integers.

2 ≤ N ≤ 10^5

0 \leq M \leq 10^5

0 \leq K \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

1 \leq C_i, D_i \leq N

C_i \neq D_i

(A_i, B_i) \neq (A_j, B_j) (i \neq j)

(A_i, B_i) \neq (B_j, A_j)

(C_i, D_i) \neq (C_j, D_j) (i \neq j)

(C_i, D_i) \neq (D_j, C_j)

(A_i, B_i) \neq (C_j, D_j)

(A_i, B_i) \neq (D_j, C_j)

Input

Input is given from Standard Input in the following format:

N M K
A_1 B_1
\vdots
A_M B_M
C_1 D_1
\vdots
C_K D_K

Output

Print the answers in order, with space in between.

Sample Input 1

4 4 1
2 1
1 3
3 2
3 4
4 1

Sample Output 1

0 1 0 1

There is a friendship between User 2 and 3, and between 3 and 4. Also, there is no friendship or blockship between User 2 and 4. Thus, User 4 is a friend candidate for User 2.

However, neither User 1 or 3 is a friend candidate for User 2, so User 2 has one friend candidate.

Sample Input 2

5 10 0
1 2
1 3
1 4
1 5
3 2
2 4
2 5
4 3
5 3
4 5

Sample Output 2

0 0 0 0 0

Everyone is a friend of everyone else and has no friend candidate.

Sample Input 3

10 9 3
10 1
6 7
8 2
2 5
8 4
7 3
10 9
6 4
5 8
2 6
7 5
3 1

Sample Output 3

1 3 5 4 3 3 3 3 1 0


import qualified Data.Vector.Unboxed as U
import qualified Data.ByteString.Char8 as C
import Data.List
import Control.Monad
import Control.Arrow
import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import Data.Maybe
import Data.Graph

r :: Int -> IO (U.Vector Int)
r n = U.unfoldrN n (C.readInt . C.dropWhile (==' ')) <$> C.getLine

r' :: IO [Int]
r'  =   unfoldr    (C.readInt . C.dropWhile (==' ')) <$> C.getLine

main :: IO ()
main = do
    [n,m,k] <- r' :: IO [Int]
    friends <- replicateM m (r' >>= (\[a,b] -> return (a,b)))
    blocks  <- replicateM k (r' >>= (\[s,c] -> return (s,c)))

    let fs = friends ++ map swap friends
    let bs = blocks  ++ map swap blocks

    let fg = buildG (1,n) fs

    let cm = IM.fromList $ map (id &&& (IS.fromList.reachable fg)) [1..n]
    let fm = IM.map IS.fromList $ IM.fromListWith (++) $ map (second pure) fs
    let bm = IM.map IS.fromList $ IM.fromListWith (++) $ map (second pure) bs

    let net = Net n cm fm bm

    putStrLn $ unwords $ map (show .solve net) [1..n]

data Network = Net {population :: Int
    , componentMap :: IM.IntMap IS.IntSet
    , friendMap :: IM.IntMap IS.IntSet
    , blockMap :: IM.IntMap IS.IntSet}

solve net me = IS.size $ componentMap net IM.! me IS.\\
    (IS.fromList [me] `IS.union` (IM.findWithDefault IS.empty me (friendMap net)) `IS.union` (IM.findWithDefault IS.empty me (blockMap net)))

swap (a,b) = (b,a)


import qualified Data.Vector.Unboxed as U
import qualified Data.Vector as V
import qualified Data.ByteString.Char8 as C
import Debug.Trace
import Data.List
import Control.Monad
import Data.Ord

r :: Int -> IO (U.Vector Int)
r n = U.unfoldrN n (C.readInt . C.dropWhile (==' ')) <$> C.getLine

r' :: IO [Int]
r'  =   unfoldr    (C.readInt . C.dropWhile (==' ')) <$> C.getLine

rp :: IO (Int,Int)
rp  = toTup . unfoldr    (C.readInt . C.dropWhile (==' ')) <$> C.getLine

toTup [a,b] = (a,b)

main :: IO ()
main = do
    [n,k] <- r'
    print $ ceiling $ logBase (fromIntegral k) (fromIntegral n)

Score : 200 points

Problem Statement

Given is an integer N. Find the number of digits that N has in base K.

Notes

For information on base-K representation, see Positional notation - Wikipedia.

Constraints

All values in input are integers.

1 \leq N \leq 10^9

2 \leq K \leq 10

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of digits that N has in base K.

Sample Input 1

11 2

Sample Output 1

4

In binary, 11 is represented as 1011.

Sample Input 2

1010101 10

Sample Output 2

7

Sample Input 3

314159265 3

Sample Output 3

18


{-# LANGUAGE BangPatterns #-}

module Main
  ( main
  )
where

import           Control.Applicative
import           Control.Monad
import           Data.Bits
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import           Data.List
import           Data.Maybe
import qualified Data.Vector                   as V
import qualified Data.Vector.Mutable           as MV
import           Control.Monad.ST
import           Data.Ord

parse = fst . fromJust
parseInt = parse . BS.readInt
parseInteger = parse . BS.readInteger
readInt = parseInt <$> BS.getLine
readInteger = parseInteger <$> BS.getLine
readIntList = map parseInt . BS.words <$> BS.getLine
readIntegerList = map parseInteger . BS.words <$> BS.getLine

main = do
  n <- readInt
  arr <- readIntList
  let s = sum arr
      lb = s `div` n
      ub = lb + 1
      scoreLb = foldl' (\acc val -> acc + (val - lb) ^ 2) 0 arr
      scoreUb = foldl' (\acc val -> acc + (val - ub) ^ 2) 0 arr
  print $ min scoreLb scoreUb

Score : 300 points

Problem Statement

There are N people living on a number line.

The i-th person lives at coordinate X_i.

You are going to hold a meeting that all N people have to attend.

The meeting can be held at any integer coordinate. If you choose to hold the meeting at coordinate P, the i-th person will spend (X_i - P)^2 points of stamina to attend the meeting.

Find the minimum total points of stamina the N people have to spend.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq X_i \leq 100

Input

Input is given from Standard Input in the following format:

N
X_1 X_2 ... X_N

Output

Print the minimum total stamina the N people have to spend.

Sample Input 1

2
1 4

Sample Output 1

5

Assume the meeting is held at coordinate 2. In this case, the first person will spend (1 - 2)^2 points of stamina, and the second person will spend (4 - 2)^2 = 4 points of stamina, for a total of 5 points of stamina. This is the minimum total stamina that the 2 people have to spend.

Note that you can hold the meeting only at an integer coordinate.

Sample Input 2

7
14 14 2 13 56 2 37

Sample Output 2

2354


import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.List
import qualified Data.Vector as V

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

moduloN :: Int
moduloN = 10 ^ 9 + 7

modN = flip mod moduloN

mulMod x y = modN $ x * y

powerMod x 0 = 1
powerMod x y
    | even y = mulMod t t
    | otherwise = mulMod x $ mulMod t t
    where
        t = powerMod x $ div y 2

plusMod x y = modN $ x + y

minusMod x y | x < y = moduloN + x - y
             | otherwise = x - y

inv n = powerMod n $ moduloN - 2

comb n k | n - k < k = mulMod (foldr mulMod 1 [k+1..n]) . inv $ foldr mulMod 1 [1..n-k]
         | otherwise = mulMod (foldr mulMod 1 [n-k+1..n]) . inv $ foldr mulMod 1 [1..k]

main = do
    [n, a, b] <- getIntList
    print . minusMod ((powerMod 2 n) - 1) $ plusMod (comb n a) (comb n b)

Score : 400 points

Problem Statement

Akari has n kinds of flowers, one of each kind.

She is going to choose one or more of these flowers to make a bouquet.

However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b.

How many different bouquets are there that Akari can make?

Find the count modulo (10^9 + 7).

Here, two bouquets are considered different when there is a flower that is used in one of the bouquets but not in the other bouquet.

Constraints

All values in input are integers.

2 \leq n \leq 10^9

1 \leq a < b \leq \textrm{min}(n, 2 \times 10^5)

Input

Input is given from Standard Input in the following format:

n a b

Output

Print the number of bouquets that Akari can make, modulo (10^9 + 7). (If there are no such bouquets, print 0.)

Sample Input 1

4 1 3

Sample Output 1

7

In this case, Akari can choose 2 or 4 flowers to make the bouquet.

There are 6 ways to choose 2 out of the 4 flowers, and 1 way to choose 4, so there are a total of 7 different bouquets that Akari can make.

Sample Input 2

1000000000 141421 173205

Sample Output 2

34076506

Print the count modulo (10^9 + 7).


answer :: [String] -> String
answer [a,b,c] | a == b && b == c && a == c = "No"
               | a /= b && b /= c && a /= c = "No"
               | otherwise = "Yes"
main = do
  list <- words <$> getLine
  putStrLn $ answer list

Score: 100 points

Problem Statement

A triple of numbers is said to be poor when two of those numbers are equal but the other number is different from those two numbers.

You will be given three integers A, B, and C. If this triple is poor, print Yes; otherwise, print No.

Constraints

A, B, and C are all integers between 1 and 9 (inclusive).

Input

Input is given from Standard Input in the following format:

A B C

Output

If the given triple is poor, print Yes; otherwise, print No.

Sample Input 1

5 7 5

Sample Output 1

Yes

A and C are equal, but B is different from those two numbers, so this triple is poor.

Sample Input 2

4 4 4

Sample Output 2

No

A, B, and C are all equal, so this triple is not poor.

Sample Input 3

4 9 6

Sample Output 3

No

Sample Input 4

3 3 4

Sample Output 4

Yes


module Main where

import Data.List

main = putStrLn =<< solve <$> readInts

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

solve :: [Int] -> String
solve [a, b, c]
    | a /= b && b /= c = "No"
    | a == c = "No"
    | otherwise = "Yes"


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

f :: Int -> Int -> Int -> String
f a b c
  | a == b && b /= c = "Yes"
  | a == c && c /= b = "Yes"
  | b == c && c /= a = "Yes"
  | otherwise = "No"


{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NumDecimals #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}

import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Monad.ST

import Data.Char
import Data.List
import Data.Maybe

import qualified Data.ByteString.Char8 as B

import Data.Array.ST.Safe
import Data.STRef

import Debug.Trace
import Text.Printf

readInt = readLn :: IO Int
readInteger = readLn :: IO Integer
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine

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

modifyArray a i f = writeArray a i =<< f <$> readArray a i

main = getLine >> readInts >>= putStrLn . which "APPROVED" "DENIED" . all f

f x = odd x || x `mod` 3 == 0 || x `mod` 5 == 0

Score: 200 points

Problem Statement

You are an immigration officer in the Kingdom of AtCoder. The document carried by an immigrant has some number of integers written on it, and you need to check whether they meet certain criteria.

According to the regulation, the immigrant should be allowed entry to the kingdom if and only if the following condition is satisfied:

All even numbers written on the document are divisible by 3 or 5.

If the immigrant should be allowed entry according to the regulation, output APPROVED; otherwise, print DENIED.

Notes

The condition in the statement can be rephrased as "If x is an even number written on the document, x is divisible by 3 or 5".
Here "if" and "or" are logical terms.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

If the immigrant should be allowed entry according to the regulation, print APPROVED; otherwise, print DENIED.

Sample Input 1

5
6 7 9 10 31

Sample Output 1

APPROVED

The even numbers written on the document are 6 and 10.

All of them are divisible by 3 or 5, so the immigrant should be allowed entry.

Sample Input 2

3
28 27 24

Sample Output 2

DENIED

28 violates the condition, so the immigrant should not be allowed entry.


module Main where

import Data.List
import qualified Data.Map.Strict as Map
import Control.Monad
import Data.Ord

main = do
    printRes =<< solve <$> (readStrings =<< readInt)

readStrings :: Int -> IO [String]
readStrings n = replicateM n getLine

readInt :: IO Int
readInt = read <$> getLine

solve :: [String] -> [String]
solve strs = ret
    where
        sorted = sortOn (Down . snd) $ Map.toList $ Map.fromListWith (+) $ map (\s -> (s, 1)) strs
        maxVal = snd $ head sorted
        ret = map fst $ takeWhile ((== maxVal) . snd) sorted

printRes :: [String] -> IO ()
printRes [] = return ()
printRes (x:xs) = do
    putStrLn x
    printRes xs

Score: 300 points

Problem Statement

We have N voting papers. The i-th vote (1 \leq i \leq N) has the string S_i written on it.

Print all strings that are written on the most number of votes, in lexicographical order.

Constraints

1 \leq N \leq 2 \times 10^5

S_i (1 \leq i \leq N) are strings consisting of lowercase English letters.

The length of S_i (1 \leq i \leq N) is between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

Print all strings in question in lexicographical order.

Sample Input 1

7
beat
vet
beet
bed
vet
bet
beet

Sample Output 1

beet
vet

beet and vet are written on two sheets each, while beat, bed, and bet are written on one vote each. Thus, we should print the strings beet and vet.

Sample Input 2

8
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo

Sample Output 2

buffalo

Sample Input 3

7
bass
bass
kick
kick
bass
kick
kick

Sample Output 3

kick

Sample Input 4

4
ushi
tapu
nichia
kun

Sample Output 4

kun
nichia
tapu
ushi


intListString :: [Int] -> String
intListString [] = ""
intListString (x:xs) = show x ++ " " ++ intListString xs

main = do
    [s,t] <- words <$> getLine
    [a,b] <- map read <$> (words <$> getLine) :: IO [Int]
    u <- getLine
    if s == u
        then putStrLn $ intListString [a-1,b]
        else putStrLn $ intListString [a,b-1]

Score : 100 points

Problem Statement

We have A balls with the string S written on each of them and B balls with the string T written on each of them.

From these balls, Takahashi chooses one with the string U written on it and throws it away.

Find the number of balls with the string S and balls with the string T that we have now.

Constraints

S, T, and U are strings consisting of lowercase English letters.

The lengths of S and T are each between 1 and 10 (inclusive).

S \not= T

S=U or T=U.

1 \leq A,B \leq 10

A and B are integers.

Input

Input is given from Standard Input in the following format:

S T
A B
U

Output

Print the answer, with space in between.

Sample Input 1

red blue
3 4
red

Sample Output 1

2 4

Takahashi chose a ball with red written on it and threw it away.
Now we have two balls with the string S and four balls with the string T.

Sample Input 2

red blue
5 5
blue

Sample Output 2

5 4

Takahashi chose a ball with blue written on it and threw it away.
Now we have five balls with the string S and four balls with the string T.


import Data.List
import Data.Char
import Data.Maybe
import Control.Monad
import qualified Data.ByteString.Char8 as BS8
import Data.Map.Strict ((!))
import qualified Data.Map.Strict as MapS

main=do
    [s, t] <- words<$>getLine
    [a, b] <- unfoldr (BS8.readInt . BS8.dropWhile isSpace) <$> BS8.getLine
    u <- getLine

    let m = MapS.fromList [(s, a), (t, b)]
        ans = MapS.insert u ((m ! u) - 1) m

    putStrLn $ unwords $ map show [ans ! s, ans ! t]


main = do
  s <- getLine
  putStrLn $ replicate (length s) 'x'

Score : 200 points

Problem Statement

Given is a string S. Replace every character in S with x and print the result.

Constraints

S is a string consisting of lowercase English letters.

The length of S is between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

Replace every character in S with x and print the result.

Sample Input 1

sardine

Sample Output 1

xxxxxxx

Replacing every character in S with x results in xxxxxxx.

Sample Input 2

xxxx

Sample Output 2

xxxx

Sample Input 3

gone

Sample Output 3

xxxx


import qualified Data.IntSet as IntSet

main = do
  n <- readLn
  a <- map read . words <$> getLine
  putStrLn $
    if n == IntSet.size (IntSet.fromList a)
      then "YES"
      else "NO"

Score : 300 points

Problem Statement

Given is a sequence of integers A_1, A_2, ..., A_N.
If its elements are pairwise distinct, print YES; otherwise, print NO.

Constraints

2 ≤ N ≤ 200000

1 ≤ A_i ≤ 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

If the elements of the sequence are pairwise distinct, print YES; otherwise, print NO.

Sample Input 1

5
2 6 1 4 5

Sample Output 1

YES

The elements are pairwise distinct.

Sample Input 2

6
4 1 3 1 6 2

Sample Output 2

NO

The second and fourth elements are identical.

Sample Input 3

2
10000000 10000000

Sample Output 3

NO


{-# LANGUAGE
  ScopedTypeVariables, BangPatterns, TupleSections, ExplicitForAll,
  LambdaCase, MultiWayIf, Unsafe, RecordWildCards, FlexibleContexts, CPP,
  NoMonomorphismRestriction, GADTs, PatternGuards, MagicHash, UnboxedTuples,
  RankNTypes, EmptyDataDecls, EmptyCase, ViewPatterns, PolyKinds,
  TypeFamilies, OverloadedStrings, FlexibleInstances, UndecidableInstances,
  DefaultSignatures, GeneralizedNewtypeDeriving, StandaloneDeriving,
  DeriveGeneric, DeriveFunctor, DeriveDataTypeable, DeriveFoldable,
  DeriveTraversable, DeriveDataTypeable, FlexibleInstances,
  MultiParamTypeClasses #-}
{-# OPTIONS_GHC -O2 #-}

#define PHASE_FUSED [1]
#define PHASE_INNER [0]
#define INLINE_FUSED INLINE PHASE_FUSED
#define INLINE_INNER INLINE PHASE_INNER

import Prelude
import Data.Bits
import Data.List
import Data.Maybe
import Data.Tuple
import Data.Ord
import Data.Int
import Data.Word
import Data.Char
import Data.Ratio
import Data.Function
import Data.STRef
import Data.IORef
import Data.Monoid
import Data.Functor
import Data.Functor.Identity
import Data.Data
import Data.Typeable
import GHC.Generics
import System.IO
import System.IO.Unsafe (unsafeDupablePerformIO, unsafePerformIO)
import Control.Arrow
import Control.Applicative
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.State.Strict
import Control.Monad.ST
import Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)
import qualified Control.Monad.ST.Lazy as STL
-- import Control.Monad.ST.Safe
import Control.DeepSeq
import Data.Coerce
import qualified Data.ByteString as BSW
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as BSLW
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.ByteString.Builder as BSB
import qualified Data.ByteString.Unsafe as BSU
import qualified Data.ByteString.Internal as BSU
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as IMS
import qualified Data.IntMap.Lazy as IML
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Storable.Mutable as VSM
import qualified Data.Vector.Primitive as VP
import qualified Data.Vector.Primitive.Mutable as VPM
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import qualified Data.Vector.Fusion.Bundle.Monadic as VFBM
import qualified Data.Vector.Fusion.Bundle as VFB
import qualified Data.Vector.Fusion.Stream.Monadic as VFSM
import qualified Data.Vector.Fusion.Bundle.Size as VFBS
import qualified Data.Vector.Fusion.Util as VFU
import qualified Data.Attoparsec.ByteString.Char8 as Atto
import Debug.Trace
import Unsafe.Coerce
import Foreign.ForeignPtr
import GHC.Exts (build, Int(..), Int#,
                 (+#), (*#), (-#), (<#), (>=#), (==#), quotRemInt#,
                 remInt#, uncheckedIShiftRL#, andI#, orI#,
                isTrue#, Addr#, Ptr(..))

main :: IO ()
main = do
  [r1,c1,r2,c2] <- map readInt . words <$> getLine
  print $ comb (r2+1+c2+1) (r2+1) - comb (r2+c1+1) (r2+1)
           - comb (r1+c2+1) r1 + comb (r1+c1) r1

{-# INLINE_FUSED zipTailWithM_stream #-}
zipTailWithM_stream :: Monad m =>
  (a -> a -> m b) -> VFSM.Stream m a -> VFSM.Stream m b
zipTailWithM_stream f (VFSM.Stream step s) = VFSM.Stream step2 (Nothing, s)
  where
    {-# INLINE_INNER step2 #-}
    step2 (Nothing, s0) = (<$> step s0) $ \res -> case res of
      VFSM.Yield a1 s1 -> VFSM.Skip (Just a1, s1)
      VFSM.Skip     s1 -> VFSM.Skip (Nothing, s1)
      VFSM.Done        -> VFSM.Done
    step2 (Just a0, s0) = step s0 >>= \res -> case res of
      VFSM.Yield a1 s1 -> (`VFSM.Yield` (Just a1, s1)) <$> f a0 a1
      VFSM.Skip     s1 -> return $ VFSM.Skip (Just a0, s1)
      VFSM.Done        -> return $ VFSM.Done

{-# INLINE zipTailWith_stream #-}
zipTailWith_stream :: Monad m =>
  (a -> a -> b) -> VFSM.Stream m a -> VFSM.Stream m b
zipTailWith_stream f = zipTailWithM_stream (\a0 a1 -> return (f a0 a1))

{-# INLINE zipTail_stream #-}
zipTail_stream :: Monad m => VFSM.Stream m a -> VFSM.Stream m (a,a)
zipTail_stream = zipTailWith_stream (,)

{-# INLINE_FUSED zipTailWithM_mbundle #-}
zipTailWithM_mbundle :: Monad m =>
  (a -> a -> m b) -> VFBM.Bundle m v a -> VFBM.Bundle m v b
zipTailWithM_mbundle f VFBM.Bundle{VFBM.sElems = s, VFBM.sSize = n}
  = VFBM.fromStream (zipTailWithM_stream f s) (VFBS.clampedSubtract n 1)

{-# INLINE zipTailWith_mbundle #-}
zipTailWith_mbundle :: Monad m =>
  (a -> a -> b) -> VFBM.Bundle m v a -> VFBM.Bundle m v b
zipTailWith_mbundle f = zipTailWithM_mbundle (\a0 a1 -> return $ f a0 a1)

{-# INLINE zipTail_mbundle #-}
zipTail_mbundle :: Monad m => VFBM.Bundle m v a -> VFBM.Bundle m v (a,a)
zipTail_mbundle = zipTailWith_mbundle (,)

{-# INLINE zipTailWith_bundle #-}
zipTailWith_bundle :: (a -> a -> b) -> VFB.Bundle v a -> VFB.Bundle v b
zipTailWith_bundle = zipTailWith_mbundle

{-# INLINE zipTail_bundle #-}
zipTail_bundle :: VFB.Bundle v a -> VFB.Bundle v (a,a)
zipTail_bundle = zipTail_mbundle

{-# INLINE vZipTailWith #-}
vZipTailWith :: (VG.Vector v a, VG.Vector v b) => (a -> a -> b) -> v a -> v b
vZipTailWith f = VG.unstream . zipTailWith_bundle f . VG.stream

{-# INLINE vZipTail #-}
vZipTail :: (VG.Vector v a, VG.Vector v (a,a)) => v a -> v (a,a)
vZipTail = vZipTailWith (,)

factMax :: Int
factMax = 2000005

factorials :: VU.Vector RemF
factorials
  = VU.scanl' (*) 1 $ VU.tail $ VU.generate (factMax+1) (remF . fromIntegral)

factorial :: Int -> RemF
factorial = (factorials VU.!)

factoInvs :: VU.Vector RemF
factoInvs
  = VU.reverse
  $ VU.scanl' (*) (recip $ VU.last factorials)
  $ VU.enumFromStepN (fromIntegral factMax) (fromIntegral (-1)) factMax

invFacto :: Int -> RemF
invFacto = (factoInvs VU.!)

perm :: Int -> Int -> RemF
perm !n !k
  | k == 0 = 1
  | k < 0 || k > n || n < 0 = 0
  | otherwise = factorial n * invFacto (n-k)

comb :: Int -> Int -> RemF
comb !n !k
  | k == 0 = 1
  | k < 0 || k > n || n < 0 = 0
  | otherwise = factorial n * invFacto k * invFacto (n-k)

data FixedModulus

instance HasWord32 FixedModulus where
  {-# INLINE CONLIKE word32Val #-}
  word32Val = const 1000000007 -- 10^9 + 7

type RemF = Rem FixedModulus

pxyF :: Proxy FixedModulus
pxyF = Proxy
remF :: Word32 -> RemF
{-# INLINE CONLIKE remF #-}
remF = Rem

newtype Magic r = Magic (forall (m :: *). HasWord32 m => Proxy m -> r)

{-# INLINE reifyWord32 #-}
reifyWord32 :: forall a. Word32 ->
  (forall (m :: *). HasWord32 m => Proxy m -> a) -> a
reifyWord32 v f = unsafeCoerce (Magic f :: Magic a) (const v) Proxy

newtype Rem m = Rem {unRem :: Word32} deriving (Eq)

withTypeArgOf :: c a -> d a -> c a
{-# INLINE CONLIKE withTypeArgOf #-}
withTypeArgOf = const

proxyFor :: c a -> Proxy a
{-# INLINE CONLIKE proxyFor #-}
proxyFor = const Proxy

withProxy :: (Proxy m -> c m) -> c m
{-# INLINE withProxy #-}
withProxy f = f Proxy

remP :: Proxy m -> Word32 -> Rem m
{-# INLINE CONLIKE remP #-}
remP = const Rem

{-# INLINE modulus32 #-}
modulus32 :: HasWord32 m => Rem m -> Word32
modulus32 x = word32Val $ proxyFor x

class HasWord32 m where
  word32Val :: Proxy m -> Word32

instance Show (Rem m) where
  {-# INLINE showsPrec #-}
  showsPrec = coerce `asTypeOf` (\f p (Rem v) -> f p v) $ showsPrec

negRem :: HasWord32 m => Rem m -> Rem m
{-# INLINE negRem #-}
negRem x0@(Rem x)
  | x == 0 = Rem 0
  | otherwise = Rem $ modulus32 x0 - x

addRem, subRem, multRem
  :: HasWord32 m => Rem m -> Rem m -> Rem m
{-# INLINE subRem #-}
subRem x0@(Rem x) (Rem y) = Rem $ x-y + if x < y then modulus32 x0 else 0
{-# INLINE addRem #-}
addRem x0@(Rem x) (Rem y) = Rem $ x-negy + if x < negy then m else 0
  where m = modulus32 x0; negy = m-y
{-# INLINE multRem #-}
multRem x0@(Rem x) (Rem y)
  = Rem $ toW32 $ (toW64 x * toW64 y) `rem` toW64 (modulus32 x0)

{-# INLINE fromIntegerRem #-}
fromIntegerRem :: (HasWord32 m) => Integer -> Rem m
fromIntegerRem x = withProxy $ Rem . fromInteger . mod x . toInteger . word32Val

{-# INLINE signumRem #-}
signumRem :: (HasWord32 m) => Rem m -> Rem m
signumRem = (\case True -> Rem 0; False -> Rem 1) . (== Rem 0)

instance HasWord32 m => Num (Rem m) where
  {-# INLINE negate #-}
  negate = negRem
  {-# INLINE (-) #-}
  (-) = subRem
  {-# INLINE (+) #-}
  (+) = addRem
  {-# INLINE (*) #-}
  (*) = multRem
  {-# INLINE fromInteger #-}
  fromInteger = fromIntegerRem
  {-# INLINE abs #-}
  abs = id
  {-# INLINE signum #-}
  signum = signumRem

recipRem :: HasWord32 m => Rem m -> Rem m
{-# INLINE recipRem #-}
recipRem = \x -> x ^ (modulus32 x - 2)

-- works only for primes
instance HasWord32 m => Fractional (Rem m) where
  {-# INLINE recip #-}
  recip = recipRem
  fromRational q = fromInteger (numerator q) / fromInteger (denominator q)

newtype instance VU.Vector (Rem m)
  = VRem { unVRem :: VU.Vector Word32 }
newtype instance VUM.MVector s (Rem m)
  = VMRem { unVMRem :: VUM.MVector s Word32 }
instance VUM.Unbox (Rem m)

instance VGM.MVector VUM.MVector (Rem m) where
  {-# INLINE basicLength #-}
  basicLength = coerce `asTypeOf` (. unVMRem) $ VGM.basicLength
  {-# INLINE basicUnsafeSlice #-}
  basicUnsafeSlice
    = coerce `asTypeOf` (\f x y (VMRem v) -> VMRem $ f x y v)
      $ VGM.basicUnsafeSlice
  {-# INLINE basicOverlaps #-}
  basicOverlaps = coerce `asTypeOf` (`on` unVMRem) $ VGM.basicOverlaps
  {-# INLINE basicUnsafeNew #-}
  basicUnsafeNew = fmap (coerce `asTypeOf` VMRem) . VGM.basicUnsafeNew
  {-# INLINE basicInitialize #-}
  basicInitialize = coerce `asTypeOf` (. unVMRem) $ VGM.basicInitialize
  {-# INLINE basicUnsafeReplicate #-}
  basicUnsafeReplicate !n
    = fmap (coerce `asTypeOf` VMRem) . VGM.basicUnsafeReplicate n
    . unRem
  {-# INLINE basicUnsafeRead #-}
  basicUnsafeRead (VMRem v) i = coerce `asTypeOf` Rem <$>
                                VGM.basicUnsafeRead v i
  {-# INLINE basicUnsafeWrite #-}
  basicUnsafeWrite = coerce `asTypeOf` (\f (VMRem v) n (Rem x) -> f v n x)
                     $ VGM.basicUnsafeWrite
  {-# INLINE basicClear #-}
  basicClear = coerce `asTypeOf` (. unVMRem) $ VGM.basicClear
  {-# INLINE basicSet #-}
  basicSet = coerce `asTypeOf` (\f (VMRem v) (Rem x) -> f v x) $ VGM.basicSet
  {-# INLINE basicUnsafeCopy #-}
  basicUnsafeCopy = coerce `asTypeOf` (`on` unVMRem) $ VGM.basicUnsafeCopy
  {-# INLINE basicUnsafeMove #-}
  basicUnsafeMove = coerce `asTypeOf` (`on` unVMRem) $ VGM.basicUnsafeMove
  {-# INLINE basicUnsafeGrow #-}
  basicUnsafeGrow (VMRem v) !n
    = fmap (coerce `asTypeOf` VMRem) $ VGM.basicUnsafeGrow v n

instance VG.Vector VU.Vector (Rem m) where
  {-# INLINE basicUnsafeFreeze #-}
  basicUnsafeFreeze (VMRem v)
    = (coerce `asTypeOf` VRem) <$> VG.basicUnsafeFreeze v
  {-# INLINE basicUnsafeThaw #-}
  basicUnsafeThaw (VRem v)
    = (coerce `asTypeOf` VMRem) <$> VG.basicUnsafeThaw v
  {-# INLINE basicLength #-}
  basicLength = coerce `asTypeOf` (. unVRem) $ VG.basicLength
  {-# INLINE basicUnsafeSlice #-}
  basicUnsafeSlice
    = coerce `asTypeOf` (\f i l (VRem v) -> VRem $ f i l v)
      $ VG.basicUnsafeSlice
  {-# INLINE basicUnsafeIndexM #-}
  basicUnsafeIndexM (VRem !v) !i = coerce <$> VG.basicUnsafeIndexM v i
  {-# INLINE basicUnsafeCopy #-}
  basicUnsafeCopy
    = coerce `asTypeOf` (\f (VMRem mv) (VRem v) -> f mv v)
      $ VG.basicUnsafeCopy
  {-# INLINE elemseq #-}
  elemseq = const seq

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

IL(putBuilder) = BSB.hPutBuilder stdout

printVecInLines, printVecInSpcSepLn ::
  (VG.Vector v a, ShowAsBuilder a) => v a -> IO ()
IL(printVecInLines) = putBuilder . v2BLines
IL(printVecInSpcSepLn) = putBuilder . v2BSpcSepLn

class ShowAsBuilder a where
  showAsBuilder :: a -> BSB.Builder
  default showAsBuilder :: (Show a) => a -> BSB.Builder
  IL(showAsBuilder) = BSB.string8 . show

-- Inconsistent with show
instance (ShowAsBuilder a, VG.Vector v a) => ShowAsBuilder (v a) where
  IL(showAsBuilder) = v2BSpcSep

#define INS(t,f) instance ShowAsBuilder t where { IL(showAsBuilder)=f }
INS(Int,BSB.intDec)
INS(Int8,BSB.int8Dec)
INS(Int16,BSB.int16Dec)
INS(Int32,BSB.int32Dec)
INS(Int64,BSB.int64Dec)
INS(Word,BSB.wordDec)
INS(Word8,BSB.word8Dec)
INS(Word16,BSB.word16Dec)
INS(Word32,BSB.word32Dec)
INS(Word64,BSB.word64Dec)
INS(Integer,BSB.integerDec)
INS(Float,BSB.floatDec)
INS(Double,BSB.doubleDec)
-- INS(String,BSB.string8) -- Inconsistent with Show
-- INS(BS.ByteString,BSB.byteString) -- Inconsistent with Show
-- INS(BSL.ByteString,BSB.lazyByteString) -- Inconsisitent with Show
#undef INS

-- Inconsistent with Show
instance (ShowAsBuilder a, ShowAsBuilder b) => ShowAsBuilder (a,b) where
  IL(showAsBuilder) = showTupAsBuilder
instance (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c) =>
  ShowAsBuilder (a,b,c) where
  IL(showAsBuilder) = showTup3AsBuilder
instance (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c, ShowAsBuilder d) =>
  ShowAsBuilder (a,b,c,d) where
  IL(showAsBuilder) = showTup4AsBuilder

IL(showTupAsBuilderWith)
  :: (a -> BSB.Builder) -> (b -> BSB.Builder) -> (a,b) -> BSB.Builder
showTupAsBuilderWith showA showB
  = \(a,b) -> (showA a <>) $ BSB.char7 ' ' <> showB b
IL(showTupAsBuilder) :: (ShowAsBuilder a, ShowAsBuilder b)
  => (a,b) -> BSB.Builder
showTupAsBuilder = showTupAsBuilderWith showAsBuilder showAsBuilder

IL(showTup3AsBuilderWith) :: (a -> BSB.Builder) -> (b -> BSB.Builder) ->
  (c -> BSB.Builder) -> (a,b,c) -> BSB.Builder
showTup3AsBuilderWith showA showB showC
  = \(a,b,c) -> (showA a <>) $ (BSB.char7 ' ' <>) $ (showB b <>)
                $ (BSB.char7 ' ' <>) $ showC c
IL(showTup3AsBuilder) :: (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c)
  => (a,b,c) -> BSB.Builder
showTup3AsBuilder
  = showTup3AsBuilderWith showAsBuilder showAsBuilder showAsBuilder

IL(showTup4AsBuilderWith) :: (a -> BSB.Builder) -> (b -> BSB.Builder) ->
  (c -> BSB.Builder) -> (d -> BSB.Builder) -> (a,b,c,d) -> BSB.Builder
showTup4AsBuilderWith showA showB showC showD
  = \(a,b,c,d) -> (showA a <>) $ (BSB.char7 ' ' <>)
                  $ showTup3AsBuilderWith showB showC showD (b,c,d)
IL(showTup4AsBuilder) ::
  (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c, ShowAsBuilder d) =>
  (a,b,c,d) -> BSB.Builder
showTup4AsBuilder = showTup4AsBuilderWith showAsBuilder showAsBuilder
                    showAsBuilder showAsBuilder

v2BSpcSepLn, v2BSpcSep, v2BConcat, v2BLines ::
  (VG.Vector v a, ShowAsBuilder a)
  => v a -> BSB.Builder
IL(v2BSpcSepLn) = v2BSpcSepLnWith showAsBuilder
IL(v2BSpcSep) = v2BSpcSepWith showAsBuilder
IL(v2BConcat) = v2BConcatWith showAsBuilder
IL(v2BLines) = v2BLinesWith showAsBuilder

v2BSpcSepLnWith, v2BSpcSepWith, v2BConcatWith, v2BLinesWith ::
  (VG.Vector v a)
  => (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
IL(v2BSpcSepLnWith) = v2BSpcSepPostfWith $ BS.singleton '\n'
IL(v2BSpcSepWith) = v2BSpcSepPostfWith BS.empty
IL(v2BConcatWith) showFct = VG.foldr ((<>) . showFct) mempty
IL(v2BLinesWith) showFct
  = VG.foldr (\ a -> (showFct a <>) . (BSB.char7 '\n' <>)) mempty

v2BSpcSepPostf :: (VG.Vector v a, ShowAsBuilder a)
  => BS.ByteString -- ^ postfix
  -> v a -> BSB.Builder
IL(v2BSpcSepPostf) = (`v2BSpcSepPostfWith` showAsBuilder)

v2BSpcSepPostfWith :: (VG.Vector v a)
  => BS.ByteString -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
IL(v2BSpcSepPostfWith) = vecToBuilder BS.empty $ BS.singleton ' '

IL(vecToBuilder) :: (VG.Vector v a)
  => BS.ByteString -- ^ prefix
  -> BS.ByteString -- ^ separator
  -> BS.ByteString -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
vecToBuilder !prefix !separator !postfix
  = vecToBuilder_ (BSB.byteString prefix)
                  (BSB.byteString separator)
                  (BSB.byteString postfix)

IL(vecToBuilder_) :: (VG.Vector v a)
  => BSB.Builder -- ^ prefix
  -> BSB.Builder -- ^ separator
  -> BSB.Builder -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
vecToBuilder_ !prefix !separator !postfix showFct = \vec -> prefix <>
  VG.foldr
  (\ a rest !prefx -> prefx <> (showFct a <> rest separator))
  (const postfix) vec mempty

IL(evalVals) :: [a] -> [a]
evalVals xs = build $ \c n -> foldr (c $!) n xs
IL(forceVals) :: (NFData a) => [a] -> [a]
forceVals xs = build $ \c n -> foldr (c $!!) n xs

IL(readLnWith) :: StateT BS.ByteString Maybe a -> IO a
readLnWith parser = fromJust . evalStateT parser <$> BS.getLine
IL(readContentWith) :: StateT BSL.ByteString Maybe a -> IO a
readContentWith parser = fromJust . evalStateT parser <$> BSL.getContents

IL(getVecGLn) :: (VG.Vector v a) =>
  Int -> StateT BS.ByteString Maybe a -> IO (v a)
getVecGLn n s = VG.unfoldrN n (runStateT s) <$> BS.getLine
IL(getVecGRest) :: (VG.Vector v a) =>
  Int -> StateT BSL.ByteString Maybe a -> IO (v a)
getVecGRest n s = VG.unfoldrN n (runStateT s) <$> BSL.getContents
IL(getVecLn) :: Int -> StateT BS.ByteString Maybe a -> IO (V.Vector a)
getVecLn = getVecGLn
IL(getVecRest) :: Int -> StateT BSL.ByteString Maybe a -> IO (V.Vector a)
getVecRest = getVecGRest
IL(getVecULn) :: (VU.Unbox a) =>
  Int -> StateT BS.ByteString Maybe a -> IO (VU.Vector a)
getVecULn = getVecGLn
IL(getVecURest) :: (VU.Unbox a) =>
  Int -> StateT BSL.ByteString Maybe a -> IO (VU.Vector a)
getVecURest = getVecGRest

IL(rIntL) :: StateT BSL.ByteString Maybe Int
rIntL = skipSpecialL $ StateT BSL.readInt
IL(rIntS) :: StateT BS.ByteString Maybe Int
rIntS = skipSpecialS $ StateT BS.readInt
IL(rStrL) :: (MonadState BSL.ByteString m) => m BS.ByteString
rStrL = skipSpecialL $ BSL.toStrict <$> state (BSL.span (>='!'))
IL(rStrS) :: (MonadState BS.ByteString m) => m BS.ByteString
rStrS = skipSpecialS $ state $ BS.span (>='!')
IL(rCharL) :: StateT BSL.ByteString Maybe Char
rCharL = StateT BSL.uncons
IL(rCharS) :: StateT BS.ByteString Maybe Char
rCharS = StateT BS.uncons
IL(dropSpecialL) :: (MonadState BSL.ByteString m) => m ()
dropSpecialL = modify $ BSL.dropWhile (<'!')
IL(dropSpecialS) :: (MonadState BS.ByteString m) => m ()
dropSpecialS = modify $ BS.dropWhile (<'!')
IL(skipSpecialL) :: (MonadState BSL.ByteString m) => m a -> m a
skipSpecialL = (dropSpecialL *>)
IL(skipSpecialS) :: (MonadState BS.ByteString m) => m a -> m a
skipSpecialS = (dropSpecialS *>)

IL(linToMat) :: (VG.Vector v a) => Int -> Int -> v a -> V.Vector (v a)
linToMat h w lvec = vEvalElemsId $ V.generate h (\i -> VG.slice (i*w) w lvec)

IL(mLinToMat) :: (VGM.MVector v a) => Int -> Int -> v s a -> V.Vector (v s a)
mLinToMat h w lvec = vEvalElemsId $ V.generate h (\i -> VGM.slice (i*w) w lvec)

IL(unsafeAddrToSVec) :: Int -> Addr# -> VS.Vector Word8
unsafeAddrToSVec n addr
  = (`VS.unsafeFromForeignPtr0` n)
    $ unsafeDupablePerformIO
    $ newForeignPtr_ $ Ptr addr

IL(vEvalElemsId) :: (VG.Vector v a) => v a -> v a
vEvalElemsId = vMapFoldl (\ !_ !x -> (x,())) ()

IL(vEvalElems) :: (VG.Vector v a) => v a -> ()
vEvalElems = VG.foldl' (\ !_ !_ -> ()) ()

IL(vMapFoldl) :: (VG.Vector v b, VG.Vector v c) =>
  (a -> b -> (c,a)) -> a -> v b -> v c
vMapFoldl f a
  = VG.unstream . VFB.inplace (streamMapFoldl f a) id . VG.stream

streamMapFoldl :: (Functor m) =>
  (a -> b -> (c,a)) -> a -> VFSM.Stream m b -> VFSM.Stream m c
{-# INLINE_FUSED streamMapFoldl #-}
streamMapFoldl f a (VFSM.Stream step s) = VFSM.Stream step1 (a,s)
  where
    {-# INLINE_INNER step1 #-}
    step1 (a0,s0) =  (<$> step s0) $ \r -> case r of
      VFSM.Yield b s1 -> case f a0 b of (c,a1) -> VFSM.Yield c (a1,s1)
      VFSM.Skip    s1 -> VFSM.Skip (a0,s1)
      VFSM.Done       -> VFSM.Done

IL(svecToBS) :: VS.Vector Word8 -> BS.ByteString
svecToBS vec = BSU.fromForeignPtr ptr 0 len
  where (ptr, len) = VS.unsafeToForeignPtr0 vec

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

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

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

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

#undef IL

Score : 600 points

Problem Statement

Snuke is standing on a two-dimensional plane. In one operation, he can move by 1 in the positive x-direction, or move by 1 in the positive y-direction.

Let us define a function f(r, c) as follows:

f(r,c) := (The number of paths from the point (0, 0) to the point (r, c) that Snuke can trace by repeating the operation above)

Given are integers r_1, r_2, c_1, and c_2.
Find the sum of f(i, j) over all pair of integers (i, j) such that r_1 ≤ i ≤ r_2 and c_1 ≤ j ≤ c_2, and compute this value modulo (10^9+7).

Constraints

1 ≤ r_1 ≤ r_2 ≤ 10^6

1 ≤ c_1 ≤ c_2 ≤ 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r_1 c_1 r_2 c_2

Output

Print the sum of f(i, j) modulo (10^9+7).

Sample Input 1

1 1 2 2

Sample Output 1

14

For example, there are two paths from the point (0, 0) to the point (1, 1): (0,0) → (0,1) → (1,1) and (0,0) → (1,0) → (1,1), so f(1,1)=2.

Similarly, f(1,2)=3, f(2,1)=3, and f(2,2)=6. Thus, the sum is 14.

Sample Input 2

314 159 2653 589

Sample Output 2

602215194


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

solve :: [Int] -> Int
solve [h, a]
    | h `mod` a == 0 = s
    | otherwise      = s + 1
    where
        s = h `div` a

Score : 100 points

Problem Statement

Serval is fighting with a monster.

The health of the monster is H.

In one attack, Serval can decrease the monster's health by A.
There is no other way to decrease the monster's health.

Serval wins when the monster's health becomes 0 or below.

Find the number of attacks Serval needs to make before winning.

Constraints

1 \leq H \leq 10^4

1 \leq A \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H A

Output

Print the number of attacks Serval needs to make before winning.

Sample Input 1

10 4

Sample Output 1

3

After one attack, the monster's health will be 6.

After two attacks, the monster's health will be 2.

After three attacks, the monster's health will be -2.

Thus, Serval needs to make three attacks to win.

Sample Input 2

1 10000

Sample Output 2

1

Sample Input 3

10000 1

Sample Output 3

10000


main = do
    [h,a] <- map read <$> (words <$> getLine) :: IO [Int]
    if h `mod` a > 0
        then print $ 1+(h `div` a)
        else print $ (h `div` a)


{-# LANGUAGE BangPatterns #-}

module Main
  ( main
  )
where

import           Control.Applicative
import           Control.Monad
import           Data.Bits
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import           Data.List
import           Data.Maybe
import qualified Data.Vector                   as V
import qualified Data.Vector.Mutable           as MV
import           Control.Monad.ST

parse = fst . fromJust
parseInt = parse . BS.readInt
parseInteger = parse . BS.readInteger
readInt = parseInt <$> BS.getLine
readInteger = parseInteger <$> BS.getLine
readIntList = map parseInt . BS.words <$> BS.getLine
readIntegerList = map parseInteger . BS.words <$> BS.getLine

main = do
  [h, a] <- readIntList
  print $ (h + a - 1) `div` a


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

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

getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

main = do
  [h, a] <- getIntList
  let n = 0
  print $ solve h a n

solve :: Int -> Int -> Int -> Int
solve h a n = if a*n >= h then n else solve h a (n+1)


import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.List
import Data.Maybe
import Data.Ord
import Data.Time
import qualified Data.Vector as VC
import qualified Data.Vector.Mutable as VM

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

readIntegerLists :: Int -> IO [[Integer]]
readIntegerLists n = replicateM n (map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine)

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

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

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

readStringLists :: Int -> IO [[String]]
readStringLists n = replicateM n (map BS.unpack . BS.words <$> BS.getLine)

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

solve h a
  | n == 0 = m
  | otherwise = m + 1
  where
    (m, n) = h `divMod` a


{-# LANGUAGE OverloadedStrings #-}
module Main where

import           Data.List
import           Control.Monad
import           Debug.Trace
import qualified Data.ByteString.Char8         as BC
import           Data.Maybe                     ( fromJust )
import qualified Data.Set                      as S
import qualified Data.IntMap.Strict            as IM
import           Data.Char

readTuple2 :: IO (Int, Int)
readTuple2 = do
    [a, b] <- map (fst . fromJust . BC.readInt) . BC.words <$> BC.getLine
    return (a, b)

readTuple3 :: IO (Int, Int, Int)
readTuple3 = do
    [a, b, c] <- map (fst . fromJust . BC.readInt) . BC.words <$> BC.getLine
    return (a, b, c)

readInt :: IO Int
readInt = fst . fromJust . BC.readInt <$> BC.getLine

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

split :: (a -> Bool) -> [a] -> [[a]]
split f [] = []
split f as =
    let (fo, la) = span f as
        las      = case la of
            [] -> []
            xs -> split f $ tail xs
    in  case fo of
            [] -> las
            xs -> xs : las

main = do
    (n, k) <- readTuple2
    hs <- readInts
    print $ sum $ drop k $ sortOn negate hs

Score : 300 points

Problem Statement

Fennec is fighting with N monsters.

The health of the i-th monster is H_i.

Fennec can do the following two actions:

Attack: Fennec chooses one monster. That monster's health will decrease by 1.

Special Move: Fennec chooses one monster. That monster's health will become 0.

There is no way other than Attack and Special Move to decrease the monsters' health.

Fennec wins when all the monsters' healths become 0 or below.

Find the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning when she can use Special Move at most K times.

Constraints

1 \leq N \leq 2 \times 10^5

0 \leq K \leq 2 \times 10^5

1 \leq H_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
H_1 ... H_N

Output

Print the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning.

Sample Input 1

3 1
4 1 5

Sample Output 1

5

By using Special Move on the third monster, and doing Attack four times on the first monster and once on the second monster, Fennec can win with five Attacks.

Sample Input 2

8 9
7 9 3 2 3 8 4 6

Sample Output 2

0

She can use Special Move on all the monsters.

Sample Input 3

3 0
1000000000 1000000000 1000000000

Sample Output 3

3000000000

Watch out for overflow.


import Control.Monad
import Control.Monad.ST
import Data.Maybe
import Data.List
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as MV
import qualified Data.ByteString.Char8 as BS

main = do
  h: n: _ <- map readAsInt . BS.words <$> BS.getLine :: IO [Int]
  xs <- map (map readAsInt . BS.words) <$> BS.lines <$> BS.getContents :: IO [[Int]]
  putStrLn $ show $ knapsack xs h

readAsInt = fst . fromJust . BS.readInt

knapsack :: [[Int]] -> Int -> Int
knapsack xs k = knapsackMemo xs V.! k
    where knapsackMemo :: [[Int]] -> V.Vector Int
          knapsackMemo [] = V.generate (k+1) $ \j -> if j == 0 then 0 else div maxBound 2
          knapsackMemo ([w, v]: xs) = V.modify evolve $ knapsackMemo xs
              where evolve :: MV.MVector s Int -> ST s ()
                    evolve memo = foldM_ step () [1..k]
                        where step _ j = do
                                passed <- MV.read memo j
                                selected <- MV.read memo (if j < w then 0 else j-w)
                                MV.write memo j $ min passed (selected + v)

Score : 500 points

Problem Statement

Ibis is fighting with a monster.

The health of the monster is H.

Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.

The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.

Ibis wins when the health of the monster becomes 0 or below.

Find the minimum total Magic Points that have to be consumed before winning.

Constraints

1 \leq H \leq 10^4

1 \leq N \leq 10^3

1 \leq A_i \leq 10^4

1 \leq B_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H N
A_1 B_1
:
A_N B_N

Output

Print the minimum total Magic Points that have to be consumed before winning.

Sample Input 1

9 3
8 3
4 2
2 1

Sample Output 1

4

First, let us cast the first spell to decrease the monster's health by 8, at the cost of 3 Magic Points. The monster's health is now 1.

Then, cast the third spell to decrease the monster's health by 2, at the cost of 1 Magic Point. The monster's health is now -1.

In this way, we can win at the total cost of 4 Magic Points.

Sample Input 2

100 6
1 1
2 3
3 9
4 27
5 81
6 243

Sample Output 2

100

It is optimal to cast the first spell 100 times.

Sample Input 3

9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461

Sample Output 3

139815


f x a b
    | b > 0 = f (10*x+a) a (b-1)
    | otherwise = x

solve a b = min (show (f 0 a b)) (show (f 0 b a))
main = do
    [a, b] <- map read . words <$> getLine
    putStrLn $ solve a b

Score : 200 points

Problem Statement

Given are 1-digit positive integers a and b. Consider these two strings: the concatenation of b copies of the digit a, and the concatenation of a copies of the digit b. Which of these is lexicographically smaller?

Constraints

1 \leq a \leq 9

1 \leq b \leq 9

a and b are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

Print the lexicographically smaller of the two strings. (If the two strings are equal, print one of them.)

Sample Input 1

4 3

Sample Output 1

3333

We have two strings 444 and 3333. Between them, 3333 is the lexicographically smaller.

Sample Input 2

7 7

Sample Output 2

7777777


main = do
  ab <- (return . map (read::String->Int) . words) =<< getLine
  let a = minimum ab
  let b = maximum ab
  putStrLn $ take b $ cycle $ show a


f :: [Integer] -> Integer
f (x:[]) = 1
f (x:xs) = if (x < minimum xs) then (1 + f xs) else f xs
main = do
 getLine
 s <- map read.words<$>getLine
 print $ f (reverse s)

Score : 300 points

Problem Statement

Given is a permutation P_1, \ldots, P_N of 1, \ldots, N.
Find the number of integers i (1 \leq i \leq N) that satisfy the following condition:

For any integer j (1 \leq j \leq i), P_i \leq P_j.

Constraints

1 \leq N \leq 2 \times 10^5

P_1, \ldots, P_N is a permutation of 1, \ldots, N.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 ... P_N

Output

Print the number of integers i that satisfy the condition.

Sample Input 1

5
4 2 5 1 3

Sample Output 1

3

i=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j holds for j = 1.

Similarly, i=5 does not satisfy the condition, either. Thus, there are three integers that satisfy the condition.

Sample Input 2

4
4 3 2 1

Sample Output 2

4

All integers i (1 \leq i \leq N) satisfy the condition.

Sample Input 3

6
1 2 3 4 5 6

Sample Output 3

1

Only i=1 satisfies the condition.

Sample Input 4

8
5 7 4 2 6 8 1 3

Sample Output 4

4

Sample Input 5

1
1

Sample Output 5

1


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

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

#if __GLASGOW_HASKELL__ >= 808
import qualified Data.OrdPSQ as PSQ
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

data OrdQ = Ascending | Descending
#endif

--------------------------------------------------------------------------
type A = IOUArray (Int, Int) Int
main = do
    n <- int
    table <- newArray ((1,1),(9,9)) 0 :: IO A
    res <- newIORef 0
    forM_ [1..n] $ \i -> do
        let
            h = digitToInt $ head $ show i
            t = digitToInt $ last $ show i
        when (h /= 0 && t /= 0) $
            readArray table (h,t) >>= \r -> writeArray table (h,t) $ r + 1
    forM_ [1..9] $ \i ->
        forM_ [1..9] $ \j -> do
            a <- readArray table (i,j)
            b <- readArray table (j,i)
            modifyIORef' res (+(a*b))
    readIORef res >>= print

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

-- 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 -> []

#if __GLASGOW_HASKELL__ >= 808
sortV :: (Ord a, VU.Unbox a) => VU.Vector a -> VU.Vector a
sortV v = VU.create $ do
    w <- VU.thaw v
    VAM.sort w
    return w

buildPQL :: Ord a => OrdQ -> [a] -> PSQ.OrdPSQ Int Int a
buildPQL oq xs =
    case oq of
        Ascending -> f $ zip3 [1..l] [1..l] $ sort xs
        Descending -> f $ zip3  [1..l] (map negate [1..l]) $ sort xs
    where
        l = length xs
        f = foldl' g PSQ.empty
        g acc (k,p,v) = PSQ.insert k p v acc

buildPQV :: (Ord a, VU.Unbox a) => OrdQ -> VU.Vector a -> PSQ.OrdPSQ Int Int a
buildPQV oq xs =
    case oq of
        Ascending -> f $ VU.zip3 (VU.generate l (+1)) (VU.generate l (+1)) $ sortV xs
        Descending -> f $ VU.zip3  (VU.generate l (+1)) (VU.generate l $ negate . (+1)) $ sortV xs
    where
        l = VU.length xs
        f = VU.foldl' g PSQ.empty
        g acc (k,p,v) = PSQ.insert k p v acc
#endif

Score : 400 points

Problem Statement

Given is a positive integer N.

Find the number of pairs (A, B) of positive integers not greater than N that satisfy the following condition:

When A and B are written in base ten without leading zeros, the last digit of A is equal to the first digit of B, and the first digit of A is equal to the last digit of B.

Constraints

1 \leq N \leq 2 \times 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

25

Sample Output 1

17

The following 17 pairs satisfy the condition: (1,1), (1,11), (2,2), (2,22), (3,3), (4,4), (5,5), (6,6), (7,7), (8,8), (9,9), (11,1), (11,11), (12,21), (21,12), (22,2), and (22,22).

Sample Input 2

1

Sample Output 2

1

Sample Input 3

100

Sample Output 3

108

Sample Input 4

2020

Sample Output 4

40812

Sample Input 5

200000

Sample Output 5

400000008


import Data.List

main = do
  n <- readLn :: IO Int
  xls <- map (map read . words) <$> lines <$> getContents :: IO [[Int]]
  putStrLn $ show $ count $ sortOn snd $ map (\(x: l: _) -> (let b = x - l in if b < 0 then 0 else b, x + l)) xls

foldlState :: (a -> c -> b -> (a, c)) -> a -> c -> [b] -> a
foldlState f a s l = fst $ foldl (\(a, s) -> f a s) (a, s) l

count ys = foldlState step 0 0 ys
    where step a k (b, e)
              | b < k     = (a, k)
              | otherwise = (a + 1, e)

Score : 200 points

Problem Statement

In a factory, there are N robots placed on a number line.
Robot i is placed at coordinate X_i and can extend its arms of length L_i in both directions, positive and negative.

We want to remove zero or more robots so that the movable ranges of arms of no two remaining robots intersect.
Here, for each i (1 \leq i \leq N), the movable range of arms of Robot i is the part of the number line between the coordinates X_i - L_i and X_i + L_i, excluding the endpoints.

Find the maximum number of robots that we can keep.

Constraints

1 \leq N \leq 100,000

0 \leq X_i \leq 10^9 (1 \leq i \leq N)

1 \leq L_i \leq 10^9 (1 \leq i \leq N)

If i \neq j, X_i \neq X_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 L_1
X_2 L_2
\vdots
X_N L_N

Output

Print the maximum number of robots that we can keep.

Sample Input 1

4
2 4
4 3
9 3
100 5

Sample Output 1

3

By removing Robot 2, we can keep the other three robots.

Sample Input 2

2
8 20
1 10

Sample Output 2

1

Sample Input 3

5
10 1
2 1
4 1
6 1
8 1

Sample Output 3

5