-- https://github.com/minoki/my-atcoder-solutions
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}
import Control.Monad
import Data.Char (isSpace)
import Data.Int (Int64)
import Data.List
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import qualified Data.ByteString.Char8 as BS
import Control.Monad.ST
import Data.Array.ST
import Control.Monad.Reader
--
import Data.Coerce
import qualified Data.Vector.Generic
import qualified Data.Vector.Generic.Mutable
import qualified Data.Array.Base
import qualified Unsafe.Coerce

type Memo s a = ReaderT (STUArray s (Int,Int) N) (ST s) a

runMemo :: Int -> Int -> (forall s. Memo s a) -> a
runMemo x n action = runST $ do
  arr <- newArray ((0,0),(x,n)) invalidN
  runReaderT action arr

solve :: Int -> Int -> [Int] -> N -> Memo s N
solve !x 0 [] !c = pure $ c * fromIntegral x
solve !x !n ss !c = do
  arr <- ask
  val <- lift $ readArray arr (x,n)
  if val == invalidN
    then do val <- doCalc x n ss
            lift $ writeArray arr (x,n) val
            return $ c * val
    else return $ c * val
  where
    doCalc !x !n ss = case spanN (> x) ss of
      (_,[]) -> pure $ factV U.! n * fromIntegral x
      (!m,ss1) -> do
        let !q = factV U.! n / factV U.! (n-m)
        s <- sumM [ solve (x `rem` t) (n-k-1) ts (factV U.! (n-m-1) / factV U.! (n-k-1))
                  | (k, t:ts) <- zip [m..] $ tails ss1
                    -- k + length ts + 1 == n
                    -- k : t より大きいやつ
                  ]
        return (q * s)
-- n == length ss

main = do
  [n,x] <- unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  -- n <= 200, x <= 10^5
  ss <- U.toList . mergeSortBy (\x y -> compare y x) . U.unfoldrN n (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  -- si <= 10^5
  print $ runMemo x n $ solve x n ss 1

factV :: U.Vector N
factV = U.scanl' (*) 1 (U.enumFromN 1 200)

sumM :: (Monad m, Num a) => [m a] -> m a
sumM = foldM (\s a -> (s +) <$> a) 0

-- spanN f xs == first length (span f xs)
spanN :: (a -> Bool) -> [a] -> (Int, [a])
spanN f = go 0
  where
    go !n [] = (n, [])
    go !n xs@(x:xss) = if f x
                       then go (n+1) xss
                       else (n, xs)

---

modulo :: Int64
modulo = 10^9+7
addMod, subMod, mulMod :: Int64 -> Int64 -> Int64
addMod !x !y | x + y >= modulo = x + y - modulo
             | otherwise = x + y
subMod !x !y | x >= y = x - y
             | otherwise = x - y + modulo
mulMod !x !y = (x * y) `rem` modulo

newtype N = N { unwrapN :: Int64 } deriving (Eq)
instance Show N where
  show (N x) = show x
instance Num N where
  (+) = coerce addMod
  (-) = coerce subMod
  (*) = coerce mulMod
  fromInteger n = N (fromInteger (n `mod` fromIntegral modulo))
  abs = undefined; signum = undefined

invalidN :: N
invalidN = N (-1)

{-# RULES
"^9/Int" forall x. x ^ (9 :: Int) = let u = x; v = u * u * u in v * v * v
"^9/Integer" forall x. x ^ (9 :: Integer) = let u = x; v = u * u * u in v * v * v
 #-}

---

exEuclid :: (Eq a, Integral a) => a -> a -> (a, a, a)
exEuclid !f !g = loop 1 0 0 1 f g
  where loop !u0 !u1 !v0 !v1 !f 0 = (f, u0, v0)
        loop !u0 !u1 !v0 !v1 !f g =
          case divMod f g of
            (q,r) -> loop u1 (u0 - q * u1) v1 (v0 - q * v1) g r

recipM :: Int64 -> Int64
recipM !x = case exEuclid x modulo of
             (1,a,_) -> a `mod` modulo
             (-1,a,_) -> (-a) `mod` modulo
divM :: Int64 -> Int64 -> Int64
divM !x !y = x `mulMod` recipM y

instance Fractional N where
  (/) = coerce divM
  recip = coerce recipM
  fromRational = undefined

---

mergeSortBy :: (U.Unbox a) => (a -> a -> Ordering) -> U.Vector a -> U.Vector a
mergeSortBy !cmp !vec = doSort vec
  where
    doSort vec | U.length vec <= 1 = vec
               | otherwise = let (xs, ys) = U.splitAt (U.length vec `quot` 2) vec
                             in merge (doSort xs) (doSort ys)
    merge xs ys = U.create $ do
      let !n = U.length xs
          !m = U.length ys
      result <- UM.new (n + m)
      let loop !i !j
            | i == n = U.copy (UM.drop (i + j) result) (U.drop j ys)
            | j == m = U.copy (UM.drop (i + j) result) (U.drop i xs)
            | otherwise = let !x = xs U.! i
                              !y = ys U.! j
                          in case cmp x y of
                               LT -> do UM.write result (i + j) x
                                        loop (i + 1) j
                               EQ -> do UM.write result (i + j) x
                                        UM.write result (i + j + 1) y
                                        loop (i + 1) (j + 1)
                               GT -> do UM.write result (i + j) y
                                        loop i (j + 1)
      loop 0 0
      return result

---

newtype instance UM.MVector s N = MV_N (UM.MVector s Int64)
newtype instance U.Vector N = V_N (U.Vector Int64)

instance Data.Vector.Generic.Mutable.MVector UM.MVector N where -- needs MultiParamTypeClasses here
  basicLength (MV_N mv) = Data.Vector.Generic.Mutable.basicLength mv
  basicUnsafeSlice i l (MV_N mv) = MV_N (Data.Vector.Generic.Mutable.basicUnsafeSlice i l mv)
  basicOverlaps (MV_N mv) (MV_N mv') = Data.Vector.Generic.Mutable.basicOverlaps mv mv'
  basicUnsafeNew l = MV_N <$> Data.Vector.Generic.Mutable.basicUnsafeNew l
  basicInitialize (MV_N mv) = Data.Vector.Generic.Mutable.basicInitialize mv
  basicUnsafeReplicate i x = MV_N <$> Data.Vector.Generic.Mutable.basicUnsafeReplicate i (coerce x)
  basicUnsafeRead (MV_N mv) i = coerce <$> Data.Vector.Generic.Mutable.basicUnsafeRead mv i
  basicUnsafeWrite (MV_N mv) i x = Data.Vector.Generic.Mutable.basicUnsafeWrite mv i (coerce x)
  basicClear (MV_N mv) = Data.Vector.Generic.Mutable.basicClear mv
  basicSet (MV_N mv) x = Data.Vector.Generic.Mutable.basicSet mv (coerce x)
  basicUnsafeCopy (MV_N mv) (MV_N mv') = Data.Vector.Generic.Mutable.basicUnsafeCopy mv mv'
  basicUnsafeMove (MV_N mv) (MV_N mv') = Data.Vector.Generic.Mutable.basicUnsafeMove mv mv'
  basicUnsafeGrow (MV_N mv) n = MV_N <$> Data.Vector.Generic.Mutable.basicUnsafeGrow mv n

instance Data.Vector.Generic.Vector U.Vector N where -- needs MultiParamTypeClasses here
  basicUnsafeFreeze (MV_N mv) = V_N <$> Data.Vector.Generic.basicUnsafeFreeze mv
  basicUnsafeThaw (V_N v) = MV_N <$> Data.Vector.Generic.basicUnsafeThaw v
  basicLength (V_N v) = Data.Vector.Generic.basicLength v
  basicUnsafeSlice i l (V_N v) = V_N (Data.Vector.Generic.basicUnsafeSlice i l v)
  basicUnsafeIndexM (V_N v) i = coerce <$> Data.Vector.Generic.basicUnsafeIndexM v i
  basicUnsafeCopy (MV_N mv) (V_N v) = Data.Vector.Generic.basicUnsafeCopy mv v
  elemseq (V_N v) x y = Data.Vector.Generic.elemseq v (coerce x) y

instance U.Unbox N

--- STUArray s i N

unsafeCoerce_STUArray_N_Int :: STUArray s i N -> STUArray s i Int64
unsafeCoerce_STUArray_N_Int = Unsafe.Coerce.unsafeCoerce
unsafeCoerce_STUArray_Int_N :: STUArray s i Int64 -> STUArray s i N
unsafeCoerce_STUArray_Int_N = Unsafe.Coerce.unsafeCoerce

instance Data.Array.Base.MArray (STUArray s) N (ST s) where
  getBounds arr = Data.Array.Base.getBounds (unsafeCoerce_STUArray_N_Int arr)
  getNumElements arr = Data.Array.Base.getNumElements (unsafeCoerce_STUArray_N_Int arr)
  newArray lu e = unsafeCoerce_STUArray_Int_N <$> Data.Array.Base.newArray lu (coerce e)
  newArray_ lu = unsafeCoerce_STUArray_Int_N <$> Data.Array.Base.newArray_ lu
  unsafeNewArray_ lu = unsafeCoerce_STUArray_Int_N <$> Data.Array.Base.unsafeNewArray_ lu
  unsafeRead arr i = coerce <$> Data.Array.Base.unsafeRead (unsafeCoerce_STUArray_N_Int arr) i
  unsafeWrite arr i e = Data.Array.Base.unsafeWrite (unsafeCoerce_STUArray_N_Int arr) i (coerce e)


{-# LANGUAGE BangPatterns       #-}
{-# LANGUAGE DataKinds          #-}
{-# LANGUAGE ExplicitNamespaces #-}
{-# LANGUAGE KindSignatures     #-}
{-# LANGUAGE TypeOperators      #-}
-- module ExaWizards2019.D (main) where

import           Control.Exception (assert)
import           Data.Bifunctor    (bimap)
import           Data.List         (foldl', sort)
import           Data.Map          (Map, (!))
import qualified Data.Map          as M (empty, foldlWithKey, insert)
import           Data.Ratio        (denominator, numerator)
import           Data.Vector       (Vector)
import qualified Data.Vector       as V (generate, (!))
import           GHC.TypeLits      (type (+), KnownNat, Nat, type (^), natVal)

main :: IO ()
main = do
  [n, x] <- map read . words <$> getLine
  ss <- map read . words <$> getLine
  assert (length ss == n) $
    print $ solve' n x ss

type M = Modular Int (10 ^ 9 + 7)

type Table = Map Int M

solve :: Int -> Int -> [Int] -> M
solve n x ss = fact n * foldl' f M.empty set ! x
  where
    set :: [(M, Int)]
    set = bimap fromIntegral id <$> zip [1..] (sort ss)

    f :: Table -> (M, Int) -> Table
    f table (i, s) =
      let
        p1 = 1 / i
        p2 = 1 - p1

        step table' k b =
          let
            n1 = table ! (k `mod` s)
            n2 = b
          in
            M.insert k (p1 * n1 + p2 * n2) table'
      in
        M.foldlWithKey step M.empty table

solve' :: Int -> Int -> [Int] -> M
solve' n x ss = fact n * (foldl step table0 set V.! x)
  where
    set :: [(Int, Int)]
    set = zip [1..n] $ sort ss

    table0 :: Vector M
    table0 = V.generate (x + 1) fromIntegral

    step :: Vector M -> (Int, Int) -> Vector M
    step !table (i, y) =
      let
        !p1 = recip $ fromIntegral i
        !p2 = 1 - p1
      in
        V.generate (x + 1) $ \x' ->
            let
              n1 = table V.! (x' `mod` y)
              n2 = table V.! x'
            in
              p1 * n1 + p2 * n2

fact :: Int -> M
fact n = product $ map fromIntegral [1 .. n]

-- modular

newtype Modular a (modulus :: Nat) =
  Modular { unModular :: a }
  deriving (Eq)

instance Show a => Show (Modular a modulus) where
  show (Modular n) = show n

instance (Integral a, KnownNat modulus) => Num (Modular a modulus) where
  fromInteger           = toModular . fromInteger
  Modular n + Modular m = toModular $ n + m
  Modular n * Modular m = toModular $ n * m
  negate (Modular n)    = toModular $ negate n
  abs (Modular n)       = toModular $ abs n
  signum (Modular n)    = toModular $ signum n

instance (Integral a, KnownNat modulus) => Fractional (Modular a modulus) where
  recip m@(Modular n) = toModular $ modularReciprocal (fromInteger (natVal m)) n
  fromRational r = fromInteger (numerator r) / fromInteger (denominator r)

toModular :: (Integral a, KnownNat modulus) => a -> Modular a modulus
toModular n = let m = Modular $ n `mod` fromInteger (natVal m) in m

modularReciprocal :: Integral a => a -> a -> a
modularReciprocal modulus n = snd $ modularReciprocal' modulus n
  where
    -- modularReciprocal' n m = (x, y)
    -- n * x + m * y = 1
    modularReciprocal' _ 0 = notCoprimeError
    modularReciprocal' _ 1 = (0, 1)
    modularReciprocal' m l = (y, x - q * y)
      where
        (q, r) = m `divMod` l
        (x, y) = modularReciprocal' l r
    notCoprimeError =
      error $ unwords
        [ "divider"
        , parentheses $ showIntegral n
        , "must be coprime to modulus"
        , parentheses $ showIntegral modulus
        ]
    parentheses s = "(" ++ s ++ ")"
    showIntegral = show . toInteger

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

Score : 600 points

Problem Statement

Snuke has a blackboard and a set S consisting of N integers.
The i-th element in S is S_i.

He wrote an integer X on the blackboard, then performed the following operation N times:

Choose one element from S and remove it.

Let x be the number written on the blackboard now, and y be the integer removed from S. Replace the number on the blackboard with x \bmod {y}.

There are N! possible orders in which the elements are removed from S.
For each of them, find the number that would be written on the blackboard after the N operations, and compute the sum of all those N! numbers modulo 10^{9}+7.

Constraints

All values in input are integers.

1 \leq N \leq 200

1 \leq S_i, X \leq 10^{5}

S_i are pairwise distinct.

Input

Input is given from Standard Input in the following format:

N X
S_1 S_2 \ldots S_{N}

Output

Print the answer.

Sample Input 1

2 19
3 7

Sample Output 1

3

There are two possible orders in which we remove the numbers from S.

If we remove 3 and 7 in this order, the number on the blackboard changes as follows: 19 \rightarrow 1 \rightarrow 1.

If we remove 7 and 3 in this order, the number on the blackboard changes as follows: 19 \rightarrow 5 \rightarrow 2.

The output should be the sum of these: 3.

Sample Input 2

5 82
22 11 6 5 13

Sample Output 2

288

Sample Input 3

10 100000
50000 50001 50002 50003 50004 50005 50006 50007 50008 50009

Sample Output 3

279669259

Be sure to compute the sum modulo 10^{9}+7.

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.Arrow
import Control.Monad
import Data.List
import qualified Data.ByteString.Char8 as B
import qualified Data.Vector as V
import Control.Monad.State (State, evalState, runState, put, gets, modify)
import Data.Map.Strict (Map, lookup, insert, empty)
import Data.Foldable

main :: IO ()
main = readContents 2 >>= print . solve

solve :: [[Int]] -> Int
solve [[n, x0], ss] = mul (ps V.! n) $ evalMemo calc (x0, 0)
    where
        vs = V.fromList $ sort ss
        ps = V.fromList $ scanl mul 1 [1..n]

        calc f (x, i)
            | i < n = (mul (inv $ n - i)) <$> (add <$> lowers <*> highers)
            | otherwise = return x
            where
                lowers = adds <$> mapM f [(x `mod` (vs V.! idx), i + 1) | idx <- [0..(m - 1)]]
                highers = (mul (n - m - i)) <$> f (x, i + 1)

                m = edit $ binarySearch x vs

        adds = foldl' add 0

        edit (Right i) = i + 1
        edit (Left i ) = i

readLine :: IO [Int]
readLine = unfoldr (fmap (second (maybe B.empty snd . B.uncons)) . B.readInt) <$> B.getLine

readContents :: Int -> IO [[Int]]
readContents = flip replicateM readLine

infixl 6 `add`
infixl 7 `mul`

add :: Int -> Int -> Int
add x y = val $ x + y

mul :: Int -> Int -> Int
mul x y = val $ x * y

inv :: Int -> Int
inv x = pow x $ modVal - 2

pow :: Int -> Int -> Int
pow b e
    | e == 0 = 1
    | odd e = mul b . pow b $ e - 1
    | otherwise = mul v v
    where
        v = pow b $ e `div` 2

val :: Int -> Int
val = (`mod` modVal)

modVal :: Int
modVal = 10 ^ 9 + 7

primes :: [Int]
primes = build [2..]
    where
        build (x : xs) = x : build (filter (\n -> n `mod` x /= 0) xs)

isPrime :: Int -> Bool
isPrime n = check primes
    where
        check (x : xs)
            | x == n = True
            | x > n = False
            | otherwise = check xs

binarySearch :: (Ord a) => a -> V.Vector a -> Either Int Int
binarySearch k xs
    | V.null xs = Left 0
    | otherwise = bsf 0 $ V.length xs
    where
        bsf base size
            | size > 1 && mv > k = bsf base $ size - half
            | size > 1 = bsf mid $ size - half
            | bv == k = Right base
            | bv < k = Left $ base + 1
            | otherwise = Left base
            where
                half = size `div` 2
                mid = base + half
                bv = xs V.! base
                mv = xs V.! mid

type Memoizer a b = a -> State (Map a b) b

evalMemo :: (Ord a) => (Memoizer a b -> Memoizer a b) -> a -> b
evalMemo f = flip evalState empty . memoizeFix f

runMemo :: (Ord a) => (Memoizer a b -> Memoizer a b) -> a -> (b, Map a b)
runMemo f = flip runState empty . memoizeFix f

memoizeFix :: (Ord a) => (Memoizer a b -> Memoizer a b) -> Memoizer a b
memoizeFix f x = gets (Data.Map.Strict.lookup x) >>= maybe (f (memoizeFix f) x >>= ((<$) <*> (modify . Data.Map.Strict.insert x))) return


import Control.Arrow
import Control.Monad
import Data.List
import qualified Data.ByteString.Char8 as B
import qualified Data.Vector as V
import Control.Monad.State (State, evalState, runState, put, gets, modify)
import Data.Map.Strict (Map, lookup, insert, empty)
import Data.Foldable

main :: IO ()
main = readContents 2 >>= print . solve

solve :: [[Int]] -> Int
solve [[n, x0], ss] = evalMemo calc (x0, 0)
    where
        vs = V.fromList $ sort ss
        ps = V.fromList $ scanl mul 1 [1..n]

        calc _ (0, _) = return 0
        calc f (x, i)
            | x < vs V.! 0 = return $ (ps V.! (n - i)) `mul` x
            | otherwise = add <$> lowers <*> highers
            where
                m = edit $ binarySearch x vs
                lowers = adds f [(x `mod` (vs V.! iy), i + 1) | iy <- [0..(m - 1)]]
                highers
                    | n - i - m > 0 = (mul (n - i - m)) <$> f (x, i + 1)
                    | otherwise = return 0

        adds f xs = mapM f xs >>= foldlM (\acc x -> return $ acc `add` x) 0

        edit (Right i) = i + 1
        edit (Left i ) = i

readLine :: IO [Int]
readLine = unfoldr (fmap (second (maybe B.empty snd . B.uncons)) . B.readInt) <$> B.getLine

readContents :: Int -> IO [[Int]]
readContents = flip replicateM readLine

infixl 6 `add`
infixl 7 `mul`

add :: Int -> Int -> Int
add x y = val $ x + y

mul :: Int -> Int -> Int
mul x y = val $ x * y

inv :: Int -> Int
inv x = pow x $ modVal - 2

pow :: Int -> Int -> Int
pow b e
    | e == 0 = 1
    | odd e = mul b . pow b $ e - 1
    | otherwise = mul v v
    where
        v = pow b $ e `div` 2

val :: Int -> Int
val = (`mod` modVal)

modVal :: Int
modVal = 10 ^ 9 + 7

primes :: [Int]
primes = build [2..]
    where
        build (x : xs) = x : build (filter (\n -> n `mod` x /= 0) xs)

isPrime :: Int -> Bool
isPrime n = check primes
    where
        check (x : xs)
            | x == n = True
            | x > n = False
            | otherwise = check xs

binarySearch :: (Ord a) => a -> V.Vector a -> Either Int Int
binarySearch k xs
    | V.null xs = Left 0
    | otherwise = bsf 0 $ V.length xs
    where
        bsf base size
            | size > 1 && mv > k = bsf base $ size - half
            | size > 1 = bsf mid $ size - half
            | bv == k = Right base
            | bv < k = Left $ base + 1
            | otherwise = Left base
            where
                half = size `div` 2
                mid = base + half
                bv = xs V.! base
                mv = xs V.! mid

type Memoizer a b = a -> State (Map a b) b

evalMemo :: (Ord a) => (Memoizer a b -> Memoizer a b) -> a -> b
evalMemo f = flip evalState empty . memoizeFix f

runMemo :: (Ord a) => (Memoizer a b -> Memoizer a b) -> a -> (b, Map a b)
runMemo f = flip runState empty . memoizeFix f

memoizeFix :: (Ord a) => (Memoizer a b -> Memoizer a b) -> Memoizer a b
memoizeFix f x = gets (Data.Map.Strict.lookup x) >>= maybe (f (memoizeFix f) x >>= ((<$) <*> (modify . Data.Map.Strict.insert x))) return


main = do
    c <- getLine :: IO String
    putStrLn (case c of
        "A" -> "A"
        "C" -> "T"
        "G" -> "C"
        "T" -> "G")

Score : 100 points

Problem Statement

On the Planet AtCoder, there are four types of bases: A, C, G and T. A bonds with T, and C bonds with G.

You are given a letter b as input, which is A, C, G or T. Write a program that prints the letter representing the base that bonds with the base b.

Constraints

b is one of the letters A, C, G and T.

Input

Input is given from Standard Input in the following format:

b

Output

Print the letter representing the base that bonds with the base b.

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C


checkATCG::String->String
checkATCG x = case x of
    "A" -> "T"
    "T" -> "A"
    "C" -> "G"
    "G" -> "C"

main::IO ()
main = do
    b <- getLine
    putStrLn $ checkATCG b


import Data.Tuple (swap)

main :: IO ()
main = do
  b <- getLine
  putStrLn . snd . head . filter ((== b) . fst) $ pairs

pairs = xs ++ map swap xs
  where
    xs = [("A", "T"), ("C", "G")]


main = do
  v:_ <- getLine
  putChar $ case v of
    'A' -> 'T'
    'T' -> 'A'
    'C' -> 'G'
    'G' -> 'C'


main = do
  x <- readLn
  putStrLn $ case x of
    ["A"] -> "T"
    ["T"] -> "A"
    ["C"] -> "G"
    ["G"] -> "C"


import Control.Monad

main = do
    s <- getLine
    putStrLn $ show $ solve s

solve :: String -> Int
solve "" = 0
solve s  = max (length $ takeWhile ok s) (solve $ tail s)
  where
    ok c = elem c "ACGT"

Score : 200 points

Problem Statement

You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

S is a string of length between 1 and 10 (inclusive).

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest ACGT string that is a substring of S.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is (the empty string).


main = do
  s <- getLine :: IO String
  print $ maximum $ f s 0

f :: String -> Int -> [Int]
f [] _ = [0]
f [x] i = if x `elem` "ACGT" then [i+1] else [0]
f (x:xs) i
  | x `elem` "ACGT" = f xs (i+1)
  | otherwise = i : f xs 0


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

f :: String -> Int
f = fst. foldr step (0, (0, []))
  where
    step x (m, (l, xs)) = if x `elem` "ACGT" then let l' = succ l in (max l' m, (l', x : xs)) else (m, (0, []))


main=getLine>>=print.maximum.f 0
f p(a:s)=if(sum[1|c<-"ATGC",a==c])>0 then f(p+1)s else p:(f 0 s)
f p[]=[p]


import Data.List
main = do
  s <- getLine
  let a = [drop y (take x s) | x <- [0..(length s)], y <- [0..(length s)], x+y <= length s, x>=y]
  print $ maximum $ map f a
f xs
  | all (\x -> elem x ['A','C','G','T']) xs = length xs
  | otherwise = 0


import Data.List
isIn::(Eq a) => [a] -> [a] -> Bool
n `isIn` m = any (n `isPrefixOf`) (tails m)
main=do
 s<-getLine
 print$maximum(map length ["t"|("t" `isIn` "s") == True])


import Control.Monad (replicateM)
import qualified Data.Map.Strict as M

main :: IO ()
main = do
  [n,q] <- map (read :: String -> Int) . words <$> getLine
  s <- getLine
  lrs <- map (map (read :: String -> Int)) . map words <$> getNLine_ q
  mapM_ print $ map (ans s) lrs

ans :: String -> [Int] -> Int
ans s [l,r] = (ms M.! r) - (ms M.! l)
  where ms = myIndex s

myIndex :: String -> M.Map Int Int
myIndex s = M.fromList . (\(b,z,k,a) -> a) $
  foldl (\(b,z,k,acc) c -> if c == 'A'
    then (b+1, True, k, (b+1,k):acc)
    else if c == 'C' && z
         then (b+1, False, k+1, (b+1,k+1):acc)
         else (b+1, False, k, (b+1,k):acc)) (0, False, 0, []) s

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

Score : 300 points

Problem Statement

You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:

Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.

Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.

Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.


Score : 400 points

Problem Statement

You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:

The string does not contain characters other than A, C, G and T.

The string does not contain AGC as a substring.

The condition above cannot be violated by swapping two adjacent characters once.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.

Sample Input 1

3

Sample Output 1

61

There are 4^3 = 64 strings of length 3 that do not contain characters other than A, C, G and T. Among them, only AGC, ACG and GAC violate the condition, so the answer is 64 - 3 = 61.

Sample Input 2

4

Sample Output 2

230

Sample Input 3

100

Sample Output 3

388130742

Be sure to print the number of strings modulo 10^9+7.


import Data.Map ((!))
import qualified Data.Map as M
import Control.Monad

main = readLn >>= print.solve

solve :: Int -> Int
solve = M.foldr (+%) 0.(ans!!)
  where
  ans = M.empty : M.empty : M.empty
        : M.fromList (zip (correctStrs 3) (repeat 1))
        : map f (drop 3 ans)
  f pMap = foldr g M.empty (correctStrs 4)
    where g head4 = M.insertWith (+%) (init head4) (pMap!tail head4)
  correctStrs n = filter correct $ replicateM n "ACGT"
  correct ('A':'G':'C': _ ) = False
  correct [ _ ,'A','G','C'] = False
  correct ('A':'C':'G': _ ) = False
  correct [ _ ,'A','C','G'] = False
  correct ('G':'A':'C': _ ) = False
  correct [ _ ,'G','A','C'] = False
  correct ['A', _ ,'G','C'] = False
  correct ['A','G', _ ,'C'] = False
  correct _ = True

infixl 6 +%
a +% b = (a+b)`mod`1000000007


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

readInt = fromIntegral . fst . fromJust . BS.readInteger

readString = map BS.unpack . BS.words

getInt = readInt <$> BS.getLine

getString = readString <$> BS.getLine

productP :: [Int] -> Int -> Int
productP [] p = p
productP (x : xs) p = productP xs ((x + 1) * p `mod` (10 ^ 9 + 7))

sum' :: [Int] -> Int -> Int
sum' [] s = s
sum' (x : xs) s = sum' xs ((x + s) `mod` (10 ^ 9 + 7))

main = do
  n <- getInt
  [s] <- getString
  let s' = map length (group (sort s))
  print $ sum' [(productP s' 1), (-1)] 0

Score : 200 points

Problem Statement

You are given a string S of length N.
Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings.

Here, a subsequence of a string is a concatenation of one or more characters from the string without changing the order.

Constraints

1 \leq N \leq 100000

S consists of lowercase English letters.

|S|=N

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of the subsequences such that all characters are different, modulo 10^9+7.

Sample Input 1

4
abcd

Sample Output 1

15

Since all characters in S itself are different, all its subsequences satisfy the condition.

Sample Input 2

3
baa

Sample Output 2

5

The answer is five: b, two occurrences of a, two occurrences of ba. Note that we do not count baa, since it contains two as.

Sample Input 3

5
abcab

Sample Output 3

17


import Data.List
main = getLine >> getLine >>= putStrLn . show . flip mod (10^9 + 7) . (+ (-1)) . foldl1 (*) . map ((+) 1 . length) . group . sort


{-# LANGUAGE BangPatterns      #-} --引数に!
{-# LANGUAGE MultiWayIf        #-}
{-# LANGUAGE TupleSections     #-}

import Data.List

main :: IO ()
main = do
  _ <- getLine
  s <- getLine
  putStrLn $ show $ (foldl1' (\x y -> (mod0 $ x*y)) $ map (mod0.(+1).length) $ group $ sort s)-1

mod0 :: Int -> Int
mod0 n = if n < 1000000007 then n else mod n 1000000007


{-# LANGUAGE
  ScopedTypeVariables, BangPatterns, TupleSections, ExplicitForAll,
  LambdaCase, MultiWayIf, Unsafe, RecordWildCards, FlexibleContexts, CPP,
  NoMonomorphismRestriction, GADTs,
  RankNTypes, EmptyDataDecls, EmptyCase, ViewPatterns #-}

import Data.Bits
import Data.List
import Data.Maybe
import Data.Tuple
import Data.Ord
import Data.Int
import Data.Word
import Data.Char
import Data.Function
import Data.STRef
import Data.IORef
import System.IO
import Control.Applicative
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.State.Strict
import Control.Monad.ST
-- import Control.Monad.ST.Safe
import Control.DeepSeq
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as IMS
import qualified Data.IntMap.Lazy as IML
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.Vector.Primitive as VP
import qualified Data.Vector.Primitive.Mutable as VPM
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import GHC.Exts (build)

-- import Control.Monad.ST.Unsafe

main :: IO ()
main = do
  [n,a,b] <- map readInt . words <$> getLine
  maybe (putStrLn "NO")
    (\xs -> do
        putStrLn "YES"
        putStrLn $ unwords $ map show xs)
    $ findSeq n a b

-- PREREQUISTE: 0 <= from,to < 2^n
findSeq :: Int -> Int -> Int -> Maybe [Int]
{-# INLINE findSeq #-}
findSeq !n !a !b
  | even $ popCount $ xor a b, n > 0 = Nothing
  | otherwise  = Just $ build
                 $ \cns nil -> builder cns a b (xor a b) (bit n - 1) nil
  where
    builder :: (Int -> b -> b) -> Int -> Int -> Int -> Int -> b -> b
    {-# INLINE builder #-}
    builder c = go
      where
        go !from !to !xorft !bitMask
          | bitMask == 0 = c from
          | otherwise    = go from mid0 newMask_least newMask
                           . go mid1 to (xor mid1 to) newMask
          where
            !xorft_least = xorft .&. (-xorft)
            !newMask = bitMask .&. complement xorft_least
            !newMask_least = newMask .&. (-newMask)
            !mid0 = from `xor` newMask_least
            !mid1 = mid0 `xor` xorft_least

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

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

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

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

Score : 800 points

Problem Statement

You are given integers N,\ A and B.
Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.

P_0=A

P_{2^N-1}=B

For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.

Constraints

1 \leq N \leq 17

0 \leq A \leq 2^N-1

0 \leq B \leq 2^N-1

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

If there is no permutation that satisfies the conditions, print NO.

If there is such a permutation, print YES in the first line.
Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between.
If there are multiple solutions, any of them is accepted.

Sample Input 1

2 1 3

Sample Output 1

YES
1 0 2 3

The binary representation of P=(1,0,2,3) is (01,00,10,11), where any two adjacent elements differ by exactly one bit.

Sample Input 2

3 2 1

Sample Output 2

NO


main = do
    fst <- getLine
    snd <- getLine
    let h = head $ intList fst
    let w = head $ reverse $ intList fst
    let a = head $ intList snd
    let b = head $ reverse $ intList snd
    let y = show $ ans h w a b
    putStrLn y

intList :: [Char] -> [Int]
intList [] = []
intList (x:xs)
    | x == ' ' = intList xs
    | otherwise = [read [x] :: Int] ++ intList xs

ans :: Int -> Int -> Int -> Int -> Int
ans h w a b = (h - a) * (w - b)

Score : 100 points

Problem Statement

There are H rows and W columns of white square cells.

You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns.

How many white cells will remain?

It can be proved that this count does not depend on what rows and columns are chosen.

Constraints

All values in input are integers.

1 \leq H, W \leq 20

1 \leq h \leq H

1 \leq w \leq W

Input

Input is given from Standard Input in the following format:

H W
h w

Output

Print the number of white cells that will remain.

Sample Input 1

3 2
2 1

Sample Output 1

1

There are 3 rows and 2 columns of cells. When two rows and one column are chosen and painted in black, there is always one white cell that remains.

Sample Input 2

5 5
2 3

Sample Output 2

6

Sample Input 3

2 4
2 4

Sample Output 3

0


main = do
    fst <- getLine
    snd <- getLine
    let h = head $ intList fst
    let w = head $ reverse $ intList fst
    let a = head $ intList snd
    let b = head $ reverse $ intList snd
    let y = ans h w a b
    print y

intList :: [Char] -> [Int]
intList [] = []
intList (x:xs)
    | x == ' ' = intList xs
    | otherwise = [read [x] :: Int] ++ intList xs

ans :: Int -> Int -> Int -> Int -> Int
ans h w a b = h * w - a * w - b * h + a * b


main = do
  [h0,w0] <- map read . words <$> getLine
  [h1,w1] <- map read . words <$> getLine
  print ((h0 - h1) * (w0 - w1) :: Int)


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

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

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


main = do
  (_:sM:sC:_) <- words <$> getLine
  let m = (read sM) :: Int
  let c = (read sC) :: Integer
  let cs = take m $ repeat c
  bs <- map (read :: String-> Integer) <$> words <$> getLine
  aMat <- map (map read :: [String]-> [Integer]) <$> map words <$> lines <$> getContents
  let matMuled = map (\ aLine -> zipWith (*) aLine bs) aMat
  let aSum = foldl (\ aSumTmp aLine -> zipWith (+) aSumTmp aLine) cs matMuled
  putStrLn $ show  $ length $ filter (\a -> a > 0) aSum

Score : 200 points

Problem Statement

There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}.

Additionally, you are given integers B_1, B_2, ..., B_M and C.

The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0.

Among the N codes, find the number of codes that correctly solve this problem.

Constraints

All values in input are integers.

1 \leq N, M \leq 20

-100 \leq A_{ij} \leq 100

-100 \leq B_i \leq 100

-100 \leq C \leq 100

Input

Input is given from Standard Input in the following format:

N M C
B_1 B_2 ... B_M
A_{11} A_{12} ... A_{1M}
A_{21} A_{22} ... A_{2M}
\vdots
A_{N1} A_{N2} ... A_{NM}

Output

Print the number of codes among the given N codes that correctly solve this problem.

Sample Input 1

2 3 -10
1 2 3
3 2 1
1 2 2

Sample Output 1

1

Only the second code correctly solves this problem, as follows:

Since 3 \times 1 + 2 \times 2 + 1 \times 3 + (-10) = 0 \leq 0, the first code does not solve this problem.

1 \times 1 + 2 \times 2 + 2 \times 3 + (-10) = 1 > 0, the second code solves this problem.

Sample Input 2

5 2 -4
-2 5
100 41
100 40
-3 0
-6 -2
18 -13

Sample Output 2

2

Sample Input 3

3 3 0
100 -100 0
0 100 100
100 100 100
-100 100 100

Sample Output 3

0

All of them are Wrong Answer. Except yours.


import           Control.Monad
import           Data.List

main :: IO ()
main = do
    [n, m] <- fmap (map read . words) getLine :: IO [Int]
    cs     <- replicateM n $ fmap (map read . words) getLine :: IO [[Int]]
    print . solve m $ cs

solve :: Int -> [[Int]] -> Int
solve m cs = purchase m scs
    where scs = sortOn fst . map (\[a, b] -> (a, b)) $ cs

purchase :: Int -> [(Int, Int)] -> Int
purchase m ((a, b) : cs) =
    if m <= b then m * a else a * b + purchase (m - b) cs
purchase _ [] = 0

Score : 300 points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.

There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy M cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the minimum amount of money with which Takahashi can buy M cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

The output may not fit into a 32-bit integer type.


{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}

import qualified Data.ByteString.Char8 as B
import Data.Attoparsec.ByteString.Char8
import Data.List (sort)

type Input  = (Int, Int, [(Int, Int)])
type Output = Int

input :: Parser Input
input = do
  (_N, _M) <- decimalPair
  _ABs <- count _N decimalPair
  return (_N, _M, _ABs)

decimalPair :: Parser (Int, Int)
decimalPair = (,)
  <$> decimal <* char ' '
  <*> decimal <* endOfLine

main :: IO ()
main = B.interact
  $ B.pack . show . either (error "parse err") solve . parseOnly input

solve :: Input -> Output
solve (_N, _M, _ABs) = go 0 _M $ sort _ABs
  where
    go !n !m ((a, b) : abs)
      | m <= b    = n + a * m
      | otherwise = go (n + a * b) (m - b) abs


import Data.List (sort)

main :: IO ()
main = do
  [n, m] <- map read . words <$> getLine :: IO [Integer]
  abs <- sequence . replicate (fromInteger n) $ unsafeListToTuple . map read . words <$> getLine :: IO [(Integer, Integer)]
  let
    abs' = sort abs
    a = fst . foldl step (0, 0) $ abs'
    step (s, t) (u, v) = if t + v < m then (s + u * v, t + v) else let v' = m - t in (s + u * v', m)
  print a

unsafeListToTuple :: [a] -> (a, a)
unsafeListToTuple (x : y : _) = (x, y)
unsafeListToTuple _ = undefined


lst a b k = [x | x <- [1..min a b], mod a x == 0 && mod b x == 0]

main =
    getLine >>= putStrLn.show.(\[a, b, k] -> (reverse(lst a b k)) !! (k - 1)).map read.words

Score : 200 points

Problem Statement

You are given positive integers A and B.

Find the K-th largest positive integer that divides both A and B.

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

The K-th largest positive integer that divides both A and B exists.

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the K-th largest positive integer that divides both A and B.

Sample Input 1

8 12 2

Sample Output 1

2

Three positive integers divides both 8 and 12: 1, 2 and 4.
Among them, the second largest is 2.

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


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

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

solve :: [Int] -> Int
solve [a, b, k] = head . drop (k - 1) $ sortBy (flip compare) [i | i <- [1..x], x `mod` i == 0, y `mod` i == 0]
    where
        [x, y] = sort [a, b]

readLine :: IO [Int]
readLine = unfoldr (fmap (second (maybe B.empty snd . B.uncons)) . B.readInt) <$> B.getLine

readContents :: Int -> IO [[Int]]
readContents = flip replicateM readLine


main = do
  [a,b,k] <- map read . words <$> getLine
  print $ head $ drop (k-1) $ reverse $ filter (\x -> b `mod` x == 0) (filter (\x -> a `mod` x == 0) [1..(min a b)])


main = do
  [a,b,k] <- map read . words <$> getLine
  print $ [c|c<-[1..], mod a c==0 && mod b c==0] !! (k-1)


Score : 300 points

Problem Statement

There are N cubes stacked vertically on a desk.

You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is 0, and blue if that character is 1.

You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent, and remove them. Here, the cubes that were stacked on the removed cubes will fall down onto the object below them.

At most how many cubes can be removed?

Constraints

1 \leq N \leq 10^5

|S| = N

Each character in S is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of cubes that can be removed.

Sample Input 1

0011

Sample Output 1

4

All four cubes can be removed, by performing the operation as follows:

Remove the second and third cubes from the bottom. Then, the fourth cube drops onto the first cube.

Remove the first and second cubes from the bottom.

Sample Input 2

11011010001011

Sample Output 2

12

Sample Input 3

0

Sample Output 3

0


f b l=if null l then 0 else
      if(head l)==(last b)then f(b++[head l])(tail l)else
      2+if null ((tail l)++(init b)) then 0 else f[head b](tail ((init b)++(tail l)))
main=do
 l<-getLine
 print$f [head l](tail l)


import Data.List

solver::String->Int
solver = eater.(map (\ (i,b) -> if (mod i 2 == 0) then b else (not b)  ) ).(zip [0..]).(map (\ c -> (c == '0') ))

eater::[Bool]->Int
eater bs = let grpd = group bs in
           let ev = (sum.(map length).filter (\ ls -> mod (length ls) 2 == 0)) grpd in
           let od = (sum.(map (\ ls -> 2*(div (length ls) 2))).group.concat.(filter (\ ls -> mod (length ls) 2 /= 0))) grpd in
           ev+od
main::IO()
main=print.solver=<<getLine


{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE RankNTypes #-}
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Maybe
import Data.List
import qualified Data.IntMap.Strict as IM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import Control.Monad
import Control.Monad.ST
import Debug.Trace
-- trace _ = id

solve :: Int -> Int -> [(Int,Int)] -> [Int]
solve bN bM lstAB = map (\x -> (combi2 bN) - x) conn
  where
  conn = reverse $ VU.toList $ VU.prescanl' (+) 0 vDiff

  vDiff :: VU.Vector Int
  vDiff = traceL "vDiff" vDiff0 vDiff0
  vDiff0 = VU.create $ do
    uf <- uftInit (bN+1)
    ccSize <- VUM.replicate (bN+1) 1
    diff <- VUM.new bM
    forM_ (zip [0..bM-1] (reverse lstAB)) $ \(i, (a,b)) -> do
      a' <- uftFind uf a
      b' <- uftFind uf b
      if a' == b' then VUM.write diff i 0 else do
        nA <- VUM.read ccSize a'
        nB <- VUM.read ccSize b'
        let nSum = nA + nB
        let thisDiff = (combi2 nSum) - (combi2 nA) - (combi2 nB)
        VUM.write diff i thisDiff
        uftUnion uf a' b'
        VUM.write ccSize b' nSum
    return diff

combi2 n = (n * (n-1)) `div` 2

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

{-
   Union-Find Tree
      Note: only flattern part is implemented.
            length comparison part has not yet been implemented.
-}

-- Initialization
uftInit :: Int -> ST s (VUM.MVector s Int)
uftInit size = do
  vec <- VUM.new size
  forM_ [0..size-1] $ \i -> VUM.write vec i i
  return vec

-- Union, or merge
uftUnion :: VUM.MVector s Int -> Int -> Int -> ST s ()
uftUnion vec x y = do
  rx <- uftFind vec x
  ry <- uftFind vec y
  if rx == ry then return ()
              else VUM.write vec rx ry

-- Returns the root
uftFind :: VUM.MVector s Int -> Int -> ST s Int
uftFind vec x = do
  y <- VUM.read vec x
  if x == y then return x
            else uftFind vec y >>= vum_write_ret vec x

-- Tests if in the same group
uftSameGrp :: VUM.MVector s Int -> Int -> Int -> ST s Bool
uftSameGrp vec x y = (==) <$> uftFind vec x <*> uftFind vec y

vum_write_ret :: VUM.Unbox a => VUM.MVector s a -> Int -> a -> ST s a
vum_write_ret vec i a = VUM.write vec i a >> return a

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

tmain :: B.ByteString -> [Int]
tmain cont =
  let remLines0 = map B.words (B.lines cont)
      [bs_bN,bs_bM]:remLines1 = remLines0
      bN = readBInt bs_bN
      bM = readBInt bs_bM
      lstAB = map (\[x1,x2] -> (readBInt x1,readBInt x2)) remLines1
  in solve bN bM lstAB

outAnswer :: [Int] -> IO ()
outAnswer ns = putStr (unlines (map show ns))

main :: IO ()
main = outAnswer . tmain =<< B.getContents

traceL :: Show a => String -> a -> b -> b
traceL label showObj val = trace (label ++ " " ++ show showObj) val

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

inp1 = "4 5\n1 2\n3 4\n1 3\n2 3\n1 4\n"
inp2 = "6 5\n2 3\n1 2\n5 6\n3 4\n4 5\n"
inp3 = "2 1\n1 2\n"
tv1 = tmain $ B.pack inp1
tv2 = tmain $ B.pack inp2
tv3 = tmain $ B.pack inp3
test1 = tv1 == [0,0,4,5,6]
test2 = tv2 == [8,9,12,14,15]
test3 = tv3 == [1]
alltest = test1 && test2 && test3

Score : 400 points

Problem Statement

There are N islands and M bridges.

The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.

Initially, we can travel between any two islands using some of these bridges.

However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.

Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.

For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

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.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 1

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

Sample Output 1

0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

Sample Input 2

6 5
2 3
1 2
5 6
3 4
4 5

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1


main = do
  s <- getLine
  putStrLn $ if s <= "2019/04/30" then "Heisei" else "TBD"

Score : 100 points

Problem Statement

You are given a string S as input. This represents a valid date in the year 2019 in the yyyy/mm/dd format. (For example, April 30, 2019 is represented as 2019/04/30.)

Write a program that prints Heisei if the date represented by S is not later than April 30, 2019, and prints TBD otherwise.

Constraints

S is a string that represents a valid date in the year 2019 in the yyyy/mm/dd format.

Input

Input is given from Standard Input in the following format:

S

Output

Print Heisei if the date represented by S is not later than April 30, 2019, and print TBD otherwise.

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD


import Control.Monad

main = do
    n <- readLn
    ss <- map (toTuple . words) <$> replicateM n getLine
    print $ sum $ map toJPY ss

toTuple :: [String] -> (Double, String)
toTuple (n:t:xs) = (read n, t)

toJPY :: (Double, String) -> Double
toJPY (n, t)
    | t == "BTC" = n * 380000.0
    | t == "JPY" = n

Score : 200 points

Problem Statement

Takahashi received otoshidama (New Year's money gifts) from N of his relatives.

You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either JPY or BTC, and x_i and u_i represent the content of the otoshidama from the i-th relative.

For example, if x_1 = 10000 and u_1 = JPY, the otoshidama from the first relative is 10000 Japanese yen; if x_2 = 0.10000000 and u_2 = BTC, the otoshidama from the second relative is 0.1 bitcoins.

If we convert the bitcoins into yen at the rate of 380000.0 JPY per 1.0 BTC, how much are the gifts worth in total?

Constraints

2 \leq N \leq 10

u_i = JPY or BTC.

If u_i = JPY, x_i is an integer such that 1 \leq x_i \leq 10^8.

If u_i = BTC, x_i is a decimal with 8 decimal digits, such that 0.00000001 \leq x_i \leq 100.00000000.

Input

Input is given from Standard Input in the following format:

N
x_1 u_1
x_2 u_2
:
x_N u_N

Output

If the gifts are worth Y yen in total, print the value Y (not necessarily an integer).

Output will be judged correct when the absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
10000 JPY
0.10000000 BTC

Sample Output 1

48000.0

The otoshidama from the first relative is 10000 yen. The otoshidama from the second relative is 0.1 bitcoins, which is worth 38000.0 yen if converted at the rate of 380000.0 JPY per 1.0 BTC. The sum of these is 48000.0 yen.

Outputs such as 48000 and 48000.1 will also be judged correct.

Sample Input 2

3
100000000 JPY
100.00000000 BTC
0.00000001 BTC

Sample Output 2

138000000.0038

In this case, outputs such as 138001000 and 1.38e8 will also be judged correct.


import Data.List ((\\))

main :: IO ()
main = do
  nabc <- map read . words <$> getLine
  ls <- map read . lines <$> getContents
  let
    patterns = filter (null . ([1, 2, 3] \\)) . sequence . replicate (nabc !! 0) $ [0, 1, 2, 3]
    m = minimum . map mp $ patterns
    mp pattern = sum . flip map [1, 2, 3] . (\pls i -> let lsi = map snd . filter ((==  i) . fst) $ pls in (10 * (length lsi - 1) + abs (sum lsi - (nabc !! i)))) . zip pattern $ ls
  print m

Score : 300 points

Problem Statement

You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.

Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.

Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

3 \leq N \leq 8

1 \leq C < B < A \leq 1000

1 \leq l_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C
l_1
l_2
:
l_N

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.

Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)

Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)

Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)

Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is 0. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243


{-# LANGUAGE BangPatterns          #-}

import Control.Monad
import qualified Data.Vector.Unboxed as V

main = do
    [a,b,q] <- map read . words <$> getLine
    vss <- (\x->V.fromList $ (-2*10^10):x ++ [2*10^10]) <$> replicateM a readLn
    vts <- (\x->V.fromList $ (-2*10^10):x ++ [2*10^10]) <$> replicateM b readLn
    vxs <- (\x->V.fromList $ x) <$> replicateM q readLn
    let as = V.toList $ V.map (solve vss vts) vxs
    sequence_ [print $ a | a <- as]

solve :: V.Vector Int -> V.Vector Int -> Int -> Int
solve vss vts x = minimum [d n|n <-ns]
    where
        ns = toPair (bIdxSrch vss x (0,V.length vss -1)) (bIdxSrch vts x (0,V.length vts -1))
        d = \(i,j) -> min (abs(x - (V.unsafeIndex vss i)) + abs ((V.unsafeIndex vss i) - (V.unsafeIndex vts j))) (abs (x - (V.unsafeIndex vts j) ) + abs((V.unsafeIndex vss i) - (V.unsafeIndex vts j)))

toPair :: (Int,Int) -> (Int,Int) -> [(Int,Int)]
toPair (a,b) (c,d) = [(a,c),(a,d),(b,c),(b,d)]

bIdxSrch :: V.Vector Int -> Int -> (Int,Int) -> (Int,Int)
bIdxSrch vs x (!l,!r)
    | midIdx == l = (l,l+1)
    |  x <= midVal = bIdxSrch vs x (l, midIdx)
    | otherwise = bIdxSrch vs x (midIdx, r)
        where
            midIdx = (r-l) `div` 2 + l
            midVal = V.unsafeIndex vs midIdx

Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.


import Data.Vector.Unboxed (Vector, (!))
import qualified Data.Vector.Unboxed as V

main = do
  [a,b,q] <- map read . words <$> getLine
  input   <- V.fromList . map read . lines <$> getContents :: IO (Vector Int)
  let
    (ss, left ) = V.splitAt a input
    (ts, left') = V.splitAt b left
    xs = V.toList left'
  putStr . unlines . map show $ solve ss ts xs

solve ss ts = map (inner ss ts)
  where
  inner ss ts x =
    minimum [ abs (p2 - p1) + abs (p1 - x)
            | (first, second) <- [(fst, snd), (snd, fst)]
            , let nx = ( nears x ss, nears x ts ); ps1 = first nx; ps2 = second nx
            , p1 <- [fst ps1, snd ps1], p2 <- [fst ps2, snd ps2] ]

nears x ps
  | x < V.head ps = (-10000000000,V.head ps)
  | x < V.last ps = ( ps!i, ps!(i+1) )
  | otherwise     = (V.last ps, 20000000000)
  where i = borderl (<=x) ps

borderl f v = inner 0 (V.length v - 1)
  where
  inner i j
    | i == j    = i
    | otherwise = if f (v!m) then inner m j else inner i (m-1)
    where m = div (i+j+1) 2


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns          #-}
{-# LANGUAGE CPP                   #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE RecordWildCards       #-}
{-# LANGUAGE TupleSections         #-}
{-# LANGUAGE TypeFamilies          #-}

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Data.Bool
import qualified Data.ByteString.Char8       as B
import qualified Data.ByteString.Unsafe      as B
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
import qualified Data.IntMap.Strict          as IM
import qualified Data.IntSet                 as IS
import           Data.List
import qualified Data.Map.Strict             as M
import           Data.Monoid
import           Data.Ord
import           Data.Primitive.MutVar
import qualified Data.Set                    as S
import           Data.Tuple
import qualified Data.Vector                 as V
import qualified Data.Vector.Generic         as G
import qualified Data.Vector.Generic.Mutable as GM
import qualified Data.Vector.Unboxed         as U
import qualified Data.Vector.Unboxed.Mutable as UM
import           Debug.Trace
import           Foreign                     hiding (void)
import           Unsafe.Coerce

main :: IO ()
main = do
    [a, b, q] <- map read.words <$> getLine :: IO [Int]
    sstsxs <- U.unfoldrN (a + b + q) (B.readInt.B.dropWhile isSpace) <$> B.getContents
    let (ss, tsxs) = U.splitAt a sstsxs
    let (ts, xs) = U.splitAt b tsxs
    putStr.unlines.map show.U.toList $ solve ss ts xs

solve :: U.Vector Int -> U.Vector Int -> U.Vector Int -> U.Vector Int
solve ss ts xs = U.map f xs
  where
    f x = minimum $ s2t x ++ t2s x
    s2t x = do
        Just !si <- [prevIx x ss, nextIx x ss]
        let !s = U.unsafeIndex ss si
        Just !ti <- [prevIx s ts, nextIx s ts]
        let !t = U.unsafeIndex ts ti
        return $! abs (s - x) + abs (t - s)
    t2s x = do
        Just !ti <- [prevIx x ts, nextIx x ts]
        let !t = U.unsafeIndex ts ti
        Just !si <- [prevIx t ss, nextIx t ss]
        let !s = U.unsafeIndex ss si
        return $! abs (t - x) + abs (s - t)

prevIx :: Int -> U.Vector Int -> Maybe Int
prevIx x xs
    | x < U.head xs = Nothing
    | otherwise = Just $ upperBound 0 (U.length xs - 1) (\i -> U.unsafeIndex xs i <= x)

nextIx :: Int -> U.Vector Int -> Maybe Int
nextIx x xs
    | U.last xs < x = Nothing
    | otherwise = Just $ lowerBound 0 (U.length xs - 1) (\i -> x <= U.unsafeIndex xs i)

-------------------------------------------------------------------------------
lowerBound :: (Integral i) => i -> i -> (i -> Bool) -> i
lowerBound low high p = go low high
  where
    go !low !high
        | high <= low = high
        | p mid       = go low       mid
        | otherwise   = go (mid + 1) high
      where
        h = toInteger high
        l = toInteger low
        mid = fromIntegral $ l + div (h - l) 2
{-# INLINE lowerBound #-}

upperBound :: (Integral i) => i -> i -> (i -> Bool) -> i
upperBound low high p
    | p high = high
    | otherwise = lowerBound low high (not.p) - 1
{-# INLINE upperBound #-}


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

Score : 100 points

Problem Statement

You are given positive integers A and B.

If A is a divisor of B, print A + B; otherwise, print B - A.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

If A is a divisor of B, print A + B; otherwise, print B - A.

Sample Input 1

4 12

Sample Output 1

16

As 4 is a divisor of 12, 4 + 12 = 16 should be printed.

Sample Input 2

8 20

Sample Output 2

12

Sample Input 3

1 1

Sample Output 3

2

1 is a divisor of 1.


import Control.Monad

main = do
    [n,m] <- map read . words <$> getLine
    a <- replicateM n (map read . words <$> getLine) :: IO [[Int]]
    let b = join $ map (\x -> tail x) a
    print $ sum [ isAns b i n | i<-[1..30]]

isAns :: [Int] -> Int -> Int -> Int
isAns b i n = let num = filter (==i) b in if length num == n then 1 else 0

Score : 200 points

Problem Statement

Katsusando loves omelette rice.

Besides, he loves crème brûlée, tenderloin steak and so on, and believes that these foods are all loved by everyone.

To prove that hypothesis, he conducted a survey on M kinds of foods and asked N people whether they like these foods or not.

The i-th person answered that he/she only likes the A_{i1}-th, A_{i2}-th, ..., A_{iK_i}-th food.

Find the number of the foods liked by all the N people.

Constraints

All values in input are integers.

1 \leq N, M \leq 30

1 \leq K_i \leq M

1 \leq A_{ij} \leq M

For each i (1 \leq i \leq N), A_{i1}, A_{i2}, ..., A_{iK_i} are distinct.

Constraints

Input is given from Standard Input in the following format:

N M
K_1 A_{11} A_{12} ... A_{1K_1}
K_2 A_{21} A_{22} ... A_{2K_2}
:
K_N A_{N1} A_{N2} ... A_{NK_N}

Output

Print the number of the foods liked by all the N people.

Sample Input 1

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

Sample Output 1

1

As only the third food is liked by all the three people, 1 should be printed.

Sample Input 2

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

Sample Output 2

0

Katsusando's hypothesis turned out to be wrong.

Sample Input 3

1 30
3 5 10 30

Sample Output 3

3


import Data.List

main = do
    getLine
    xs <- map read . words <$> getLine :: IO [Int]
    print $ foldl1 gcd xs

Score : 300 points

Problem Statement

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

Initially, the health of Monster i is A_i.

Below, a monster with at least 1 health is called alive.

Until there is only one alive monster, the following is repeated:

A random alive monster attacks another random alive monster.

As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.

Find the minimum possible final health of the last monster alive.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

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 minimum possible final health of the last monster alive.

Sample Input 1

4
2 10 8 40

Sample Output 1

2

When only the first monster keeps on attacking, the final health of the last monster will be 2, which is minimum.

Sample Input 2

4
5 13 8 1000000000

Sample Output 2

1

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

1000000000


import Control.Arrow (second)
import Data.List
import qualified Data.Vector.Unboxed as V
import qualified Data.ByteString.Char8 as B

solve :: V.Vector Int -> Int
solve xs = V.foldl' gcd (V.minimum xs) xs

main = do
  Just n <- fmap fst . B.readInt <$> B.getLine
  xs <- V.unfoldrN n (fmap (second B.tail) . B.readInt) <$> B.getLine
  print $ solve xs


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns          #-}
{-# LANGUAGE CPP                   #-}
{-# LANGUAGE LambdaCase            #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE MultiWayIf            #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE RecordWildCards       #-}
{-# LANGUAGE TupleSections         #-}
{-# LANGUAGE TypeFamilies          #-}

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Data.Bool
import qualified Data.ByteString.Char8       as B
import qualified Data.ByteString.Unsafe      as B
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
import qualified Data.IntMap.Strict          as IM
import qualified Data.IntSet                 as IS
import           Data.List
import qualified Data.Map.Strict             as M
import           Data.Monoid
import           Data.Ord
import           Data.Primitive.MutVar
import qualified Data.Set                    as S
import           Data.Tuple
import qualified Data.Vector                 as V
import qualified Data.Vector.Generic         as G
import qualified Data.Vector.Generic.Mutable as GM
import qualified Data.Vector.Unboxed         as U
import qualified Data.Vector.Unboxed.Mutable as UM
import           Debug.Trace
import           Foreign                     hiding (void)
import           Unsafe.Coerce

#define NOTHING (-1)

main :: IO ()
main = do
    [n, m] <- map read.words <$> getLine :: IO [Int]
    digits <- V.unfoldrN m (B.readInt.B.dropWhile isSpace) <$> B.getLine
    print $ solve n digits

solve :: Int -> V.Vector Int -> Integer
solve n digits = memo V.! n
  where
    memo = V.generate (n + 1) $ \case
        0 -> 0
        i -> V.maximum . flip V.map digits $ \digit ->
            if  | cost U.! digit <= i -> case memo V.! (i - cost U.! digit) of
                    NOTHING -> NOTHING
                    x -> 10 * x + fromIntegral digit
                | otherwise -> NOTHING

cost :: U.Vector Int
cost = U.fromList [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]

Score : 400 points

Problem Statement

Find the largest integer that can be formed with exactly N matchsticks, under the following conditions:

Every digit in the integer must be one of the digits A_1, A_2, ..., A_M (1 \leq A_i \leq 9).

The number of matchsticks used to form digits 1, 2, 3, 4, 5, 6, 7, 8, 9 should be 2, 5, 5, 4, 5, 6, 3, 7, 6, respectively.

Constraints

All values in input are integers.

2 \leq N \leq 10^4

1 \leq M \leq 9

1 \leq A_i \leq 9

A_i are all different.

There exists an integer that can be formed by exactly N matchsticks under the conditions.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_M

Output

Print the largest integer that can be formed with exactly N matchsticks under the conditions in the problem statement.

Sample Input 1

20 4
3 7 8 4

Sample Output 1

777773

The integer 777773 can be formed with 3 + 3 + 3 + 3 + 3 + 5 = 20 matchsticks, and this is the largest integer that can be formed by 20 matchsticks under the conditions.

Sample Input 2

101 9
9 8 7 6 5 4 3 2 1

Sample Output 2

71111111111111111111111111111111111111111111111111

The output may not fit into a 64-bit integer type.

Sample Input 3

15 3
5 4 6

Sample Output 3

654


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

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

solve :: [Int] -> Int
solve [k, a, b]
    | k <= a || b - a < 3 = k + 1
    | odd d = (n + 1) * (b - a) + a
    | otherwise = n * (b - a) + a + 1
    where
        d = k - a
        n = d `div` 2

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

readContents :: Int -> IO [[Int]]
readContents = flip replicateM readLine

Score : 400 points

Problem Statement

Snuke has one biscuit and zero Japanese yen (the currency) in his pocket.
He will perform the following operations exactly K times in total, in the order he likes:

Hit his pocket, which magically increases the number of biscuits by one.

Exchange A biscuits to 1 yen.

Exchange 1 yen to B biscuits.

Find the maximum possible number of biscuits in Snuke's pocket after K operations.

Constraints

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

K,A and B are integers.

Input

Input is given from Standard Input in the following format:

K A B

Output

Print the maximum possible number of biscuits in Snuke's pocket after K operations.

Sample Input 1

4 2 6

Sample Output 1

7

The number of biscuits in Snuke's pocket after K operations is maximized as follows:

Hit his pocket. Now he has 2 biscuits and 0 yen.

Exchange 2 biscuits to 1 yen. his pocket. Now he has 0 biscuits and 1 yen.

Hit his pocket. Now he has 1 biscuits and 1 yen.

Exchange 1 yen to 6 biscuits. his pocket. Now he has 7 biscuits and 0 yen.

Sample Input 2

7 3 4

Sample Output 2

8

Sample Input 3

314159265 35897932 384626433

Sample Output 3

48518828981938099


{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE RankNTypes #-}
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Maybe
import Data.List
import qualified Data.Vector.Unboxed as VU
-- import qualified Data.Vector.Unboxed.Mutable as VUM
-- import Control.Monad
-- import Control.Monad.ST
import Debug.Trace
-- trace _ = id

solve :: Int -> [Int] -> Int
solve bL as = minimum finVals
  where
  finVals = foldl f [0,0,0,0,0] as
    where
    f vals a = zipWith (\fn !v -> v + fn a)
                 fns (tail (scanl' min maxBound vals))

fns = [id, gRet, gOw, gRet, id]

gRet 0 = 2
gRet x | odd x = 1
       | even x = 0

gOw x | odd x = 0
      | even x = 1

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

traceL :: Show a => String -> a -> b -> b
traceL label showObj val = trace (label ++ " " ++ show showObj) val

traceLM :: (Monad m, Show a) => String -> (b -> a) -> m b -> m b
traceLM label showFn act = do
  aaa <- act
  traceL label (showFn aaa) (return ())
  return aaa

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

tmain :: B.ByteString -> Int
tmain cont =
  let remLines0 = map B.words (B.lines cont)
      [bs_bL]:remLines1 = remLines0
      bL = readBInt bs_bL
      as = map (\[x] -> readBInt x) remLines1
  in solve bL as

outAnswer :: Int -> IO ()
outAnswer = putStrLn . show

main :: IO ()
main = outAnswer . tmain =<< B.getContents

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

inp1 = "4\n1\n0\n2\n3\n"
inp2 = "8\n2\n0\n0\n2\n1\n3\n4\n1\n"
inp3 = "7\n314159265\n358979323\n846264338\n327950288\n419716939\n937510582\n0\n"
tv1 = tmain $ B.pack inp1
tv2 = tmain $ B.pack inp2
tv3 = tmain $ B.pack inp3
test1 = tv1 == 1
test2 = tv2 == 3
test3 = tv3 == 1
alltest = test1 && test2 && test3

Score : 600 points

Problem Statement

Snuke stands on a number line. He has L ears, and he will walk along the line continuously under the following conditions:

He never visits a point with coordinate less than 0, or a point with coordinate greater than L.

He starts walking at a point with integer coordinate, and also finishes walking at a point with integer coordinate.

He only changes direction at a point with integer coordinate.

Each time when Snuke passes a point with coordinate i-0.5, where i is an integer, he put a stone in his i-th ear.

After Snuke finishes walking, Ringo will repeat the following operations in some order so that, for each i, Snuke's i-th ear contains A_i stones:

Put a stone in one of Snuke's ears.

Remove a stone from one of Snuke's ears.

Find the minimum number of operations required when Ringo can freely decide how Snuke walks.

Constraints

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

0 \leq A_i \leq 10^9(1\leq i\leq L)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

L
A_1
:
A_L

Output

Print the minimum number of operations required when Ringo can freely decide how Snuke walks.

Sample Input 1

4
1
0
2
3

Sample Output 1

1

Assume that Snuke walks as follows:

He starts walking at coordinate 3 and finishes walking at coordinate 4, visiting coordinates 3,4,3,2,3,4 in this order.

Then, Snuke's four ears will contain 0,0,2,3 stones, respectively.
Ringo can satisfy the requirement by putting one stone in the first ear.

Sample Input 2

8
2
0
0
2
1
3
4
1

Sample Output 2

3

Sample Input 3

7
314159265
358979323
846264338
327950288
419716939
937510582
0

Sample Output 3

1


{-# LANGUAGE
  ScopedTypeVariables, BangPatterns, TupleSections, ExplicitForAll,
  LambdaCase, MultiWayIf, Unsafe, RecordWildCards, FlexibleContexts, CPP,
  NoMonomorphismRestriction, GADTs,
  RankNTypes, EmptyDataDecls, EmptyCase, ViewPatterns #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IMS
import qualified Data.IntMap.Lazy as IML
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import Control.Monad
import Control.Monad.ST
-- import Control.Monad.ST.Safe
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import System.IO
import Data.Function
import Control.Monad.Primitive
import qualified Data.Vector.Primitive.Mutable as VPM
import qualified Data.Vector.Generic.Mutable as VGM
import Data.STRef
import Data.IORef

main :: IO ()
main = do
  input <- BS.getLine
  let n = BS.length input
      blues = VU.map (subtract (fromEnum '0') . fromEnum)
              $ VU.unfoldrN n BS.uncons input
      (!vec_aftern,!bleft_aftern,!b,!r) = VU.ifoldl'
        (\(!vec_prev,!bleft_prev,!b_prev,!r_prev) !i !b_this ->
           let !len_prev = VU.length vec_prev
               !b = b_prev + b_this
               !r = r_prev + 2 - b_this
               !bleft | shortenleft = bleft_prev + 1
                      | otherwise   = bleft_prev
               !vec = VU.zipWith plus (VU.cons 0 vec_prev) (VU.snoc vec_prev 0)
               !shortenleft = r <= i - bleft_prev
               !shortenright = b <= bleft_prev + len_prev - 1
               sl | shortenleft = 1 | otherwise = 0
               sr | shortenright = 1 | otherwise = 0
           in (,bleft,b,r)
              $! VU.slice sl (len_prev + 1 - sl - sr) vec)
        (VU.singleton 1,0, 0, 0) blues
      (!lastvec,!bleft_last) = foldl'
        (\ (!vec_prev,!bleft_prev) !i ->
            let !len_prev = VU.length vec_prev
                !vec = VU.zipWith plus (VU.cons 0 vec_prev) (VU.snoc vec_prev 0)
                !bleft = bleft_prev + sl
                !shortenleft = r <= i-1 - bleft_prev
                !shortenright = b <= bleft_prev + len_prev - 1
                sl | shortenleft = 1 | otherwise = 0
                sr | shortenright = 1 | otherwise = 0
            in (VU.slice sl (len_prev + 1 - sl - sr) vec, bleft))
        (vec_aftern,bleft_aftern) [n+1..2*n]
  print $ lastvec VU.! 0

{-# INLINE plus #-}
plus :: Int -> Int -> Int
plus x y
  | xpy >= modulus = xpy - modulus
  | otherwise      = xpy
  where !xpy = x+y

{-# INLINE modulus #-}
modulus :: (Integral i) => i
modulus = 998244353

{-# INLINE nprime #-}
nprime :: Word64
nprime = 998244351

{-# INLINE rsq #-}
rsq :: Word64
rsq = 932051910

newtype Montgomery = Mon {unMon :: Word32}
  deriving (Eq, Show)

instance Num Montgomery where
  {-# INLINE (+) #-}
  (+) = monAdd
  {-# INLINE (*) #-}
  (*) = monMult
  {-# INLINE (-) #-}
  (-) = monSub
  {-# INLINE negate #-}
  negate (Mon x) = Mon (modulus - x)
  {-# INLINE fromInteger #-}
  fromInteger = monRep . fromInteger
  {-# INLINE signum #-}
  signum x | x == Mon 0 = Mon 0
           | otherwise  = monRep 1
  {-# INLINE abs #-}
  abs = id

{-# INLINE monMult #-}
monMult :: Montgomery -> Montgomery -> Montgomery
monMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y

{-# INLINE monAdd #-}
monAdd :: Montgomery -> Montgomery -> Montgomery
monAdd (Mon x) (Mon y) = Mon $ x+y + if x >= modulus-y then modulus else 0

{-# INLINE monSub #-}
monSub :: Montgomery -> Montgomery -> Montgomery
monSub (Mon x) (Mon y) = Mon $ x-y + if x < y then modulus else 0

{-# INLINE monRep #-}
monRep :: Word32 -> Montgomery
monRep x = Mon $ monRed $ rsq * fromIntegral x

{-# INLINE fromMon #-}
fromMon :: Montgomery -> Word32
fromMon (Mon x) = monRed $ fromIntegral x

{-# INLINE monRed #-}
monRed :: Word64 -> Word32
monRed x = t - if t >= modulus then modulus else 0
  where t = fromIntegral $ (`shiftR` 32) $ x + x*nprime .&.mask32 *modulus

mask32 :: Word64
mask32 = bit 32 - 1

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

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

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

Score : 900 points

Problem Statement

There are N Snukes lining up in a row.
You are given a string S of length N. The i-th Snuke from the front has two red balls if the i-th character in S is 0; one red ball and one blue ball if the i-th character in S is 1; two blue balls if the i-th character in S is 2.

Takahashi has a sequence that is initially empty. Find the number of the possible sequences he may have after repeating the following procedure 2N times, modulo 998244353:

Each Snuke who has one or more balls simultaneously chooses one of his balls and hand it to the Snuke in front of him, or hand it to Takahashi if he is the first Snuke in the row.

Takahashi receives the ball and put it to the end of his sequence.

Constraints

1 \leq |S| \leq 2000

S consists of 0,1 and 2.

Note that the integer N is not directly given in input; it is given indirectly as the length of the string S.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of the possible sequences Takahashi may have after repeating the procedure 2N times, modulo 998244353.

Sample Input 1

02

Sample Output 1

3

There are three sequences that Takahashi may have: rrbb, rbrb and rbbr, where r and b stand for red and blue balls, respectively.

Sample Input 2

1210

Sample Output 2

55

Sample Input 3

12001021211100201020

Sample Output 3

543589959


import Control.Monad

main = do
    [t, x] <- fmap read <$> words <$> getLine
    putStrLn $ show $ solve t x

solve :: Double -> Double -> Double
solve t x = t / x

Score : 100 points

Problem Statement

In order to pass the entrance examination tomorrow, Taro has to study for T more hours.

Fortunately, he can leap to World B where time passes X times as fast as it does in our world (World A).

While (X \times t) hours pass in World B, t hours pass in World A.

How many hours will pass in World A while Taro studies for T hours in World B?

Constraints

All values in input are integers.

1 \leq T \leq 100

1 \leq X \leq 100

Input

Input is given from Standard Input in the following format:

T X

Output

Print the number of hours that will pass in World A.

The output will be regarded as correct when its absolute or relative error from the judge's output is at most 10^{-3}.

Sample Input 1

8 3

Sample Output 1

2.6666666667

While Taro studies for eight hours in World B where time passes three times as fast, 2.6666... hours will pass in World A.

Note that an absolute or relative error of at most 10^{-3} is allowed.

Sample Input 2

99 1

Sample Output 2

99.0000000000

Sample Input 3

1 100

Sample Output 3

0.0100000000


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


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
import qualified Data.ByteString.Char8 as B
import           Data.Char             (isSpace)
import qualified Data.Vector.Unboxed   as V

main :: IO ()
main = do
  n <- readLn
  ls <- V.unfoldrN n parseInt <$> B.getLine
  putStrLn $ if solve n ls then "Yes" else "No"

solve :: Int -> V.Vector Int -> Bool
solve _ ls = m < V.sum (V.take i ls) + V.sum (V.drop (i + 1) ls)
  where i = V.maxIndex ls
        m = ls V.! i

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

Score : 200 points

Problem Statement

Determine if an N-sided polygon (not necessarily convex) with sides of length L_1, L_2, ..., L_N can be drawn in a two-dimensional plane.

You can use the following theorem:

Theorem: an N-sided polygon satisfying the condition can be drawn if and only if the longest side is strictly shorter than the sum of the lengths of the other N-1 sides.

Constraints

All values in input are integers.

3 \leq N \leq 10

1 \leq L_i \leq 100

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Output

If an N-sided polygon satisfying the condition can be drawn, print Yes; otherwise, print No.

Sample Input 1

4
3 8 5 1

Sample Output 1

Yes

Since 8 < 9 = 3 + 5 + 1, it follows from the theorem that such a polygon can be drawn on a plane.

Sample Input 2

4
3 8 4 1

Sample Output 2

No

Since 8 \geq 8 = 3 + 4 + 1, it follows from the theorem that such a polygon cannot be drawn on a plane.

Sample Input 3

10
1 8 10 5 8 12 34 100 11 3

Sample Output 3

No


import Data.List

main :: IO ()
main = do
  getLine
  ls <- map read . words <$> getLine
  putStrLn $ if solve ls
    then "Yes"
    else "No"

solve :: [Int] -> Bool
solve ls = x > sum xs
  where (x:xs) = sortBy (flip compare) ls


import Data.List
main=do
 [n,m]<-map read.words<$>getLine
 x<-sort.map read.words<$>getLine
 print(g n (f m x))
  where g n l =sum (drop(n-1)(reverse(sort l)))
        f 1 _ =[]
        f m (a:b:x) =(b-a):(f(m-1)(b:x))

Score : 300 points

Problem Statement

We will play a one-player game using a number line and N pieces.

First, we place each of these pieces at some integer coordinate.

Here, multiple pieces can be placed at the same coordinate.

Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:

Move: Choose a piece and let x be its coordinate. Put that piece at coordinate x+1 or x-1.

Note that the coordinates where we initially place the pieces are already regarded as visited.

Find the minimum number of moves required to achieve the objective.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

-10^5 \leq X_i \leq 10^5

X_1, X_2, ..., X_M are all different.

Input

Input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_M

Output

Find the minimum number of moves required to achieve the objective.

Sample Input 1

2 5
10 12 1 2 14

Sample Output 1

5

The objective can be achieved in five moves as follows, and this is the minimum number of moves required.

Initially, put the two pieces at coordinates 1 and 10.

Move the piece at coordinate 1 to 2.

Move the piece at coordinate 10 to 11.

Move the piece at coordinate 11 to 12.

Move the piece at coordinate 12 to 13.

Move the piece at coordinate 13 to 14.

Sample Input 2

3 7
-10 -3 0 9 -100 2 17

Sample Output 2

19

Sample Input 3

100 1
-100000

Sample Output 3

0


import Data.List

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

solve :: Int -> [Int] -> Int
solve n = sum . drop (n-1) . reverse . sort . distances . sort

distances :: [Int] -> [Int]
distances xs = zipWith subtract xs (tail xs)


solve :: String -> String -> String -> Int
solve [] [] [] = 0
solve (a1:ax) (b1:bx) (c1:cx)
  | a1 == b1 && b1 == c1             =     solve ax bx cx
  | a1 == b1 || b1 == c1 || a1 == c1 = 1 + solve ax bx cx
  | otherwise                        = 2 + solve ax bx cx

main :: IO ()
main = do
  _ <- getLine
  a <- getLine
  b <- getLine
  c <- getLine
  print $ solve a b c

Score : 200 points

Problem Statement

You are given three strings A, B and C. Each of these is a string of length N consisting of lowercase English letters.

Our objective is to make all these three strings equal. For that, you can repeatedly perform the following operation:

Operation: Choose one of the strings A, B and C, and specify an integer i between 1 and N (inclusive). Change the i-th character from the beginning of the chosen string to some other lowercase English letter.

What is the minimum number of operations required to achieve the objective?

Constraints

1 \leq N \leq 100

Each of the strings A, B and C is a string of length N.

Each character in each of the strings A, B and C is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
A
B
C

Output

Print the minimum number of operations required.

Sample Input 1

4
west
east
wait

Sample Output 1

3

In this sample, initially A = west、B = east、C = wait. We can achieve the objective in the minimum number of operations by performing three operations as follows:

Change the second character in A to a. A is now wast.

Change the first character in B to w. B is now wast.

Change the third character in C to s. C is now wast.

Sample Input 2

9
different
different
different

Sample Output 2

0

If A, B and C are already equal in the beginning, the number of operations required is 0.

Sample Input 3

7
zenkoku
touitsu
program

Sample Output 3

13


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

main = do
  n <- readLn
  [a,b,c] <- replicateM 3 getLine
  putStrLn $ show $ cnt a b c n

cnt :: [Char] -> [Char] -> [Char] -> Int -> Int
cnt (a:as) (b:bs) (c:cs) n
  |n <= 0 = 0
  |((a:as) == (b:bs)) && ((b:bs) == (c:cs)) = 0
  |length (filter (== a) [b,c]) == 1 = (+) 1 $ cnt as bs cs (n -1)
  |(b == c) = (+) 1 $ cnt as bs cs (n -1)
  |otherwise =  (+) 2 $ cnt as bs cs (n -1)
cnt _ _ _ 0 = 0


main = do
  [ab, bc, _] <- map read .words <$> getLine
  print $ ab * bc `div` 2

Score : 100 points

Problem Statement

There is a right triangle ABC with ∠ABC=90°.

Given the lengths of the three sides, |AB|,|BC| and |CA|, find the area of the right triangle ABC.

It is guaranteed that the area of the triangle ABC is an integer.

Constraints

1 \leq |AB|,|BC|,|CA| \leq 100

All values in input are integers.

The area of the triangle ABC is an integer.

Input

Input is given from Standard Input in the following format:

|AB| |BC| |CA|

Output

Print the area of the triangle ABC.

Sample Input 1

3 4 5

Sample Output 1

6

This triangle has an area of 6.

Sample Input 2

5 12 13

Sample Output 2

30

This triangle has an area of 30.

Sample Input 3

45 28 53

Sample Output 3

630

This triangle has an area of 630.


update [] _ = Nothing
update (h:hs) (x:xs)
  | h == x = (x:) <$> update hs xs
  | h > x  = Just $ grow (h:hs) (x:xs)
  where
    grow [] _ = []
    grow (h:hs) (x:xs)
      | h == x = x:xs
      | h > x = (x + 1) : grow hs xs

solv hs = go hs (repeat 0) 0 where
  go hs xs i =
    case update hs xs of
      Nothing -> i
      Just updated -> go hs updated (succ i)

main = do
  getLine
  hs <- map read . words <$> getLine
  print $ solv hs

Score : 300 points

Problem Statement

In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0.
You are given a sequence h=\{h_1,h_2,h_3,......\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation:

Specify integers l and r. Increase the height of Flower x by 1 for all x such that l \leq x \leq r.

Find the minimum number of watering operations required to satisfy the condition.

Constraints

1 \leq N \leq 100

0 \leq h_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 h_3 ...... h_N

Output

Print the minimum number of watering operations required to satisfy the condition.

Sample Input 1

4
1 2 2 1

Sample Output 1

2

The minimum number of watering operations required is 2.
One way to achieve it is:

Perform the operation with (l,r)=(1,3).

Perform the operation with (l,r)=(2,4).

Sample Input 2

5
3 1 2 3 1

Sample Output 2

5

Sample Input 3

8
4 23 75 0 23 96 50 100

Sample Output 3

221


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE CPP               #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections     #-}

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Data.Bool
import qualified Data.ByteString.Char8       as B
import qualified Data.ByteString.Unsafe      as B
import           Data.Char
import           Data.Function
import qualified Data.IntMap.Strict          as IM
import qualified Data.IntSet                 as IS
import           Data.List
import           Data.Monoid
import           Data.Ord
import           Data.Primitive.MutVar
import qualified Data.Set                    as S
import           Data.Tuple
import qualified Data.Vector                 as V
import qualified Data.Vector.Generic         as G
import qualified Data.Vector.Generic.Mutable as GM
import qualified Data.Vector.Unboxed         as U
import qualified Data.Vector.Unboxed.Mutable as UM
import           Debug.Trace
import           Foreign                     hiding (void)
import           Unsafe.Coerce

main :: IO ()
main = do
    [n, k] <- map read.words <$> getLine
    tds <- U.unfoldrN n parseInt2 <$> B.getContents
    print $ solve n k tds

solve :: Int -> Int -> U.Vector (Int, Int) -> Int
solve n k tds = go res0 s0 size0 used0 (reverse $ buildQ xs) ys
  where
    (xs, ys) = splitAt k
        . sortBy (flip compare)
        . map swap
        $ U.toList tds
    !s0 = sum $ map fst xs
    !size0 = IS.size used0
    !used0 = IS.fromList $ map snd xs
    !res0 = s0 + size0 * size0

    go !res !s !size !used fs ((d, t):rest)
        | IS.member t used = go res s size used fs rest
        | otherwise = case fs of
            (z:zs)
                | size' <- size + 1
                , s' <- s - z + d
                , res' <- max res $ s' + size' * size'
                , used' <- IS.insert t used
                -> go res' s' size' used' zs rest
            [] -> res
    go res _ _ _ _ [] = res

buildQ :: [(Int, Int)] -> [Int]
buildQ dts = go IS.empty dts
  where
    go !used ((d, t):rest)
      | IS.member t used = d : go used rest
      | otherwise = go (IS.insert t used) rest
    go _ [] = []

type Parser a = B.ByteString -> Maybe (a, B.ByteString)

parseInt :: Parser Int
parseInt = B.readInt . B.dropWhile isSpace

parseInt2 :: Parser (Int, Int)
parseInt2 = runStateT $
    (,) <$> StateT (B.readInt . B.dropWhile isSpace)
        <*> StateT (B.readInt . B.unsafeTail)

Score : 400 points

Problem Statement

There are N pieces of sushi. Each piece has two parameters: "kind of topping" t_i and "deliciousness" d_i.
You are choosing K among these N pieces to eat.
Your "satisfaction" here will be calculated as follows:

The satisfaction is the sum of the "base total deliciousness" and the "variety bonus".

The base total deliciousness is the sum of the deliciousness of the pieces you eat.

The variety bonus is x*x, where x is the number of different kinds of toppings of the pieces you eat.

You want to have as much satisfaction as possible.
Find this maximum satisfaction.

Constraints

1 \leq K \leq N \leq 10^5

1 \leq t_i \leq N

1 \leq d_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
t_1 d_1
t_2 d_2
.
.
.
t_N d_N

Output

Print the maximum satisfaction that you can obtain.

Sample Input 1

5 3
1 9
1 7
2 6
2 5
3 1

Sample Output 1

26

If you eat Sushi 1,2 and 3:

The base total deliciousness is 9+7+6=22.

The variety bonus is 2*2=4.

Thus, your satisfaction will be 26, which is optimal.

Sample Input 2

7 4
1 1
2 1
3 1
4 6
4 5
4 5
4 5

Sample Output 2

25

It is optimal to eat Sushi 1,2,3 and 4.

Sample Input 3

6 5
5 1000000000
2 990000000
3 980000000
6 970000000
6 960000000
4 950000000

Sample Output 3

4900000016

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


main=do
 getLine
 [a,b]<-map read.words<$>getLine
 p<-map read.words<$>getLine
 let x=length$filter(<=a+0)p
 let y=length$filter(\q->a<q&&q<=b)p
 let z=length$filter(b<)p
 print$minimum[x,y,z]

Score : 200 points

Problem Statement

You have written N problems to hold programming contests.
The i-th problem will have a score of P_i points if used in a contest.

With these problems, you would like to hold as many contests as possible under the following condition:

A contest has three problems. The first problem has a score not greater than A points, the second has a score between A + 1 and B points (inclusive), and the third has a score not less than B + 1 points.

The same problem should not be used in multiple contests.
At most how many contests can be held?

Constraints

3 \leq N \leq 100

1 \leq P_i \leq 20 (1 \leq i \leq N)

1 \leq A < B < 20

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A B
P_1 P_2 ... P_N

Output

Print the answer.

Sample Input 1

7
5 15
1 10 16 2 7 20 12

Sample Output 1

2

Two contests can be held by putting the first, second, third problems and the fourth, fifth, sixth problems together.

Sample Input 2

8
3 8
5 5 5 10 10 10 15 20

Sample Output 2

0

No contest can be held, because there is no problem with a score of A = 3 or less.

Sample Input 3

3
5 6
5 6 10

Sample Output 3

1