--{-# 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 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 (xs,a) (ys,b) acc i = acc && (x == y)
    where
        x = BC.index xs (i `div` a)
        y = BC.index ys (i `div` b)

solve xs ys n m
    | cond = l
    | otherwise = -1
    where
        l = lcm n m
        a = l `div` n
        b = l `div` m
        k = lcm a b
        g = gcd n m
        cond = foldl' (f (xs,a) (ys,b)) True [0,0+k..l-1]

main = do
    [n,m] <- sLineToIntL
    xs <- strBS
    ys <- strBS
    print $ solve xs ys n m
--------------------------------------------------------------------------

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

You are given a string S of length N and another string T of length M.
These strings consist of lowercase English letters.

A string X is called a good string when the following conditions are all met:

Let L be the length of X. L is divisible by both N and M.

Concatenating the 1-st, (\frac{L}{N}+1)-th, (2 \times \frac{L}{N}+1)-th, ..., ((N-1)\times\frac{L}{N}+1)-th characters of X, without changing the order, results in S.

Concatenating the 1-st, (\frac{L}{M}+1)-th, (2 \times \frac{L}{M}+1)-th, ..., ((M-1)\times\frac{L}{M}+1)-th characters of X, without changing the order, results in T.

Determine if there exists a good string. If it exists, find the length of the shortest such string.

Constraints

1 \leq N,M \leq 10^5

S and T consist of lowercase English letters.

|S|=N

|T|=M

Input

Input is given from Standard Input in the following format:

N M
S
T

Output

If a good string does not exist, print -1; if it exists, print the length of the shortest such string.

Sample Input 1

3 2
acp
ae

Sample Output 1

6

For example, the string accept is a good string.
There is no good string shorter than this, so the answer is 6.

Sample Input 2

6 3
abcdef
abc

Sample Output 2

-1

Sample Input 3

15 9
dnsusrayukuaiia
dujrunuma

Sample Output 3

45


--{-# 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 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 (xs,a) (ys,b) acc i = acc && (x == y)
    where
        x = BC.index xs (i `div` a)
        y = BC.index ys (i `div` b)

solve xs ys n m
    | cond = l
    | otherwise = -1
    where
        l = lcm n m
        g = gcd n m
        a = l `div` n
        b = l `div` m
        cond = VU.foldl' (f (xs,a) (ys,b)) True (VU.fromList [0,0+l..l])

main = do
    [n,m] <- sLineToIntL
    xs <- strBS
    ys <- strBS
    print $ solve xs ys n m
--------------------------------------------------------------------------

-- 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'

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.


import Control.Applicative

main :: IO ()
main = readLn >>= solve >>= putStrLn

solve :: Int -> IO String
solve n = do
  if n == 1
    then return "Hello World"
    else show <$> ((+) <$> readLn <*> readLn)

Score: 100 points

Problem Statement

In 2020, AtCoder Inc. with an annual sales of more than one billion yen (the currency of Japan) has started a business in programming education.

One day, there was an exam where a one-year-old child must write a program that prints Hello World, and a two-year-old child must write a program that receives integers A, B and prints A+B.

Takahashi, who is taking this exam, suddenly forgets his age.

He decides to write a program that first receives his age N (1 or 2) as input, then prints Hello World if N=1, and additionally receives integers A, B and prints A+B if N=2.

Write this program for him.

Constraints

N is 1 or 2.

A is an integer between 1 and 9 (inclusive).

B is an integer between 1 and 9 (inclusive).

Input

Input is given from Standard Input in one of the following formats:

1

2
A
B

Output

If N=1, print Hello World; if N=2, print A+B.

Sample Input 1

1

Sample Output 1

Hello World

As N=1, Takahashi is one year old. Thus, we should print Hello World.

Sample Input 2

2
3
5

Sample Output 2

8

As N=2, Takahashi is two years old. Thus, we should print A+B, which is 8 since A=3 and B=5.


import Control.Monad

main::IO ()
main = do
    age <- readLn
    if age == 1
        then putStrLn "Hello World"
        else do
            [a,b] <- replicateM 2 readLn
            print (a+b)


import Text.Printf
main ::IO()
main = do
    x <- (read::String->Int) <$> getLine
    if x == 1 then putStrLn "Hello World"
    else do
        a <- (read::String->Int) <$> getLine
        b <- (read::String->Int) <$> getLine
        print (a+b)


main = do
  n <- getLine
  if n == "1"
  then putStrLn "Hello World"
  else do
    a <- readLn
    b <- readLn
    print $ a + b


main=interact$f.sum.map read.words;f 1="Hello World";f x=show$x-2


import Control.Applicative

main :: IO ()
main = do
  n <- readLn
  a <- readLn
  b <- readLn
  case n of
    1 -> putStrLn "Hello World"
    2 -> putStrLn $ show (a + b)
    _ -> error "invalid n"


import Control.Monad

main :: IO ()
main = do
  n <- readLn :: IO Int

  when (n==1) $ do
    putStrLn "Hello World"
  when (n==2) $ do
    a <- readLn
    b <- readLn
    print $ a+b


import Control.Monad
main = do
    (n:t:_)<-map read.words<$>getLine::IO [Int]
    ans<-map head.filter (\(_:u:_)->u<=t) <$> replicateM n (map read.words<$>getLine)::IO[Int]
    case ans of
        [] -> putStrLn "TLE"
        _ -> print $ minimum ans

Score : 200 points

Problem Statement

When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.

You, the smartwatch, has found N routes to his home.

If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i.

Find the smallest cost of a route that takes not longer than time T.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq T \leq 1000

1 \leq c_i \leq 1000

1 \leq t_i \leq 1000

The pairs (c_i, t_i) are distinct.

Input

Input is given from Standard Input in the following format:

N T
c_1 t_1
c_2 t_2
:
c_N t_N

Output

Print the smallest cost of a route that takes not longer than time T.

If there is no route that takes not longer than time T, print TLE instead.

Sample Input 1

3 70
7 60
1 80
4 50

Sample Output 1

4

The first route gets him home at cost 7.

The second route takes longer than time T = 70.

The third route gets him home at cost 4.

Thus, the cost 4 of the third route is the minimum.

Sample Input 2

4 3
1 1000
2 4
3 1000
4 500

Sample Output 2

TLE

There is no route that takes not longer than time T = 3.

Sample Input 3

5 9
25 8
5 9
4 10
1000 1000
6 1

Sample Output 3

5


main :: IO()
main = do
    str <- getLine
    putStrLn $ map getsolve str

getsolve :: Char -> Char
getsolve ch = if ch == '1' then '9' else '1'

Score : 100 points

Problem Statement

Cat Snuke is learning to write characters.
Today, he practiced writing digits 1 and 9, but he did it the other way around.

You are given a three-digit integer n written by Snuke.
Print the integer obtained by replacing each digit 1 with 9 and each digit 9 with 1 in n.

Constraints

111 \leq n \leq 999

n is an integer consisting of digits 1 and 9.

Input

Input is given from Standard Input in the following format:

n

Output

Print the integer obtained by replacing each occurrence of 1 with 9 and each occurrence of 9 with 1 in n.

Sample Input 1

119

Sample Output 1

991

Replace the 9 in the ones place with 1, the 1 in the tens place with 9 and the 1 in the hundreds place with 9. The answer is 991.

Sample Input 2

999

Sample Output 2

111


readInt :: String -> Int
readInt = read
main = do
    s <- readInt<$>getLine
    print $ (1110-s)


import qualified Data.ByteString.Char8 as BS
import Data.Maybe (fromJust)
import Data.List

alternateSplit :: [a] -> ([a],[a])
alternateSplit = foldr (\x (l,r)-> (x:r,l)) ([],[])

solve :: [Int] -> Int
solve v
  | length v <= 2 = 0
  | allSame v =  length v `div` 2
  | otherwise  = let (l,r) = alternateSplit v
                  in countChange l + countChange r
  where
    allSame v = all (== head v) v
    f = sum . init . sort . map length . group . sort
    countChange v =
        if allSame v then 0 else f v

main :: IO ()
main = do
    n <- readLn :: IO Int
    v <- map (fst . fromJust . BS.readInt)
        . BS.words <$> BS.getLine :: IO [Int]
    print $ solve v

Score : 300 points

Problem Statement

A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied:

For each i = 1,2,..., n-2, a_i = a_{i+2}.

Exactly two different numbers appear in the sequence.

You are given a sequence v_1,v_2,...,v_n whose length is even.
We would like to make this sequence /\/\/\/ by replacing some of its elements.
Find the minimum number of elements that needs to be replaced.

Constraints

2 \leq n \leq 10^5

n is even.

1 \leq v_i \leq 10^5

v_i is an integer.

Input

Input is given from Standard Input in the following format:

n
v_1 v_2 ... v_n

Output

Print the minimum number of elements that needs to be replaced.

Sample Input 1

4
3 1 3 2

Sample Output 1

1

The sequence 3,1,3,2 is not /\/\/\/, but we can make it /\/\/\/ by replacing one of its elements: for example, replace the fourth element to make it 3,1,3,1.

Sample Input 2

6
105 119 105 119 105 119

Sample Output 2

0

The sequence 105,119,105,119,105,119 is /\/\/\/.

Sample Input 3

4
1 1 1 1

Sample Output 3

2

The elements of the sequence 1,1,1,1 are all the same, so it is not /\/\/\/.


{-# LANGUAGE BangPatterns #-}
import           Control.Exception           (assert)
import           Control.Monad
import           Control.Monad.Primitive
import qualified Control.Monad.ST            as ST
import qualified Data.Array.IO               as IO
import qualified Data.Array.ST               as ST
import qualified Data.Array.Unboxed          as A
import           Data.Bits
import qualified Data.ByteString.Char8       as BS
import           Data.Char
import           Data.Foldable
import           Data.List
import qualified Data.Map.Strict             as Map
import           Data.Maybe
import qualified Data.Sequence               as Seq
import qualified Data.Set                    as Set
import qualified Data.Vector                 as VB
import qualified Data.Vector.Mutable         as VBM
import qualified Data.Vector.Unboxed         as V
import qualified Data.Vector.Unboxed.Mutable as VM
import           Debug.Trace

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine
getIntVec n = V.unfoldrN n (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine

readInteger = fst . fromJust . BS.readInteger
readIntegerList = map readInteger . BS.words
getInteger = readInteger <$> BS.getLine
getIntegerList = readIntegerList <$> BS.getLine

inf :: Int
inf = 10^18

main = do
  s <- getLine
  t <- getLine

  let solve _ _ Nothing _ = False
      solve _ _ _ Nothing = False
      solve [] [] _ _     = True
      solve (c:cs) (x:xs) (Just m1) (Just m2) = let m1' = case Map.lookup c m1 of
                                                      Just x' | x == x'   -> Just m1
                                                              | otherwise -> Nothing
                                                      Nothing -> Just (Map.insert c x m1)
                                                    m2' = case Map.lookup x m2 of
                                                      Just c' | c == c'   -> Just m2
                                                              | otherwise -> Nothing
                                                      Nothing -> Just (Map.insert x c m2)
                                                in solve cs xs m1' m2'

      ans = if solve s t (Just Map.empty) (Just Map.empty) then "Yes" else "No"

  putStrLn ans

Score : 300 points

Problem Statement

You are given strings S and T consisting of lowercase English letters.

You can perform the following operation on S any number of times:

Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1.

Determine if S and T can be made equal by performing the operation zero or more times.

Constraints

1 \leq |S| \leq 2 \times 10^5

|S| = |T|

S and T consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S and T can be made equal, print Yes; otherwise, print No.

Sample Input 1

azzel
apple

Sample Output 1

Yes

azzel can be changed to apple, as follows:

Choose e as c_1 and l as c_2. azzel becomes azzle.

Choose z as c_1 and p as c_2. azzle becomes apple.

Sample Input 2

chokudai
redcoder

Sample Output 2

No

No sequences of operation can change chokudai to redcoder.

Sample Input 3

abcdefghijklmnopqrstuvwxyz
ibyhqfrekavclxjstdwgpzmonu

Sample Output 3

Yes


import Control.Monad
import Data.List as L
import Data.IntMap as M

primes :: Integral a => [a]
primes = takeWhile (<31623) $ L.map fromIntegral ([2, 3] ++ primes' :: [Int])
    where
      primes' = 5 : sieve [] primes' 7
      sieve divs (x : xs) n = ps ++ sieve (divs ++ [x]) xs (x * x)
          where
            isPrime m = and [rem m x /= 0 | x <- divs]
            ps = L.filter isPrime ns
            ns = [y + z | y <- [n, n + 6 .. x * x - 2], z <- [0, 4]]

fac :: [Integer]->M.IntMap Integer->Integer->M.IntMap Integer
fac _ m 1 = m
fac [] m n = M.insert (fromIntegral n) 1 m
fac pa@(p:pr) m n
    |mod n (fromIntegral p)==0=fac pa (M.insertWith(+) (fromIntegral p) 1 m) (div n (fromIntegral p))
    |otherwise =fac pr m n

invmod p g = invmod' 1 0 p 0 1 g
    where invmod' px py pgcd x y gcd
            | m==0 = mod (x+g) g
            | True = invmod' x y gcd (px - (d*x)) (py - (d*y)) m
            where
                m = mod pgcd gcd
                d = div pgcd gcd

divmod a b p = mod (a * invmod b p) p

cmbmod n k p = L.foldl' (\a i->divmod (mod (a*(n-i+1)) p) i p) 1 [1..k]

sol 1 _ = 1
sol _ 1 = 1
sol n m = L.foldl' (\a b -> (a * cmbmod (b+n-1) b 1000000007) `mod` 1000000007) 1 fm
    where fm = elems $ fac primes M.empty m

main=do
    (n:m:_)<-L.map read . words<$>getLine::IO[Integer]
    print $ sol n m

Score : 400 points

Problem Statement

You are given positive integers N and M.

How many sequences a of length N consisting of positive integers satisfy a_1 \times a_2 \times ... \times a_N = M? Find the count modulo 10^9+7.

Here, two sequences a' and a'' are considered different when there exists some i such that a_i' \neq a_i''.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^9

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of the sequences consisting of positive integers that satisfy the condition, modulo 10^9 + 7.

Sample Input 1

2 6

Sample Output 1

4

Four sequences satisfy the condition: \{a_1, a_2\} = \{1, 6\}, \{2, 3\}, \{3, 2\} and \{6, 1\}.

Sample Input 2

3 12

Sample Output 2

18

Sample Input 3

100000 1000000000

Sample Output 3

957870001


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

main :: IO ()
main = breads >>= print . solve

solve :: [Int] -> Int
solve [n, m] = prodOnVal . map mf . group $ sort es
    where
        mf x = fact (calcH $ head x) (length x)
        prodOnVal = foldl' (\l r -> val $ l * r) 1

        calcH v = val $ x * y
            where
                x = prodOnVal [n..(n + v - 1)]
                y = prodOnVal $ map inv [2..v]

        es = dcmp m [2..m]

        dcmp v (x : xs)
            | x > v = []
            | v `mod` x /= 0 = dcmp v xs
            | otherwise = c : dcmp w xs
            where
                (c, w) = count x v
        dcmp _ _ = []

        count = loop 0
            where
                loop acc x v
                    | b == 0 = loop (acc + 1) x a
                    | otherwise = (acc, v)
                    where
                        (a, b) = v `divMod` x

inv :: Int -> Int
inv = (`fact` m)
    where
        m = 10 ^ 9 + 5

fact :: Int -> Int -> Int
fact b e
    | e == 0 = 1
    | odd e = val $ b * fact b (e - 1)
    | otherwise = val $ v * v
    where
        v = fact b $ e `div` 2

val :: Int -> Int
val = (`mod` m)
    where
        m = 10 ^ 9 + 7

breads :: IO [Int]
breads = unfoldr (\s -> second (maybe B.empty snd . B.uncons) <$> B.readInt s) <$> B.getLine


toInt :: (String -> Int)
toInt x = read x ::Int

getInts = do
  x <- getLine
  let y = (map$toInt)$words x
  return y

comb :: Int -> Int -> Int
comb n r = if n - r > r
  then foldl (\acc x -> acc * x `div` (x - n + r) `mod` (10^9+7)) 1 [n-r+1..n]
  else foldl (\acc x -> acc * x `div` (x - r) `mod` (10^9+7)) 1 [r+1..n]

prime :: Int -> Bool
prime n = length([x | x <- [1..n], n `mod` x == 0 ]) == 2

ruijo :: Int -> Int -> Int -> (Int, Int)
ruijo p c n = do
  case n `mod` p of
    0 -> ruijo p (c + 1) (n `div` p)
    _ -> (c, n)

fact :: Int -> Int -> [Int]
fact n c = do
  if c > n then []
  else if prime c && n `mod` c == 0 then
    let (count, new_n) = ruijo c 0 n
        in if count > 0 then [count] ++  fact new_n (c + 1) else fact n (c + 1)
  else
    fact n (c + 1)

main :: IO ()
main = do
  [n, m] <- getInts
  print $ foldl (\acc a -> acc * comb (a+n-1) a  `mod` (10^9+7)) 1 $ fact m 2


import Control.Monad (replicateM)
import Data.List (minimum, scanl', sort, sortBy)

main :: IO ()
main = do
  [n,x] <- map read . words <$> getLine
  as    <- map read . words <$> getLine
  print $ f n x as

f :: Int -> Int -> [Int] -> Int
f n x as
  | x < minas = 0
  | x <= sas  = length $ takeWhile (<= x) $ scanl1 (+) as'
  | x <  2 * sas = length $ takeWhile (<= (2*sas - x)) $ scanl1 (+) sa
  | otherwise    = 0
  where
    minas = minimum as
    sas = sum as
    as' = sort as
    sa  = sortBy (flip compare) as

Score : 200 points

Problem Statement

There are N children, numbered 1, 2, ..., N.

Snuke has decided to distribute x sweets among them.
He needs to give out all the x sweets, but some of the children may get zero sweets.

For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets.
Snuke is trying to maximize the number of happy children by optimally distributing the sweets.
Find the maximum possible number of happy children.

Constraints

All values in input are integers.

2 \leq N \leq 100

1 \leq x \leq 10^9

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Print the maximum possible number of happy children.

Sample Input 1

3 70
20 30 10

Sample Output 1

2

One optimal way to distribute sweets is (20, 30, 20).

Sample Input 2

3 10
20 30 10

Sample Output 2

1

The optimal way to distribute sweets is (0, 0, 10).

Sample Input 3

4 1111
1 10 100 1000

Sample Output 3

4

The optimal way to distribute sweets is (1, 10, 100, 1000).

Sample Input 4

2 10
20 20

Sample Output 4

0

No children will be happy, no matter how the sweets are distributed.


import Data.List

main :: IO ()
main = do
  (n:x:_) <- map read . words <$> getLine :: IO [Int]
  as <- scanl (+) 0 . sort . map read . words <$> getLine
  putStrLn $ show $ subtract 1 $ length $ filter (<= x) as


module Main where

import           Control.Monad
import Control.Monad.Writer

newtype DiffList a = DiffList { getDiffList :: [a] -> [a] }
toDiffList :: [a] -> DiffList a
toDiffList xs = DiffList (xs++)

fromDiffList :: DiffList a -> [a]
fromDiffList (DiffList f) = f []

instance Monoid (DiffList a) where
    mempty = DiffList (\xs -> [] ++ xs)
    (DiffList f) `mappend` (DiffList g) = DiffList (\xs -> f (g xs))

main :: IO ()
main = do
    [h, _] <- (map read . words) <$> getLine
    list   <- map (map read . words) <$> (replicateM h) getLine
    let w=do
            res<-(sequence . map goRight . enumerate2d) list
            (goRight . map last) res
            return ()
    let (_,log)=runWriter w

    putStr
        $(unlines .((show . length .fromDiffList) log :) . map ((unwords . map show) . (\((a, b), (c, d)) -> [a, b, c, d])).fromDiffList)
        log

goRight
    :: [((Int, Int), Int)] -> Writer (DiffList ((Int, Int), (Int, Int))) [((Int, Int), Int)]
goRight []  = return []
goRight [x] = return [x]
goRight (a@(aPoint, aValue) : b@(bPoint, _) : xs) = do
    if even aValue then
        do
            res<-goRight (b : xs)
            return $ a:res
    else
        do
            res<-goRight (fmap (+ 1) b : xs)
            tell $ toDiffList [(aPoint, bPoint)]
            return $ fmap (subtract 1) a : res

enumerate :: [a] -> [(Int, a)]
enumerate = zip [1 ..]

enumerate2d :: [[a]] -> [[((Int, Int), a)]]
enumerate2d =
    (map (\(y, a) -> (map (\(x, b) -> ((y, x), b)) . enumerate) a) . enumerate)

Score : 400 points

Problem Statement

There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).

In Cell (i, j), a_{ij} coins are placed.

You can perform the following operation any number of times:

Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.

Maximize the number of cells containing an even number of coins.

Constraints

All values in input are integers.

1 \leq H, W \leq 500

0 \leq a_{ij} \leq 9

Input

Input is given from Standard Input in the following format:

H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}

Output

Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:

N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'

That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.

In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').

Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.

Sample Input 1

2 3
1 2 3
0 1 1

Sample Output 1

3
2 2 2 3
1 1 1 2
1 3 1 2

Every cell contains an even number of coins after the following sequence of operations:

Move the coin in Cell (2, 2) to Cell (2, 3).

Move the coin in Cell (1, 1) to Cell (1, 2).

Move one of the coins in Cell (1, 3) to Cell (1, 2).

Sample Input 2

3 2
1 0
2 1
1 0

Sample Output 2

3
1 1 1 2
1 2 2 2
3 1 3 2

Sample Input 3

1 5
9 9 9 9 9

Sample Output 3

2
1 1 1 2
1 3 1 4


main = getLine >>= putStrLn . ($ "No") . ($ "Yes") . solve . odd . calc . map read .words

solve a b c = if a then b else c

calc = foldl (*) 1

Score : 100 points

Problem Statement

Find the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive). The order does not matter.

Constraints

2\leq K\leq 100

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive).

Sample Input 1

3

Sample Output 1

2

Two pairs can be chosen: (2,1) and (2,3).

Sample Input 2

6

Sample Output 2

9

Sample Input 3

11

Sample Output 3

30

Sample Input 4

50

Sample Output 4

625


{-#LANGUAGE FlexibleContexts#-}
import Control.Monad
import Control.Monad.State
import Control.Monad.Reader
import Control.Arrow
-- import Control.Comonad
import Data.Maybe
import Data.List
import Data.Bool
import Data.Fixed
import Data.Tuple
import Data.Ratio
import Data.Bits
import qualified Data.Map.Strict as M
import qualified Data.Array.IO as IA
import qualified Data.Vector as V

getI = read <$> getLine :: IO Int
getIs = map read . words <$> getLine :: IO [Int]
getD = read <$> getLine :: IO Double
getDs = map read . words <$> getLine :: IO [Double]
getInt = read <$> getLine :: IO Integer
getInts = map read . words <$> getLine :: IO [Integer]

type Row = Integer
type Col = Integer
type PointI = (Integer, Integer)
type Point = (Int, Int)

mmm = 1000000007
fact n
    | n < 1 = 1
    | True = foldr1 (*) [1..n]
ti = toInteger
fi = fromInteger
fig = fromIntegral
rf = realToFrac

(.<.) :: Integer -> Integer -> Integer
(.<.) f g -- combination
    | g < 1 || f < 1 || f < g = 1
    | True = foldr1 (*) (take (fi g) [f,f-1..]) `div` fact g
(.>.) f g --combination with repetition
    | g < 1 || f < 1 = 1
    | True = fact (f + g - 1) `div` (fact (f - 1) * fact g)
permutation n x
    | n < x || x < 0 = 0
    | True = foldr1 (*) . take x $ [n,n-1..1]

comb = (.<.)
combWp = (.>.)

unique a = unique_ (reverse . sort $ a) [] Nothing
    where
        unique_ [] arr _ = arr
        unique_ (x:xs) arr n
            | n == Just x = unique_ xs arr n
            | otherwise = unique_ xs (x:arr) $ Just x

zeroume keta num
    | (length . show $ num) > keta = show num
    | otherwise = do
        let zeros = take keta $ repeat '0'
        reverse . take keta $ (reverse . show $ num) ++ zeros

i2b num
    | num < 2 = show num
    | otherwise = i2b_ num []
        where
            i2b_ num str
                | num == 0 = str
                | num == 1 = '1':str
                | otherwise = do
                    let next = num `div` 2
                    let this = if odd num then '1' else '0'
                    i2b_ next (this:str)

mapIncr = mapPlus 1
mapPlus n Nothing = Just n
mapPlus n a = (+) n <$> a

countIf f = length . filter f

enumDivisor :: Int -> [Int]
enumDivisor n = do
    let sqrted = floor $ sqrt (fromIntegral n)
        smaller = filter (\x -> mod n x == 0) [1..sqrted]
        bigger = reverse $ map (div n) smaller
    if head bigger == sqrted then smaller ++ (init bigger)
    else smaller ++ bigger

--
--
--

main = do
    [n,x] <- getIs
    putStrLn . show $ count n x

count n x
    | even x = _the n x + _one n x + _ale n x
    | True = _tho n x + _ono n x + _alo n x
    where
        _the n x = (permutation (n `div` x) 3) + (permutation ((n + (x `div` 2)) `div` x) 3)
        _tho n x = permutation (n `div` x) 3
        _one n x = 3 * (permutation (ceiling ((fig n) / (fig x))) 2) + 3 * (permutation (floor ((fig n) / (fig x))) 2)
        _ono n x = 3 * (permutation (n `div` x) 2 )
        _ale n x = (n * 2) `div` x
        _alo n x = n `div` x

Score : 300 points

Problem Statement

You are given integers N and K. Find the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K.
The order of a,b,c does matter, and some of them can be the same.

Constraints

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

N and K are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K.

Sample Input 1

3 2

Sample Output 1

9

(1,1,1),(1,1,3),(1,3,1),(1,3,3),(2,2,2),(3,1,1),(3,1,3),(3,3,1) and (3,3,3) satisfy the condition.

Sample Input 2

5 3

Sample Output 2

1

Sample Input 3

31415 9265

Sample Output 3

27

Sample Input 4

35897 932

Sample Output 4

114191


Score : 100 points

Problem Statement

There is an N-car train.

You are given an integer i. Find the value of j such that the following statement is true: "the i-th car from the front of the train is the j-th car from the back."

Constraints

1 \leq N \leq 100

1 \leq i \leq N

Input

Input is given from Standard Input in the following format:

N i

Output

Print the answer.

Sample Input 1

4 2

Sample Output 1

3

The second car from the front of a 4-car train is the third car from the back.

Sample Input 2

1 1

Sample Output 2

1

Sample Input 3

15 11

Sample Output 3

5


import Control.Applicative

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

main = do
    [n, i] <- f
    putStrLn $ show $ n - i + 1


import Control.Monad
import Data.List

main = do
 [a,b] <- map (read :: String -> Int).words<$>getLine
 s <- replicateM a (getLine)
 putStrLn.unlines $ solve s

solve s = transpose $ sieve $ transpose (sieve s)

sieve :: [[Char]] -> [[Char]]
sieve [] = []
sieve (a:as) | elem '#' a = [a] ++ sieve as
 | otherwise = sieve as

Score : 200 points

Problem Statement

There is a grid of squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column from the left is represented as (i, j).
Each square is black or white.
The color of the square is given as an H-by-W matrix (a_{i, j}).
If a_{i, j} is ., the square (i, j) is white; if a_{i, j} is #, the square (i, j) is black.

Snuke is compressing this grid.
He will do so by repeatedly performing the following operation while there is a row or column that consists only of white squares:

Operation: choose any one row or column that consists only of white squares, remove it and delete the space between the rows or columns.

It can be shown that the final state of the grid is uniquely determined regardless of what row or column is chosen in each operation.
Find the final state of the grid.

Constraints

1 \leq H, W \leq 100

a_{i, j} is . or #.

There is at least one black square in the whole grid.

Input

Input is given from Standard Input in the following format:

H W
a_{1, 1}...a_{1, W}
:
a_{H, 1}...a_{H, W}

Output

Print the final state of the grid in the same format as input (without the numbers of rows and columns); see the samples for clarity.

Sample Input 1

4 4
##.#
....
##.#
.#.#

Sample Output 1

###
###
.##

The second row and the third column in the original grid will be removed.

Sample Input 2

3 3
#..
.#.
..#

Sample Output 2

#..
.#.
..#

As there is no row or column that consists only of white squares, no operation will be performed.

Sample Input 3

4 5
.....
.....
..#..
.....

Sample Output 3

#

Sample Input 4

7 6
......
....#.
.#....
..#...
..#...
......
.#..#.

Sample Output 4

..#
#..
.#.
.#.
#.#


import Control.Monad
import Data.List
import qualified Data.ByteString.Char8 as B
import qualified Data.Vector.Unboxed as V
main=do
    (n:k:_)<-map read.words<$>getLine::IO[Int]
    xs<-unfoldr (B.readInt.B.dropWhile(==' '))<$>B.getLine
    --
    print $ minimum $ if elem 0 xs then solve (k-1) (filter (/=0) xs) else solve k xs
--
solve 0 _ = [0]
solve k xs@(x:_)
    | x > 0 = [xs !! (k-1)]
    | la < 0 = [negate $ (reverse xs) !! (k-1)]
    | True = solve' k xs (drop (k-1) xs)
    where la = last xs

solve' _ _ [] = []
solve' k (l:ls) (r:rs)
    | r<0 = (solve' k ls rs)
    | l>0 = []
    | True = (min (r*2-l) (r-l*2) ) : (solve' k ls rs)

Score : 300 points

Problem Statement

There are N candles placed on a number line.
The i-th candle from the left is placed on coordinate x_i.
Here, x_1 < x_2 < ... < x_N holds.

Initially, no candles are burning.
Snuke decides to light K of the N candles.

Now, he is at coordinate 0.
He can move left and right along the line with speed 1.
He can also light a candle when he is at the same position as the candle, in negligible time.

Find the minimum time required to light K candles.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq N

x_i is an integer.

|x_i| \leq 10^8

x_1 < x_2 < ... < x_N

Input

Input is given from Standard Input in the following format:

N K
x_1 x_2 ... x_N

Output

Print the minimum time required to light K candles.

Sample Input 1

5 3
-30 -10 10 20 50

Sample Output 1

40

He should move and light candles as follows:

Move from coordinate 0 to -10.

Light the second candle from the left.

Move from coordinate -10 to 10.

Light the third candle from the left.

Move from coordinate 10 to 20.

Light the fourth candle from the left.

Sample Input 2

3 2
10 20 30

Sample Output 2

20

Sample Input 3

1 1
0

Sample Output 3

0

There may be a candle placed at coordinate 0.

Sample Input 4

8 5
-9 -7 -4 -3 1 2 3 4

Sample Output 4

10


{-# OPTIONS_GHC -O #-}

import Data.List (scanl, unfoldr, foldl')
import qualified Data.ByteString.Char8 as B
import qualified Data.IntSet as S

import Control.Monad
import Control.Monad.ST
import Data.STRef
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as MV

msort :: MV.STVector s Int -> MV.STVector s Int -> (Int,Int) -> STRef s Int -> ST s ()
msort xv buf (s,e) ra
  | n == 1 = return ()
  | True = do
    msort xv buf lr ra
    msort xv buf rr ra
    forM_ [s..e-1] $ \i -> MV.unsafeRead xv i >>= MV.unsafeWrite buf i
    ac <- msort2 xv buf s lr rr 0 0
    modifySTRef' ra (+ac)
  where
    n = e - s
    m = s + (n+1) `div` 2
    lr@(ls,le) = (s,m)
    rr@(rs,re) = (m,e)
--
msort2 :: MV.STVector s Int -> MV.STVector s Int -> Int -> (Int,Int) -> (Int,Int) -> Int -> Int -> ST s Int
msort2 xv buf s (ls,le) (rs,re) ra rc
  | ls==le && rs==re = return ra
  | rs==re = MV.unsafeRead buf ls >>= MV.unsafeWrite xv s >> msort2 xv buf (s+1) (ls+1,le) (rs,re) (ra+rc) rc
  | ls==le = MV.unsafeRead buf rs >>= MV.unsafeWrite xv s >> msort2 xv buf (s+1) (ls,le) (rs+1,re) ra (rc+1)
  | True = do
    l <- MV.unsafeRead buf ls
    r <- MV.unsafeRead buf rs
    if l<=r
      then MV.unsafeWrite xv s l >> msort2 xv buf (s+1) (ls+1,le) (rs,re) (ra+rc) rc
      else MV.unsafeWrite xv s r >> msort2 xv buf (s+1) (ls,le) (rs+1,re) ra (rc+1)

invc ss = runST $ do
  v <- V.unsafeThaw $ V.fromList ss :: ST s (MV.STVector s Int)
  let len = MV.length v
  ra <- newSTRef (0::Int)
  buf <- MV.new len :: ST s (MV.STVector s Int)
  msort v buf (0, len) ra
  readSTRef ra

si as x = invc $ tail $ scanl (\ac a->if a>=x then ac+1 else ac-1) 0 as

bsearch f (a,b)
  | a+1 == b = a
  | f m  = bsearch f (m,b)
  | True = bsearch f (a,m)
  where m = (a + (b-a)`div`2)

ff av as tn x = niv >= tn `div` 2
  where
    niv = (-) tn $ si as $ av V.! x

main=do
  n<-readLn::IO Int
  as<-unfoldr (B.readInt.B.dropWhile(==' '))<$>B.getLine::IO[Int]
  let av = V.fromList $ S.toAscList $ S.fromList as
  let tn = (n*(n+1))`div`2
  print $ (V.!) av $ bsearch (ff av as tn) (-1,V.length av)

Score : 700 points

Problem Statement

We will define the median of a sequence b of length M, as follows:

Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.

For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.

Snuke comes up with the following problem.

You are given a sequence a of length N.
For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a.
We will list m_{l, r} for all pairs (l, r) to create a new sequence m.
Find the median of m.

Constraints

1 \leq N \leq 10^5

a_i is an integer.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the median of m.

Sample Input 1

3
10 30 20

Sample Output 1

30

The median of each contiguous subsequence of a is as follows:

The median of (10) is 10.

The median of (30) is 30.

The median of (20) is 20.

The median of (10, 30) is 30.

The median of (30, 20) is 30.

The median of (10, 30, 20) is 20.

Thus, m = (10, 30, 20, 30, 30, 20) and the median of m is 30.

Sample Input 2

1
10

Sample Output 2

10

Sample Input 3

10
5 9 5 9 8 9 3 5 4 3

Sample Output 3

8


import Data.List
import qualified Data.ByteString.Char8 as B
import qualified Data.Vector.Unboxed as V
import qualified Data.IntSet as S

msort xs
  | n==1 = xs
  | True = msort' 0 (msort us) (msort vs)
  where
    n = length xs
    (us,vs) = splitAt (n`div`2) xs

msort' c [] []          = []
msort' c ((x,xc):xs) [] = (x,xc+c) : msort' c xs []
msort' c [] (y:ys)      = y        : msort' (c+1) [] ys
msort' c xa@((x,xc):xs) ya@((y,yc):ys)
  | x<=y = (x,xc+c) : (msort' c xs ya)
  | True= (y,yc)   : (msort' (c+1) xa ys)

si as x = sum.map snd.msort.zip ss $ repeat 0
  where
    bs = map (\a->if a>=x then 1 else (-1)) as
    ss = scanl1 (+) bs

bsearch f (a,b)
    | a+1 == b = a
    | f m  = bsearch f (m,b)
    | True = bsearch f (a,m)
    where m = (a + (b-a)`div`2)

ff av as tn x = iv >= (tn+1) `div` 2
  where
    iv = (-) tn $ si as $ av V.! x

main=do
  n<-readLn::IO Int
  as<-unfoldr (B.readInt.B.dropWhile(==' '))<$>B.getLine::IO[Int]
  av<-pure $ V.fromList $ S.toList $ S.fromList as
  print $ (V.!) av $ bsearch (ff av as $ (n*(n-1))`div`2) (-1,V.length av)


import Data.List
import Control.Monad

f [l,r] as = take (r-l+1) (drop (l-1) as)

median [] = 0
median ns =
    let l = length ns
        n = div l 2
        ms = sort ns
    in (ms !! (n+1))

main :: IO ()
main = do
    n <- read <$> getLine :: IO Int
    as <- map read.words <$> getLine :: IO [Int]
    print $ median (map median [f [l,r] as | r <- [1..n], l <- [1..r]])


import Control.Applicative

main :: IO ()
main = do
    [a, b] <- map read . words <$> getLine
    putStrLn $ show (a * b - a - b + 1)

Score: 100 points

Problem Statement

There is a farm whose length and width are A yard and B yard, respectively. A farmer, John, made a vertical road and a horizontal road inside the farm from one border to another, as shown below: (The gray part represents the roads.)

What is the area of this yard excluding the roads? Find it.

Note

It can be proved that the positions of the roads do not affect the area.

Constraints

A is an integer between 2 and 100 (inclusive).

B is an integer between 2 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

A B

Output

Print the area of this yard excluding the roads (in square yards).

Sample Input 1

2 2

Sample Output 1

1

In this case, the area is 1 square yard.

Sample Input 2

5 7

Sample Output 2

24

In this case, the area is 24 square yards.


main :: IO ()
main = do
  n <- readLn :: IO Int
  print $ solve n

solve :: Int -> Int
solve n
  | n < 105 = 0
  | n >= 165 = 2
  | otherwise = 1

Score: 200 points

Problem Statement

The number 105 is quite special - it is odd but still it has eight divisors.
Now, your task is this: how many odd numbers with exactly eight positive divisors are there between 1 and N (inclusive)?

Constraints

N is an integer between 1 and 200 (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print the count.

Sample Input 1

105

Sample Output 1

1

Among the numbers between 1 and 105, the only number that is odd and has exactly eight divisors is 105.

Sample Input 2

7

Sample Output 2

0

1 has one divisor. 3, 5 and 7 are all prime and have two divisors. Thus, there is no number that satisfies the condition.


import Control.Monad
import Control.Applicative
import Data.List
import Data.Array
import Data.Array.IO
import Data.Maybe
import Data.Bits
import Data.Ord
import qualified Data.ByteString.Char8 as BS
import qualified Data.Set as Set
import Debug.Trace

modifyArray arr i f = readArray arr i >>= \x -> writeArray arr i (f x)

listToTuple2 [a,b] = (a,b)
listToTuple3 [a,b,c] = (a,b,c)
listToTuple4 [a,b,c,d] = (a,b,c,d)

getWords = getLine >>= return . words

readIntBS = fst . fromJust . BS.readInt

main :: IO ()
main = do
  (n,m,query) <- listToTuple3 . map read . words <$> getLine :: IO (Int,Int,Int)

  dat <- map (listToTuple2 . map readIntBS . BS.words) <$> (replicateM m BS.getLine) :: IO [(Int,Int)]

  arr <- newArray ((0,0),(n,n)) 0 :: IO (IOArray (Int,Int) Int)

  forM_ dat $ \(l,r) -> do
    modifyArray arr (l,r) (+1)

  forM_ [0..n] $ \l -> do
    forM_ [1..n] $ \r -> do
      ((+) <$> readArray arr (l,r-1) <*> readArray arr (l,r)) >>= \x -> writeArray arr (l,r) x

  forM_ [1..n] $ \l -> do
    forM_ [0..n] $ \r -> do
      ((+) <$> readArray arr (l-1,r) <*> readArray arr (l,r)) >>= \x -> writeArray arr (l,r) x

  replicateM query $ do
    (p,q) <- listToTuple2 . map readIntBS . BS.words <$> BS.getLine :: IO (Int,Int)

    a <- readArray arr (q,q)
    b <- readArray arr (p-1,q)
    c <- readArray arr (q,p-1)
    d <- readArray arr (p-1,p-1)

    print $ a - b - c + d

  return ()

Score: 400 points

Problem Statement

In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east.
A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i).
Takahashi the king is interested in the following Q matters:

The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.

Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.

Constraints

N is an integer between 1 and 500 (inclusive).

M is an integer between 1 and 200 \ 000 (inclusive).

Q is an integer between 1 and 100 \ 000 (inclusive).

1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)

1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q

Output

Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.

Sample Input 1

2 3 1
1 1
1 2
2 2
1 2

Sample Output 1

3

As all the trains runs within the section from City 1 to City 2, the answer to the only query is 3.

Sample Input 2

10 3 2
1 5
2 8
7 10
1 7
3 10

Sample Output 2

1
1

The first query is on the section from City 1 to 7. There is only one train that runs strictly within that section: Train 1.
The second query is on the section from City 3 to 10. There is only one train that runs strictly within that section: Train 3.

Sample Input 3

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

Sample Output 3

7
9
10
6
8
9
6
7
8
10


main = do
  [a, b] <- words <$> getLine
  let a' = read a :: Int
  let b' = read b :: Int
  print $ a' `mod` b'

Score : 100 points

Problem Statement

Takahashi has decided to distribute N AtCoder Crackers to K users of as evenly as possible.
When all the crackers are distributed, find the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Constraints

1 \leq N,K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Sample Input 1

7 3

Sample Output 1

1

When the users receive two, two and three crackers, respectively, the (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user, is 1.

Sample Input 2

100 10

Sample Output 2

0

The crackers can be distributed evenly.

Sample Input 3

1 1

Sample Output 3

0


import Control.Applicative ((<$>))
import Data.Bool (bool)

main :: IO ()
main = solve <$> readLn >>= putStrLn

solve :: Int -> String
solve n = bool "No" "Yes" $ n `elem` ls
  where ls = do
          i <- [0..25]
          j <- [0..14]
          let x = 4 * i + 7 * j
          return x

Score : 200 points

Problem Statement

La Confiserie d'ABC sells cakes at 4 dollars each and doughnuts at 7 dollars each.
Determine if there is a way to buy some of them for exactly N dollars. You can buy two or more doughnuts and two or more cakes, and you can also choose to buy zero doughnuts or zero cakes.

Constraints

N is an integer between 1 and 100, inclusive.

Input

Input is given from Standard Input in the following format:

N

Output

If there is a way to buy some cakes and some doughnuts for exactly N dollars, print Yes; otherwise, print No.

Sample Input 1

11

Sample Output 1

Yes

If you buy one cake and one doughnut, the total will be 4 + 7 = 11 dollars.

Sample Input 2

40

Sample Output 2

Yes

If you buy ten cakes, the total will be 4 \times 10 = 40 dollars.

Sample Input 3

3

Sample Output 3

No

The prices of cakes (4 dollars) and doughnuts (7 dollars) are both higher than 3 dollars, so there is no such way.


import Control.Applicative ((<$>))
import Data.List

main :: IO ()
main = do
  [n,m] <- map read . words <$> getLine :: IO [Integer]
  as <- map read . words <$> getLine :: IO [Integer]
  let
    ss = map (`mod` m) $ scanl1 (+) as
    cs = map (\i -> (head i,genericLength i)) $ group $ sort ss

  print $ sum $ map (\(i,c) -> c*(c-1)`div`2 + (if i == 0 then c else 0)) cs

Score : 400 points

Problem Statement

There are N boxes arranged in a row from left to right. The i-th box from the left contains A_i candies.

You will take out the candies from some consecutive boxes and distribute them evenly to M children.

Such being the case, find the number of the pairs (l, r) that satisfy the following:

l and r are both integers and satisfy 1 \leq l \leq r \leq N.

A_l + A_{l+1} + ... + A_r is a multiple of M.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

2 \leq M \leq 10^9

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the number of the pairs (l, r) that satisfy the conditions.

Note that the number may not fit into a 32-bit integer type.

Sample Input 1

3 2
4 1 5

Sample Output 1

3

The sum A_l + A_{l+1} + ... + A_r for each pair (l, r) is as follows:

Sum for (1, 1): 4

Sum for (1, 2): 5

Sum for (1, 3): 10

Sum for (2, 2): 1

Sum for (2, 3): 6

Sum for (3, 3): 5

Among these, three are multiples of 2.

Sample Input 2

13 17
29 7 5 7 9 51 7 13 8 55 42 9 81

Sample Output 2

6

Sample Input 3

10 400000000
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

25


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

main :: IO ()
main = do
  r <- readLn
  putStrLn $ solve r

solve :: Int -> String
solve r
  | r < 1200 = "ABC"
  | r < 2800 = "ARC"
  | otherwise = "AGC"

Score : 100 points

Problem Statement

A programming competition site AtCode regularly holds programming contests.

The next contest on AtCode is called ABC, which is rated for contestants with ratings less than 1200.

The contest after the ABC is called ARC, which is rated for contestants with ratings less than 2800.

The contest after the ARC is called AGC, which is rated for all contestants.

Takahashi's rating on AtCode is R. What is the next contest rated for him?

Constraints

0 ≤ R ≤ 4208

R is an integer.

Input

Input is given from Standard Input in the following format:

R

Output

Print the name of the next contest rated for Takahashi (ABC, ARC or AGC).

Sample Input 1

1199

Sample Output 1

ABC

1199 is less than 1200, so ABC will be rated.

Sample Input 2

1200

Sample Output 2

ARC

1200 is not less than 1200 and ABC will be unrated, but it is less than 2800 and ARC will be rated.

Sample Input 3

4208

Sample Output 3

AGC


main = do
    (a:s) <- getLine
    let p1 = a == 'A'
        p2 = (== 1) . length $ filter (== 'C') (init (tail s))
        p3 = (== length s - 1) . length $ filter (`elem` ['a'..'z']) $ filter (/= 'C') s
    putStrLn $ if p1 && p2 && p3 then "AC" else "WA"

Score : 200 points

Problem Statement

You are given a string S. Each character of S is uppercase or lowercase English letter.
Determine if S satisfies all of the following conditions:

The initial character of S is an uppercase A.

There is exactly one occurrence of C between the third character from the beginning and the second to last character (inclusive).

All letters except the A and C mentioned above are lowercase.

Constraints

4 ≤ |S| ≤ 10 (|S| is the length of the string S.)

Each character of S is uppercase or lowercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

If S satisfies all of the conditions in the problem statement, print AC; otherwise, print WA.

Sample Input 1

AtCoder

Sample Output 1

AC

The first letter is A, the third letter is C and the remaining letters are all lowercase, so all the conditions are satisfied.

Sample Input 2

ACoder

Sample Output 2

WA

The second letter should not be C.

Sample Input 3

AcycliC

Sample Output 3

WA

The last letter should not be C, either.

Sample Input 4

AtCoCo

Sample Output 4

WA

There should not be two or more occurrences of C.

Sample Input 5

Atcoder

Sample Output 5

WA

The number of C should not be zero, either.


import Data.Char

main :: IO ()
main = do
  s <- getString
  putStrLn $ if and [p s, q s, r s] then "AC" else "WA"
  where
    p s = head s == 'A'
    q s = any (== 'C') . init . tail . tail $ s
    r s = countIf isLower s + 2 == length s

getString :: IO String
getString = getLine

countIf :: (a -> Bool) -> [a] -> Int
countIf f = length . filter f


import Data.Char

solver::String->Bool
solver str = let a:b:rest = str in
             let restrv = reverse rest in
             let l:rest2 = restrv in
             let notC = filter ('C'/=) rest2 in
             let isC  = filter ('C'==) rest2 in
             (a=='A')&&(isLower b)&&(isLower l)&&(length isC ==1)&&(and (map isLower notC))

main::IO()
main=do
  str<-getLine
  putStr (if solver str then "AC\n" else "WA\n")


import Control.Monad
import Data.List
import Data.Maybe
main=do
    (d:g:_)<-map read.words<$>getLine::IO[Int]
    pcs<-liftM (zip [1..]) $ replicateM d $ (\(p:c:_)->(p,c)).map read.words<$>getLine::IO[(Int,(Int,Int))]
    --
    print.minimum.(0:).mapMaybe (s g pcs) $ tail $ t [1..d]
--
s g pcs ns
    | cs + ri*100*rp < g = Nothing
    | cs >= g = Just cp
    | True = Just (cp + ((g-cs)+ri*100-1) `div` (ri*100))
    where
        (sel, res) = sp ns pcs
        (cs,cp) = f sel
        (ri,(rp,_)) = mx res

f = foldl' (\(a,s) (i,(p,c))->(a+100*i*p+c, s+p)) (0,0)

t [] = [[]]
t (x:xs) = concatMap (\u->[x:u,u]) $ t xs

sp ns = partition (\(i,_)->elem i ns)

mx :: [(Int,a)] -> (Int,a)
mx = maximumBy (\(ai,_) (bi,_)->compare ai bi)

Score : 300 points

Problem Statement

A programming competition site AtCode provides algorithmic problems.
Each problem is allocated a score based on its difficulty.
Currently, for each integer i between 1 and D (inclusive), there are p_i problems with a score of 100i points.
These p_1 + … + p_D problems are all of the problems available on AtCode.

A user of AtCode has a value called total score.
The total score of a user is the sum of the following two elements:

Base score: the sum of the scores of all problems solved by the user.

Perfect bonuses: when a user solves all problems with a score of 100i points, he/she earns the perfect bonus of c_i points, aside from the base score (1 ≤ i ≤ D).

Takahashi, who is the new user of AtCode, has not solved any problem.
His objective is to have a total score of G or more points.
At least how many problems does he need to solve for this objective?

Constraints

1 ≤ D ≤ 10

1 ≤ p_i ≤ 100

100 ≤ c_i ≤ 10^6

100 ≤ G

All values in input are integers.

c_i and G are all multiples of 100.

It is possible to have a total score of G or more points.

Input

Input is given from Standard Input in the following format:

D G
p_1 c_1
:
p_D c_D

Output

Print the minimum number of problems that needs to be solved in order to have a total score of G or more points. Note that this objective is always achievable (see Constraints).

Sample Input 1

2 700
3 500
5 800

Sample Output 1

3

In this case, there are three problems each with 100 points and five problems each with 200 points. The perfect bonus for solving all the 100-point problems is 500 points, and the perfect bonus for solving all the 200-point problems is 800 points. Takahashi's objective is to have a total score of 700 points or more.

One way to achieve this objective is to solve four 200-point problems and earn a base score of 800 points. However, if we solve three 100-point problems, we can earn the perfect bonus of 500 points in addition to the base score of 300 points, for a total score of 800 points, and we can achieve the objective with fewer problems.

Sample Input 2

2 2000
3 500
5 800

Sample Output 2

7

This case is similar to Sample Input 1, but the Takahashi's objective this time is 2000 points or more. In this case, we inevitably need to solve all five 200-point problems, and by solving two 100-point problems additionally we have the total score of 2000 points.

Sample Input 3

2 400
3 500
5 800

Sample Output 3

2

This case is again similar to Sample Input 1, but the Takahashi's objective this time is 400 points or more. In this case, we only need to solve two 200-point problems to achieve the objective.

Sample Input 4

5 25000
20 1000
40 1000
50 1000
30 1000
1 1000

Sample Output 4

66

There is only one 500-point problem, but the perfect bonus can be earned even in such a case.


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
import           Data.Foldable (foldl')
import           Data.List     (transpose)

main :: IO ()
main = do
  s <- getLine
  print $ solve s

solve :: String -> Int
solve s = abc where
  [n, a, ab, abc] = foldl' f [1, 0, 0, 0] s
  f [n, a, ab, abc] 'A' = [n, add a n, ab, abc]
  f [n, a, ab, abc] 'B' = [n, a, add ab a, abc]
  f [n, a, ab, abc] 'C' = [n, a, ab, add abc ab]
  f [n, a, ab, abc] '?' = map (foldr add 0) . transpose $ map (f [n, a, ab, abc]) "ABC"

add :: Int -> Int -> Int
add x y = (x + y) `mod` modN

modN :: Int
modN = 10 ^ 9 + 7

Score : 400 points

Problem Statement

The ABC number of a string T is the number of triples of integers (i, j, k) that satisfy all of the following conditions:

1 ≤ i < j < k ≤ |T| (|T| is the length of T.)

T_i = A (T_i is the i-th character of T from the beginning.)

T_j = B

T_k = C

For example, when T = ABCBC, there are three triples of integers (i, j, k) that satisfy the conditions: (1, 2, 3), (1, 2, 5), (1, 4, 5). Thus, the ABC number of T is 3.

You are given a string S. Each character of S is A, B, C or ?.

Let Q be the number of occurrences of ? in S. We can make 3^Q strings by replacing each occurrence of ? in S with A, B or C. Find the sum of the ABC numbers of all these strings.

This sum can be extremely large, so print the sum modulo 10^9 + 7.

Constraints

3 ≤ |S| ≤ 10^5

Each character of S is A, B, C or ?.

Input

Input is given from Standard Input in the following format:

S

Output

Print the sum of the ABC numbers of all the 3^Q strings, modulo 10^9 + 7.

Sample Input 1

A??C

Sample Output 1

8

In this case, Q = 2, and we can make 3^Q = 9 strings by by replacing each occurrence of ? with A, B or C. The ABC number of each of these strings is as follows:

AAAC: 0

AABC: 2

AACC: 0

ABAC: 1

ABBC: 2

ABCC: 2

ACAC: 0

ACBC: 1

ACCC: 0

The sum of these is 0 + 2 + 0 + 1 + 2 + 2 + 0 + 1 + 0 = 8, so we print 8 modulo 10^9 + 7, that is, 8.

Sample Input 2

ABCBC

Sample Output 2

3

When Q = 0, we print the ABC number of S itself, modulo 10^9 + 7. This string is the same as the one given as an example in the problem statement, and its ABC number is 3.

Sample Input 3

????C?????B??????A???????

Sample Output 3

979596887

In this case, the sum of the ABC numbers of all the 3^Q strings is 2291979612924, and we should print this number modulo 10^9 + 7, that is, 979596887.


main :: IO ()
main = do
  xs <- getInts
  print $ maximum xs - minimum xs

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

Score : 100 points

Problem Statement

You have three tasks, all of which need to be completed.

First, you can complete any one task at cost 0.

Then, just after completing the i-th task, you can complete the j-th task at cost |A_j - A_i|.

Here, |x| denotes the absolute value of x.

Find the minimum total cost required to complete all the task.

Constraints

All values in input are integers.

1 \leq A_1, A_2, A_3 \leq 100

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

Print the minimum total cost required to complete all the task.

Sample Input 1

1 6 3

Sample Output 1

5

When the tasks are completed in the following order, the total cost will be 5, which is the minimum:

Complete the first task at cost 0.

Complete the third task at cost 2.

Complete the second task at cost 3.

Sample Input 2

11 5 5

Sample Output 2

6

Sample Input 3

100 100 100

Sample Output 3

0


main = do
    s <- concat . replicate 2 <$> getLine
    t <- getLine
    let l = length t
    putStrLn $ if elem t . take l . map (take l) . iterate tail $ s
        then "Yes"
        else "No"

Score : 200 points

Problem Statement

You are given string S and T consisting of lowercase English letters.

Determine if S equals T after rotation.

That is, determine if S equals T after the following operation is performed some number of times:

Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}.

Here, |X| denotes the length of the string X.

Constraints

2 \leq |S| \leq 100

|S| = |T|

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S equals T after rotation, print Yes; if it does not, print No.

Sample Input 1

kyoto
tokyo

Sample Output 1

Yes

In the first operation, kyoto becomes okyot.

In the second operation, okyot becomes tokyo.

Sample Input 2

abc
arc

Sample Output 2

No

abc does not equal arc after any number of operations.

Sample Input 3

aaaaaaaaaaaaaaab
aaaaaaaaaaaaaaab

Sample Output 3

Yes


import           Control.Monad
import qualified Data.ByteString.Char8 as B
import           Data.Set              (Set (..))
import qualified Data.Set              as S

data Interval = Interval Int Int

instance Eq (Interval) where
  (Interval x y) /= (Interval z w)
    | y <= z    = False
    | w <= x    = False
    | otherwise = True

instance Ord (Interval) where
  compare (Interval x y) (Interval z w)
    | y <= z    = LT
    | w <= x    = GT
    | otherwise = EQ

main :: IO ()
main = do
  [n, m] <- readInts
  i6ls <- replicateM m readInterval
  print $ solve i6ls

readInts :: IO [Int]
readInts = map (maybe err fst . B.readInt) . B.words <$> B.getLine
  where err = error "parse error"

readInterval :: IO Interval
readInterval = (\[x, y] -> Interval x y) <$> readInts

solve :: [Interval] -> Int
solve = S.size . foldr insert S.empty

merge :: Interval -> Interval -> Interval
merge (Interval x y) (Interval z w)
  | y <= z    = err
  | w <= x    = err
  | otherwise = Interval (x `max` z) (y `min` w)
  where err = error "merge error"

insert :: Interval -> Set Interval -> Set Interval
insert i8s set
  | i8s `S.member` set = S.insert (merge i8s i8s') set
  | otherwise          = S.insert i8s set
  where
    i8s'  = S.elemAt index set
    index = S.findIndex i8s set

Score : 400 points

Problem Statement

There are N islands lining up from west to east, connected by N-1 bridges.

The i-th bridge connects the i-th island from the west and the (i+1)-th island from the west.

One day, disputes took place between some islands, and there were M requests from the inhabitants of the islands:

Request i: A dispute took place between the a_i-th island from the west and the b_i-th island from the west. Please make traveling between these islands with bridges impossible.

You decided to remove some bridges to meet all these M requests.

Find the minimum number of bridges that must be removed.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq a_i < b_i \leq N

All pairs (a_i, b_i) are distinct.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the minimum number of bridges that must be removed.

Sample Input 1

5 2
1 4
2 5

Sample Output 1

1

The requests can be met by removing the bridge connecting the second and third islands from the west.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

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

Sample Output 3

4


import Control.Monad
import Data.Maybe
import qualified Data.Set as S
import Debug.Trace

main :: IO ()
main = do
    n <- read <$> getLine :: IO Int
    qs <- replicateM n (map read . words <$> getLine) :: IO [[Int]]
    -- mapM_ query' qs
    mapM_ (putStrLn . (\f->if f then "Yes" else "No") . (\[a,b,c,d] -> let
        sa = mod (mod a b + d) b - mod a b
        in f a b c d
        )) qs

f a b c d
    | a < b     = False
    | otherwise = f' a b c d sa S.empty
    where
    sa = mod (mod a b + d) b - mod a b

f' a b c d sa already
    | a < b                = False
    | c < a && a < b       = False
    | isNothing a''        = False
    | a `S.member` already = True
    | otherwise            = f' (fromJust a'') b c d sa already'
    where
    a'       = a `mod` b
    a''      = case (mod a b + d < b, sa /= 0) of
                (True, _)      -> Nothing
                (False, True)  -> Just $ mod (a' + sa * div (c-a') sa) b + d
                (False, False) -> Just $ a' + d

    already' = a `S.insert` already

Score : 600 points

Problem Statement

Ringo Mart, a convenience store, sells apple juice.

On the opening day of Ringo Mart, there were A cans of juice in stock in the morning.
Snuke buys B cans of juice here every day in the daytime.
Then, the manager checks the number of cans of juice remaining in stock every night.
If there are C or less cans, D new cans will be added to the stock by the next morning.

Determine if Snuke can buy juice indefinitely, that is, there is always B or more cans of juice in stock when he attempts to buy them.
Nobody besides Snuke buy juice at this store.

Note that each test case in this problem consists of T queries.

Constraints

1 \leq T \leq 300

1 \leq A, B, C, D \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

T
A_1 B_1 C_1 D_1
A_2 B_2 C_2 D_2
:
A_T B_T C_T D_T

In the i-th query, A = A_i, B = B_i, C = C_i, D = D_i.

Output

Print T lines. The i-th line should contain Yes if Snuke can buy apple juice indefinitely in the i-th query; No otherwise.

Sample Input 1

14
9 7 5 9
9 7 6 9
14 10 7 12
14 10 8 12
14 10 9 12
14 10 7 11
14 10 8 11
14 10 9 11
9 10 5 10
10 10 5 10
11 10 5 10
16 10 5 10
1000000000000000000 17 14 999999999999999985
1000000000000000000 17 15 999999999999999985

Sample Output 1

No
Yes
No
Yes
Yes
No
No
Yes
No
Yes
Yes
No
No
Yes

In the first query, the number of cans of juice in stock changes as follows: (D represents daytime and N represents night.)

9
→D 2
→N 11
→D 4
→N 13
→D 6
→N 6
→D x

In the second query, the number of cans of juice in stock changes as follows:

9
→D 2
→N 11
→D 4
→N 13
→D 6
→N 15
→D 8
→N 8
→D 1
→N 10
→D 3
→N 12
→D 5
→N 14
→D 7
→N 7
→D 0
→N 9
→D 2
→N 11
→D …

and so on, thus Snuke can buy juice indefinitely.

Sample Input 2

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

Sample Output 2

No
No
No
No
No
No
Yes
Yes
No
No
No
No
Yes
Yes
Yes
No
No
No
Yes
Yes
Yes
No
No
No


ans :: Int -> Int
ans n =
    if n `mod` 2 == 0 then n
    else n*2

main = do
    x <- readLn
    print $ (ans x)

Score : 100 points

Problem Statement

You are given a positive integer N.
Find the minimum positive integer divisible by both 2 and N.

Constraints

1 \leq N \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum positive integer divisible by both 2 and N.

Sample Input 1

3

Sample Output 1

6

6 is divisible by both 2 and 3.
Also, there is no positive integer less than 6 that is divisible by both 2 and 3.
Thus, the answer is 6.

Sample Input 2

10

Sample Output 2

10

Sample Input 3

999999999

Sample Output 3

1999999998


readInt :: String -> Int
readInt = read

main = getLine >>= print . solve . readInt

solve n = if even n then n else n * 2


main = do
  n <- getLine
  xs <- map read . words <$> getLine
  putStrLn . show . solve $ xs

solve :: [Int] -> Int
solve xs = (maximum xs) - (minimum xs)

Score : 200 points

Problem Statement

You are given an integer sequence A of length N.
Find the maximum absolute difference of two elements (with different indices) in A.

Constraints

2 \leq N \leq 100

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum absolute difference of two elements (with different indices) in A.

Sample Input 1

4
1 4 6 3

Sample Output 1

5

The maximum absolute difference of two elements is A_3-A_1=6-1=5.

Sample Input 2

2
1000000000 1

Sample Output 2

999999999

Sample Input 3

5
1 1 1 1 1

Sample Output 3

0


main :: IO ()
main = do
  _  <- getLine
  as <- map read . words <$> getLine :: IO [Int]
  print . f $ as

f ::[Int] -> Int
f = g (1,1)

g :: (Int,Int) -> [Int] -> Int
g (s,l) [] = l-s
g sl@(s,l) (x:xs)
  | x < s = g (x,l) xs
  | l < x = g (s,x) xs
  | otherwise = g sl xs


{-# LANGUAGE BangPatterns, MultiWayIf #-}
import Control.Arrow
import Control.Applicative
import Control.Monad.Fix
import Control.Monad.ST
import Data.Int
import Data.Foldable
import Data.List
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
import qualified Data.ByteString.Char8 as B
import Debug.Trace

-- `binSearch p` searches for an integer `n` s.t. n = min {p k | k \in nat}
binSearch :: (Int -> Bool) -> Int
binSearch pred = if pred 0
  then 0
  else let k = findInterval pred in search (k `div` 2) k
 where
  findInterval pred = head $ dropWhile (not . pred) $ map (2 ^) [0 ..]

  -- (x,y]
  search x y
    | y - x == 1
    = y
    | otherwise
    = let z = (x + y) `div` 2 in if pred z then search x z else search z y

solve :: Int -> VU.Vector Int -> Int
solve !n !an = binSearch canSplitWithin
 where
  sum = VU.sum an

  isWithIn d acc =
    length acc == 4 && let acc' = sort acc in last acc' - head acc' <= d

  canSplitWithin d = isWithIn d $ (\(!x, _, _) -> x) $ fix
    (\(!f) (!acc, !cur, !i) -> if
      | i == VU.length an -> (cur : acc, 0, i)
      | cur + an VU.! i < thMin -> f (acc, cur + an VU.! i, i + 1)
      | cur > thMax -> ([], 0, 0)
      | length acc >= 4 -> ([], 0, 0)
      | otherwise ->
      	 let res1 =
               let result@(!acc', _, _) = f ((cur + an VU.! i) : acc, 0, i + 1)
               in  if isWithIn d acc' then Just result else Nothing
             res2 =
               let result@(!acc', _, _) = f (acc, an VU.! i + cur, i + 1)
               in  if isWithIn d acc' then Just result else Nothing
         in  maybe ([], 0, 0) id $ res1 <|> res2
    )
    ([], 0, 0)
   where
    thMin = ceiling (fromIntegral (sum - 3 * d) / 4)
    thMax = floor (fromIntegral (sum + 3 * d) / 4)

main = do
  let readInt :: Integral a => B.ByteString -> Maybe (a, B.ByteString)
      readInt = fmap (first fromIntegral . second B.tail) . B.readInt

  n  <- (\vec -> (vec VU.! 0)) . VU.unfoldrN 1 readInt <$> B.getLine
  an <- VU.unfoldrN n readInt <$> B.getLine
  print $ solve n an

Score : 600 points

Problem Statement

Snuke has an integer sequence A of length N.

He will make three cuts in A and divide it into four (non-empty) contiguous subsequences B, C, D and E.
The positions of the cuts can be freely chosen.

Let P,Q,R,S be the sums of the elements in B,C,D,E, respectively.
Snuke is happier when the absolute difference of the maximum and the minimum among P,Q,R,S is smaller.
Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S.

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S.

Sample Input 1

5
3 2 4 1 2

Sample Output 1

2

If we divide A as B,C,D,E=(3),(2),(4),(1,2), then P=3,Q=2,R=4,S=1+2=3.
Here, the maximum and the minimum among P,Q,R,S are 4 and 2, with the absolute difference of 2.
We cannot make the absolute difference of the maximum and the minimum less than 2, so the answer is 2.

Sample Input 2

10
10 71 84 33 6 47 23 25 52 64

Sample Output 2

36

Sample Input 3

7
1 2 3 1000000000 4 5 6

Sample Output 3

999999994


import Data.List
import Data.Bits
import Data.List.Split

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

Score : 100 points

Problem Statement

There is always an integer in Takahashi's mind.

Initially, the integer in Takahashi's mind is 0. Takahashi is now going to eat four symbols, each of which is + or -. When he eats +, the integer in his mind increases by 1; when he eats -, the integer in his mind decreases by 1.

The symbols Takahashi is going to eat are given to you as a string S. The i-th character in S is the i-th symbol for him to eat.

Find the integer in Takahashi's mind after he eats all the symbols.

Constraints

The length of S is 4.

Each character in S is + or -.

Input

Input is given from Standard Input in the following format:

S

Output

Print the integer in Takahashi's mind after he eats all the symbols.

Sample Input 1

+-++

Sample Output 1

2

Initially, the integer in Takahashi's mind is 0.

The first integer for him to eat is +. After eating it, the integer in his mind becomes 1.

The second integer to eat is -. After eating it, the integer in his mind becomes 0.

The third integer to eat is +. After eating it, the integer in his mind becomes 1.

The fourth integer to eat is +. After eating it, the integer in his mind becomes 2.

Thus, the integer in Takahashi's mind after he eats all the symbols is 2.

Sample Input 2

-+--

Sample Output 2

-2

Sample Input 3

----

Sample Output 3

-4


main :: IO ()
main = do
  s <- getLine
  print $ solve s

solve :: String -> Int
solve ('+':xs) = 1 + solve xs
solve ('-':xs) = -1 + solve xs
solve _ = 0


import Data.Char(digitToInt)

main = do
    n <- getLine
    let m = (fmap digitToInt) n
    if read n `mod` sum m == 0
        then putStrLn "Yes"
        else putStrLn "No"

Score : 200 points

Problem Statement

Let S(n) denote the sum of the digits in the decimal notation of n.
For example, S(101) = 1 + 0 + 1 = 2.

Given an integer N, determine if S(N) divides N.

Constraints

1 \leq N \leq 10^9

Input

Input is given from Standard Input in the following format:

N

Output

If S(N) divides N, print Yes; if it does not, print No.

Sample Input 1

12

Sample Output 1

Yes

In this input, N=12.
As S(12) = 1 + 2 = 3, S(N) divides N.

Sample Input 2

101

Sample Output 2

No

As S(101) = 1 + 0 + 1 = 2, S(N) does not divide N.

Sample Input 3

999999999

Sample Output 3

Yes


import Data.List

solve :: Int -> Int -> [Int] -> Int
solve n k numbers = countBefore + countAfter
  where Just indexOf1 = elemIndex 1 numbers
        count v = if v `mod` (k - 1) == 0 then v `div` (k - 1) else (v `div` (k - 1)) + 1
        countBefore = count indexOf1
        countAfter  = count (n - indexOf1 - 1)

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

Score : 300 points

Problem Statement

There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N.

On this sequence, Snuke can perform the following operation:

Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements.

Snuke would like to make all the elements in this sequence equal by repeating the operation above some number of times.
Find the minimum number of operations required.
It can be proved that, Under the constraints of this problem, this objective is always achievable.

Constraints

2 \leq K \leq N \leq 100000

A_1, A_2, ..., A_N is a permutation of 1, 2, ..., N.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of operations required.

Sample Input 1

4 3
2 3 1 4

Sample Output 1

2

One optimal strategy is as follows:

In the first operation, choose the first, second and third elements. The sequence A becomes 1, 1, 1, 4.

In the second operation, choose the second, third and fourth elements. The sequence A becomes 1, 1, 1, 1.

Sample Input 2

3 3
1 2 3

Sample Output 2

1

Sample Input 3

8 3
7 3 1 8 4 6 2 5

Sample Output 3

4


import Control.Monad
import Control.Monad.ST
import qualified Data.Array as A
import qualified Data.Array.ST as ST
import qualified Data.Array.Unboxed as AU
import qualified Data.ByteString.Char8 as BS
import Data.Char
import Data.Int
import qualified Data.IntMap as IM
import Data.List
import qualified Data.Map as M
import Data.Maybe
import Data.Ord
import qualified Data.Set as S
import Data.Time
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

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)

main = do
  [n, k] <- readInt
  a <- readInt
  print $ solve n k a

solve n k a = 1 + m (n - k) (k - 1)
  where
    b = takeWhile (/= 1) a
    c = tail $ dropWhile (/= 1) a
    b' = m (length b) (k - 1)
    c' = m (length c) (k - 1)

m a x
  | a `mod` x == 0 = a `div` x
  | otherwise = a `div` x + 1


import Data.Bool
main=interact$bool"Yay!"":(".any(>8).map read.words

Score: 100 points

Problem Statement

E869120's and square1001's 16-th birthday is coming soon.

Takahashi from AtCoder Kingdom gave them a round cake cut into 16 equal fan-shaped pieces.

E869120 and square1001 were just about to eat A and B of those pieces, respectively,

when they found a note attached to the cake saying that "the same person should not take two adjacent pieces of cake".

Can both of them obey the instruction in the note and take desired numbers of pieces of cake?

Constraints

A and B are integers between 1 and 16 (inclusive).

A+B is at most 16.

Input

Input is given from Standard Input in the following format:

A B

Output

If both E869120 and square1001 can obey the instruction in the note and take desired numbers of pieces of cake, print Yay!; otherwise, print :(.

Sample Input 1

5 4

Sample Output 1

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 2

8 8

Sample Output 2

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 3

11 4

Sample Output 3

:(

In this case, there is no way for them to take desired number of pieces, unfortunately.


-- modules to import --

import qualified Data.ByteString.Char8
import qualified Data.Maybe
import           Prelude

-- functions for this task --

readInteger'    = Prelude.fst . Data.Maybe.fromJust . Data.ByteString.Char8.readInteger
readListInteger = Prelude.map readInteger' . Data.ByteString.Char8.words

getInteger     = readInteger'    <$> Data.ByteString.Char8.getLine
getListInteger = readListInteger <$> Data.ByteString.Char8.getLine

task_A :: Integer -> Integer -> Data.ByteString.Char8.ByteString
task_A num_piece_a num_piece_b
        | stat_a && stat_b == True = Data.ByteString.Char8.pack $ "Yay!"
        | Prelude.otherwise        = Data.ByteString.Char8.pack $ ":("
        where
        stat_a = num_piece_a <= (8 :: Integer)
        stat_b = num_piece_b <= (8 :: Integer)

-- the main process is as follows --

main :: IO ()
main = do

        -- STEP.01
        -- read out the given data
        [num_piece_a, num_piece_b] <- getListInteger

        -- STEP.02
        -- calculate & output the answer of this task
        Data.ByteString.Char8.putStrLn $ task_A (num_piece_a) (num_piece_b)


import Control.Monad
import Data.List
main=do
    a<-readLn :: IO Int
    b<-readLn :: IO Int
    let s = abs $ a-b
    let r = 16-(a+b)
    putStrLn $ case s of
        s | s<=1 -> "Yay!"
        s | s*2<=r -> "Yay!"
        _ | True -> ":("


main=do
 n<-getLine;a<-map read.words<$>getLine
 print(sum[f x|x<-a])
  where f x = (if(mod x 2)==0 then (1+(f (quot x 2))) else 0)

Score: 300 points

Problem Statement

As AtCoder Beginner Contest 100 is taking place, the office of AtCoder, Inc. is decorated with a sequence of length N, a = {a_1, a_2, a_3, ..., a_N}.

Snuke, an employee, would like to play with this sequence.

Specifically, he would like to repeat the following operation as many times as possible:

For every i satisfying 1 \leq i \leq N, perform one of the following: "divide a_i by 2" and "multiply a_i by 3".
Here, choosing "multiply a_i by 3" for every i is not allowed, and the value of a_i after the operation must be an integer.

At most how many operations can be performed?

Constraints

N is an integer between 1 and 10 \ 000 (inclusive).

a_i is an integer between 1 and 1 \ 000 \ 000 \ 000 (inclusive).

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 a_3 ... a_N

Output

Print the maximum number of operations that Snuke can perform.

Sample Input 1

3
5 2 4

Sample Output 1

3

The sequence is initially {5, 2, 4}. Three operations can be performed as follows:

First, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {15, 6, 2}.

Next, multiply a_1 by 3, divide a_2 by 2 and multiply a_3 by 3. The sequence is now {45, 3, 6}.

Finally, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {135, 9, 3}.

Sample Input 2

4
631 577 243 199

Sample Output 2

0

No operation can be performed since all the elements are odd. Thus, the answer is 0.

Sample Input 3

10
2184 2126 1721 1800 1024 2528 3360 1945 1280 1776

Sample Output 3

39


import Data.Array.IO
import Data.List
import Control.Monad

main = do
  (n:m:_) <- getLine >>= return . map read . words :: IO [Int]
  dat <- getContents >>= return . map ((\(x:y:z:_) -> (x,y,z)) . map read . words) . lines :: IO [(Integer,Integer,Integer)]

  print $ maximum $ map (solve m dat) [(1,1,1), (-1,1,1), (1,-1,1), (1,1,-1), (-1,-1,1), (-1,1,-1), (1,-1,-1), (-1,-1,-1)]

  where
    solve m xs (a,b,c) = sum . take m . reverse . sort $ map (\(x,y,z) -> a*x+b*y+c*z) xs

Score: 400 points

Problem Statement

Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100.

The shop sells N kinds of cakes.

Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The i-th kind of cake has the beauty of x_i, the tastiness of y_i and the popularity of z_i.

These values may be zero or negative.

Ringo has decided to have M pieces of cakes here. He will choose the set of cakes as follows:

Do not have two or more pieces of the same kind of cake.

Under the condition above, choose the set of cakes to maximize (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity).

Find the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.

Constraints

N is an integer between 1 and 1 \ 000 (inclusive).

M is an integer between 0 and N (inclusive).

x_i, y_i, z_i \ (1 \leq i \leq N) are integers between -10 \ 000 \ 000 \ 000 and 10 \ 000 \ 000 \ 000 (inclusive).

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1 z_1
x_2 y_2 z_2
: :
x_N y_N z_N

Output

Print the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.

Sample Input 1

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

Sample Output 1

56

Consider having the 2-nd, 4-th and 5-th kinds of cakes. The total beauty, tastiness and popularity will be as follows:

Beauty: 1 + 3 + 9 = 13

Tastiness: 5 + 5 + 7 = 17

Popularity: 9 + 8 + 9 = 26

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 13 + 17 + 26 = 56. This is the maximum value.

Sample Input 2

5 3
1 -2 3
-4 5 -6
7 -8 -9
-10 11 -12
13 -14 15

Sample Output 2

54

Consider having the 1-st, 3-rd and 5-th kinds of cakes. The total beauty, tastiness and popularity will be as follows:

Beauty: 1 + 7 + 13 = 21

Tastiness: (-2) + (-8) + (-14) = -24

Popularity: 3 + (-9) + 15 = 9

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 21 + 24 + 9 = 54. This is the maximum value.

Sample Input 3

10 5
10 -80 21
23 8 38
-94 28 11
-26 -2 18
-69 72 79
-26 -86 -54
-72 -50 59
21 65 -32
40 -94 87
-62 18 82

Sample Output 3

638

If we have the 3-rd, 4-th, 5-th, 7-th and 10-th kinds of cakes, the total beauty, tastiness and popularity will be -323, 66 and 249, respectively.

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 323 + 66 + 249 = 638. This is the maximum value.

Sample Input 4

3 2
2000000000 -9000000000 4000000000
7000000000 -5000000000 3000000000
6000000000 -1000000000 8000000000

Sample Output 4

30000000000

The values of the beauty, tastiness and popularity of the cakes and the value to be printed may not fit into 32-bit integers.


{-# OPTIONS_GHC -O #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}

import Control.Monad
import Data.List
import qualified Data.ByteString.Char8 as B
import qualified Data.Vector as V
import Data.Array
import Data.Array.IO

comb :: Int -> [a] -> [[a]]
comb 0 _ = [[]]
comb n xa@(x:xs)
    | length xa == n = [xa]
    | otherwise = ( map (x:) $ comb (n-1) xs) ++ (comb n xs)

main=do
    [n,m]<-map read.words<$>getLine::IO[Int]
    xyzs <- (replicateM n $ unfoldr (B.readInt.B.dropWhile(==' ')) <$> B.getLine)
    --
    print $ maximum $ map (foldl' (\a b -> a + (abs b)) 0. foldl' (\[x,y,z] [a,b,c] -> [a+x,b+y,c+z]) [0,0,0])  $ comb m xyzs


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

main = do
  [a,b] <- map (read::String->Int) . words <$> getLine
  print $ sum [1..b-a] - b

Score : 200 points

Problem Statement

In some village, there are 999 towers that are 1,(1+2),(1+2+3),...,(1+2+3+...+999) meters high from west to east, at intervals of 1 meter.

It had been snowing for a while before it finally stopped. For some two adjacent towers located 1 meter apart, we measured the lengths of the parts of those towers that are not covered with snow, and the results are a meters for the west tower, and b meters for the east tower.

Assuming that the depth of snow cover and the altitude are the same everywhere in the village, find the amount of the snow cover.

Assume also that the depth of the snow cover is always at least 1 meter.

Constraints

1 \leq a < b < 499500(=1+2+3+...+999)

All values in input are integers.

There is no input that contradicts the assumption.

Input

Input is given from Standard Input in the following format:

a b

Output

If the depth of the snow cover is x meters, print x as an integer.

Sample Input 1

8 13

Sample Output 1

2

The heights of the two towers are 10 meters and 15 meters, respectively.
Thus, we can see that the depth of the snow cover is 2 meters.

Sample Input 2

54 65

Sample Output 2

1


import Control.Applicative ((<$>))

main :: IO ()
main = solve <$> map read <$> words <$> getLine >>= print

solve :: [Int] -> Int
solve [a, b] = sum [1 .. b-a] - b


main :: IO ()
main = do
  n <- readLn
  print $ g n

f :: Int -> [(Int,Int)]
f n = [(x, n-x) | x <- [1..(n `div` 2)]]

sod
  :: Int -> Int
sod = sum . sod'

sod'
  :: Int -> [Int]
sod' n
  | q == 0 = [r]
  | otherwise = r : sod' q
  where
    (q,r) = quotRem n 10

sod2 :: Int -> Int -> Int
sod2 x y = sod x + sod y

g :: Int -> Int
g = minimum . map (uncurry sod2) . f

Score : 200 points

Problem Statement

Takahashi has two positive integers A and B.

It is known that A plus B equals N.
Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10).

Constraints

2 ≤ N ≤ 10^5

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B".

Sample Input 1

15

Sample Output 1

6

When A=2 and B=13, the sums of their digits are 2 and 4, which minimizes the value in question.

Sample Input 2

100000

Sample Output 2

10


digsum 0 = 0
digsum x = x `mod` 10 + digsum (x `div` 10)

main = do
  n <- readLn :: IO Int
  print $ minimum [digsum a + digsum b | a<-[1..n], let b=n-a, a<=b]


main = do
  [a, b] <- (map read . words) <$> getLine
  let add = a + b
  let sub = a - b
  let multi = a * b
  let ans = maximum [add, sub, multi]
  print ans

Score : 100 points

Problem Statement

You are given two integers A and B.
Find the largest value among A+B, A-B and A \times B.

Constraints

-1000 \leq A,B \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the largest value among A+B, A-B and A \times B.

Sample Input 1

3 1

Sample Output 1

4

3+1=4, 3-1=2 and 3 \times 1=3. The largest among them is 4.

Sample Input 2

4 -2

Sample Output 2

6

The largest is 4 - (-2) = 6.

Sample Input 3

0 0

Sample Output 3

0


main = do
    [a, b] <- map read . words <$> getLine :: IO [Int]
    print $ maximum [a + b, a - b, a * b]


module Main where

import Control.Applicative
import Control.Monad

main :: IO ()
main = do
    [a, b] <- fmap read . words <$> getLine :: IO [Int]
    print $ maximum [a + b, a - b, a * b]


import Data.List
import Data.Maybe

main :: IO ()
main = do
    _ <- getLine
    s <- getLine
    let le = scanl (\a c -> if c == 'E' then a+1 else a) 0 s
        rw = scanr (\c a -> if c == 'W' then a+1 else a) 0 s
        z = zipWith (+) le rw
        p = fromJust $ elemIndex (maximum z) z
        (pl,pr) = splitAt p s
        count f = length . filter f
    print $ count (=='W') pl + count (=='E') pr

Score : 300 points

Problem Statement

There are N people standing in a row from west to east.
Each person is facing east or west.
The directions of the people is given as a string S of length N.
The i-th person from the west is facing east if S_i = E, and west if S_i = W.

You will appoint one of the N people as the leader, then command the rest of them to face in the direction of the leader.
Here, we do not care which direction the leader is facing.

The people in the row hate to change their directions, so you would like to select the leader so that the number of people who have to change their directions is minimized.
Find the minimum number of people who have to change their directions.

Constraints

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

|S| = N

S_i is E or W.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of people who have to change their directions.

Sample Input 1

5
WEEWW

Sample Output 1

1

Assume that we appoint the third person from the west as the leader.
Then, the first person from the west needs to face east and has to turn around.
The other people do not need to change their directions, so the number of people who have to change their directions is 1 in this case.
It is not possible to have 0 people who have to change their directions, so the answer is 1.

Sample Input 2

12
WEWEWEEEWWWE

Sample Output 2

4

Sample Input 3

8
WWWWWEEE

Sample Output 3

3


import Control.Applicative
import Data.List

main = do
    [a,b,c,k] <- map read . words <$> getLine :: IO [Int]
    print $ if mod k 2 == 0 then a-b else b-a

Score : 300 points

Problem Statement

Takahashi, Nakahashi and Hikuhashi have integers A, B and C, respectively.
After repeating the following operation K times, find the integer Takahashi will get minus the integer Nakahashi will get:

Each of them simultaneously calculate the sum of the integers that the other two people have, then replace his own integer with the result.

However, if the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Constraints

1 \leq A,B,C \leq 10^9

0 \leq K \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C K

Output

Print the integer Takahashi will get minus the integer Nakahashi will get, after repeating the following operation K times.
If the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Sample Input 1

1 2 3 1

Sample Output 1

1

After one operation, Takahashi, Nakahashi and Hikuhashi have 5, 4 and 3, respectively. We should print 5-4=1.

Sample Input 2

2 3 2 0

Sample Output 2

-1

Sample Input 3

1000000000 1000000000 1000000000 1000000000000000000

Sample Output 3

0


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

Score : 100 points

Problem Statement

Three people, A, B and C, are trying to communicate using transceivers.
They are standing along a number line, and the coordinates of A, B and C are a, b and c (in meters), respectively.
Two people can directly communicate when the distance between them is at most d meters.
Determine if A and C can communicate, either directly or indirectly.
Here, A and C can indirectly communicate when A and B can directly communicate and also B and C can directly communicate.

Constraints

1 ≤ a,b,c ≤ 100

1 ≤ d ≤ 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

If A and C can communicate, print Yes; if they cannot, print No.

Sample Input 1

4 7 9 3

Sample Output 1

Yes

A and B can directly communicate, and also B and C can directly communicate, so we should print Yes.

Sample Input 2

100 10 1 2

Sample Output 2

No

They cannot communicate in this case.

Sample Input 3

10 10 10 1

Sample Output 3

Yes

There can be multiple people at the same position.

Sample Input 4

1 100 2 10

Sample Output 4

Yes