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

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

#define MOD 1000000007

main :: IO ()
main = do
    [n, ma, mb] <- map read.words <$> getLine
    es <- U.unfoldrN n (runParser $ (,,) <$> int1 <*> int1 <*> int) <$> C.getContents
    print . maybe (-1) id $ solve n ma mb es

solve :: Int -> Int -> Int -> U.Vector (Int, Int, Int) -> Maybe Int
solve n ma mb es = runST $ do
    mat <- UM.replicate (512 * 512) maxBound
    UM.write mat (0 * 512 + 0) 0
    U.forM_ es $ \(a,b,c) -> do
        rev 512 $ \i -> do
            rev 512 $ \j -> do
                when (i-a>=0 && j-b>=0) $ do
                    x <- UM.unsafeRead mat ((i-a)*512+j-b)
                    when (x /= maxBound) $ do
                        UM.unsafeModify mat (min $! x + c) (i * 512 + j)
    res <- MS.foldl' min maxBound
        . MS.mapM (\i ->
            MS.foldl' min maxBound
                . MS.mapM (\j -> UM.read mat (i * 512 + j))
                . MS.filter (\j -> i * mb == j * ma)
                $ MS.generate 512 id
            )
        . MS.tail
        $ MS.generate 512 id
    if res == maxBound
    then return Nothing
    else return $ Just res

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


{-# OPTIONS_GHC -O #-}

import Control.Monad
import Control.Monad.ST
import Data.List
import Control.Monad.Trans.State.Strict
import Data.Char (isSpace)
import Data.Maybe (fromJust,fromMaybe)
import qualified Data.ByteString.Lazy.Char8 as B

import Data.Array.ST
import Data.Array.Unboxed
type Dist s = STUArray s (Int,Int) Int

type Parser a = StateT B.ByteString Maybe a

parseInt :: Parser Int
parseInt = StateT (B.readInt . B.dropWhile isSpace)

parseInt3 :: Parser (Int,Int,Int)
parseInt3 = liftM3 (,,) parseInt parseInt parseInt

parse :: Parser ((Int,Int,Int), [(Int,Int,Int)])
parse = do
    (n,ma,mb)<-parseInt3
    abcs<-replicateM n parseInt3
    return ((n,ma,mb),abcs)

main=do
    ((n,ma,mb),abcs)<-fromJust.evalStateT parse <$> B.getContents
    let dp = fdp n abcs :: UArray (Int,Int,Int) Int
    print $ solve n ma mb dp
--
fdp n abcs = runSTUArray $ do
    dp <- newArray ((0,0,0),(n,10*n,10*n)) 5000 :: ST s (STUArray s (Int,Int,Int) Int)
    writeArray dp (0,0,0) 0
    forM_ [(ii,u,v)|ii<-zip abcs [1..n],u<-[0..10*n],v<-[0..10*n]] $ \(((a,b,c),i),u,v) ->
        if u-a>=0 && v-b>=0 then
            writeArray dp (i,u,v) =<< min <$> ((+c) <$> readArray dp (i-1,u-a,v-b)) <*> readArray dp (i-1,u,v)
        else
            writeArray dp (i,u,v) =<< readArray dp (i-1,u,v)
    return dp
--
solve n ma mb dp
    | ar < 5000 = ar
    | otherwise = -1
    where
        ca = takeWhile (\c->c*ma<=10*n && c*mb<=10*n) [1..]
        ar = minimum $ map (\c -> dp ! (n,c*ma,c*mb)) ca

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

Score : 400 points

Problem Statement

Dolphin is planning to generate a small amount of a certain chemical substance C.

In order to generate the substance C, he must prepare a solution which is a mixture of two substances A and B in the ratio of M_a:M_b.

He does not have any stock of chemicals, however, so he will purchase some chemicals at a local pharmacy.

The pharmacy sells N kinds of chemicals. For each kind of chemical, there is exactly one package of that chemical in stock.

The package of chemical i contains a_i grams of the substance A and b_i grams of the substance B, and is sold for c_i yen (the currency of Japan).

Dolphin will purchase some of these packages. For some reason, he must use all contents of the purchased packages to generate the substance C.

Find the minimum amount of money required to generate the substance C.

If it is not possible to generate the substance C by purchasing any combination of packages at the pharmacy, report that fact.

Constraints

1≦N≦40

1≦a_i,b_i≦10

1≦c_i≦100

1≦M_a,M_b≦10

gcd(M_a,M_b)=1

a_i, b_i, c_i, M_a and M_b are integers.

Input

The input is given from Standard Input in the following format:

N M_a M_b
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the minimum amount of money required to generate the substance C. If it is not possible to generate the substance C, print -1 instead.

Sample Input 1

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

Sample Output 1

3

The amount of money spent will be minimized by purchasing the packages of chemicals 1 and 2.

In this case, the mixture of the purchased chemicals will contain 3 grams of the substance A and 3 grams of the substance B, which are in the desired ratio: 3:3=1:1.

The total price of these packages is 3 yen.

Sample Input 2

1 1 10
10 10 10

Sample Output 2

-1

The ratio 1:10 of the two substances A and B cannot be satisfied by purchasing any combination of the packages. Thus, the output should be -1.

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.


main :: IO ()
main = do
    getLine
    a <- even . length . filter odd <$> getInts
    putStrLn $ if a then "YES" else "NO"

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

Score : 300 points

Problem Statement

There are N integers written on a blackboard. The i-th integer is A_i.

Takahashi will repeatedly perform the following operation on these numbers:

Select a pair of integers, A_i and A_j, that have the same parity (that is, both are even or both are odd) and erase them.

Then, write a new integer on the blackboard that is equal to the sum of those integers, A_i+A_j.

Determine whether it is possible to have only one integer on the blackboard.

Constraints

2 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9

A_i is an integer.

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 … A_N

Output

If it is possible to have only one integer on the blackboard, print YES. Otherwise, print NO.

Sample Input 1

3
1 2 3

Sample Output 1

YES

It is possible to have only one integer on the blackboard, as follows:

Erase 1 and 3 from the blackboard, then write 4. Now, there are two integers on the blackboard: 2 and 4.

Erase 2 and 4 from the blackboard, then write 6. Now, there is only one integer on the blackboard: 6.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

NO


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

main :: IO ()
main = do
  solve <$> getl read <*> getl (map read . words) >>= putStrLn

solve :: Int -> [Int] -> String
solve n as = g as
  where
    f xs = zipWith (-) xs (rot (n - i) [1..n])
      where
        (Just i) = findIndex (== (minimum xs)) xs
    g xs = if all (== 0) ys then "YES" else if any (< 0) ys then "NO" else g ys
      where
        ys = f xs

rot :: Int -> [Int] -> [Int]
rot n xs = (drop n xs) ++ (take n xs)

getl :: (String -> a) -> IO a
getl f = f <$> getLine

Score : 500 points

Problem Statement

There are N boxes arranged in a circle. The i-th box contains A_i stones.

Determine whether it is possible to remove all the stones from the boxes by repeatedly performing the following operation:

Select one box. Let the box be the i-th box. Then, for each j from 1 through N, remove exactly j stones from the (i+j)-th box. Here, the (N+k)-th box is identified with the k-th box.

Note that the operation cannot be performed if there is a box that does not contain enough number of stones to be removed.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 … A_N

Output

If it is possible to remove all the stones from the boxes, print YES. Otherwise, print NO.

Sample Input 1

5
4 5 1 2 3

Sample Output 1

YES

All the stones can be removed in one operation by selecting the second box.

Sample Input 2

5
6 9 12 10 8

Sample Output 2

YES

Sample Input 3

4
1 2 3 1

Sample Output 3

NO


solve x = if x >= 1200 then "ARC" else "ABC"

main = interact $ solve . read

Score : 100 points

Problem Statement

Smeke has decided to participate in AtCoder Beginner Contest (ABC) if his current rating is less than 1200, and participate in AtCoder Regular Contest (ARC) otherwise.

You are given Smeke's current rating, x. Print ABC if Smeke will participate in ABC, and print ARC otherwise.

Constraints

1 ≦ x ≦ 3{,}000

x is an integer.

Input

The input is given from Standard Input in the following format:

x

Output

Print the answer.

Sample Input 1

1000

Sample Output 1

ABC

Smeke's current rating is less than 1200, thus the output should be ABC.

Sample Input 2

2000

Sample Output 2

ARC

Smeke's current rating is not less than 1200, thus the output should be ARC.


main = readLn >>= \x -> putStrLn $ if x < 1200 then "ABC" else "ARC"


main = interact $ (\x -> if x<1200 then "ABC" else "ARC") . read


main = do
  n <- readLn
  putStrLn $ if n < 1200 then "ABC" else "ARC"


main = interact $ show . sol . read

sol n = 2*q + r `div` 7
  where
  (q,r) = n `quotRem` 11

Score : 300 points

Problem Statement

Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7.

Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation:

Operation: Rotate the die 90° toward one of the following directions: left, right, front (the die will come closer) and back (the die will go farther). Then, obtain y points where y is the number written in the side facing upward.

For example, let us consider the situation where the side showing 1 faces upward, the near side shows 5 and the right side shows 4, as illustrated in the figure.
If the die is rotated toward the right as shown in the figure, the side showing 3 will face upward.
Besides, the side showing 4 will face upward if the die is rotated toward the left, the side showing 2 will face upward if the die is rotated toward the front, and the side showing 5 will face upward if the die is rotated toward the back.

Find the minimum number of operation Snuke needs to perform in order to score at least x points in total.

Constraints

1 ≦ x ≦ 10^{15}

x is an integer.

Input

The input is given from Standard Input in the following format:

x

Output

Print the answer.

Sample Input 1

7

Sample Output 1

2

Sample Input 2

149696127901

Sample Output 2

27217477801


main = do
  n <- readLn :: IO Int
  print $ (n `div` 11)*2 + (if n `mod` 11 > 6 then 2 else if n`mod` 11 > 0 then 1 else 0)


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

solve :: Int -> Int
solve x = q * 2 + rm
    where
        (q, r) = x `divMod` 11
        rm
            | r == 0 = 0
            | r <= 6 = 1
            | otherwise = 2


import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)
import Text.Printf
import Debug.Trace

main = do
  [x] <- getInts
  print $ (x `div` 11) * 2 + if (x `mod` 11 == 0) then 0 else if (x `mod` 11) <= 6 then 1 else 2

-- util
getInts :: IO [Integer]
getInts = map (fst . fromJust . B.readInteger) . B.words <$> B.getLine

substr :: Int -> Int -> B.ByteString -> B.ByteString
substr b l s = B.take l $ B.drop b s


module Main where

main = do
  x <- readLn :: IO Integer
  print $ solve x

solve :: Integer -> Integer
solve x
  | x `mod` 11 == 0 = (x `div` 11) * 2
  | x `mod` 11 < 6 = (x `div` 11) * 2 + 1
  | otherwise = (x `div` 11) * 2 + 2


import Control.Monad
main = readLn >>= print . solve

solve :: Int -> Int
solve x = r * 2 + r'
    where
        (r, m) = x `divMod` 11
        r'
            | m == 0 = 0
            | m > 6 = 2
            | otherwise = 1


main:: IO ()
main = do
  nc<-getLine
  let n = read nc ::Integer
  print (solver n)

solver::Integer -> Integer
solver x = let turn_56 = (div x 11)*2 in
           let rest    =  mod x 11    in
           if x == 0 then 0 else (turn_56 + if rest <= 6 then 1 else 2)


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

main = do
  n <- readLn :: IO Int
  a <- getIntListBC
  let a' = sum . map (\x -> (length x) - 1) . group . sort $ a
  if even a' then print $ n - a'
             else print $ n - a' - 1

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

getIntListBC :: IO [Int]
getIntListBC = map bsToInt . BC.words <$> BC.getLine

Score : 400 points

Problem Statement

Snuke has decided to play a game using cards.
He has a deck consisting of N cards. On the i-th card from the top, an integer A_i is written.

He will perform the operation described below zero or more times, so that the values written on the remaining cards will be pairwise distinct. Find the maximum possible number of remaining cards. Here, N is odd, which guarantees that at least one card can be kept.

Operation: Take out three arbitrary cards from the deck. Among those three cards, eat two: one with the largest value, and another with the smallest value. Then, return the remaining one card to the deck.

Constraints

3 ≦ N ≦ 10^{5}

N is odd.

1 ≦ A_i ≦ 10^{5}

A_i is an integer.

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 A_3 ... A_{N}

Output

Print the answer.

Sample Input 1

5
1 2 1 3 7

Sample Output 1

3

One optimal solution is to perform the operation once, taking out two cards with 1 and one card with 2. One card with 1 and another with 2 will be eaten, and the remaining card with 1 will be returned to deck. Then, the values written on the remaining cards in the deck will be pairwise distinct: 1, 3 and 7.

Sample Input 2

15
1 3 5 2 1 3 2 8 8 6 2 6 11 1 1

Sample Output 2

7


import Data.Set (fromList)

main :: IO ()
main = do
    l1 <- getLine
    l2 <- getLine
    let n = read l1
    let as = (map read . words) l2 :: [Int]
    putStrLn $ solve n as

solve :: Int -> [Int] -> String
solve n as = show . countRemain $ (dup, uniq)
    where
        uniq = length $ fromList as
        dup = n - uniq

countRemain :: (Int, Int) -> Int
countRemain (dup, uniq)
    | dup `mod` 2 == 0  = uniq
    | otherwise         = uniq - 1


import Data.Array.IO
import Data.IORef
import Data.Array
main::IO()
main = do
  _<-getLine
  dc<-getLine
  let dat =map read (words dc)::[Int]
  ar<-newArray (1,100000) 0
  ar_pt<- newIORef ar
  make_histgram ar_pt dat
  i_ar<-freeze ar
  let hist_ls = elems i_ar
  print (solver hist_ls)

make_histgram::IORef (IOArray Int Int) -> [Int] -> IO()
make_histgram ar_pt [] = return ()
make_histgram ar_pt (x:xs) = do
                          ar<- readIORef ar_pt
                          v<-readArray ar x
                          writeArray ar x (v+1)
                          make_histgram ar_pt xs

solver::[Int]->Int
solver ls = let non_zero = filter (\x-> x/=0) ls in
            let ev_length = length (filter (\x-> mod x 2 ==0 ) non_zero) in
            let od_length = length (filter (\x-> mod x 2 /=0 ) non_zero) in
            od_length+ev_length+ (if mod ev_length 2 == 0 then 0 else (-1))


--{-# LANGUAGE BangPatterns #-}
--{-# LANGUAGE ScopedTypeVariables #-}
--{-# LANGUAGE FlexibleContexts #-}
--{-# LANGUAGE ViewPatterns #-}
--{-# LANGUAGE OverloadedStrings #-}

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

--------------------------------------------------------------------------
step acc (a,b) = acc'
    where
        a' = a + acc
        m = a' `mod` b
        need = if m == 0 then 0 else b - m
        acc' =  acc + need

main = do
    n <- int
    xys <- reverse <$> mLinesToTupleL n
    print $ foldl' step 0 xys
--------------------------------------------------------------------------

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

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

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

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

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

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

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

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

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

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

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

sLineToDoubleL :: IO [Double]
sLineToDoubleL = fromSLineL bsToDouble

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Score : 300 points

Problem Statement

There are an integer sequence A_1,...,A_N consisting of N terms, and N buttons.
When the i-th (1 ≦ i ≦ N) button is pressed, the values of the i terms from the first through the i-th are all incremented by 1.

There is also another integer sequence B_1,...,B_N. Takahashi will push the buttons some number of times so that for every i, A_i will be a multiple of B_i.

Find the minimum number of times Takahashi will press the buttons.

Constraints

All input values are integers.

1 ≦ N ≦ 10^5

0 ≦ A_i ≦ 10^9(1 ≦ i ≦ N)

1 ≦ B_i ≦ 10^9(1 ≦ i ≦ N)

Input

The input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print an integer representing the minimum number of times Takahashi will press the buttons.

Sample Input 1

3
3 5
2 7
9 4

Sample Output 1

7

Press the first button twice, the second button twice and the third button three times.

Sample Input 2

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

Sample Output 2

22


import Data.List
main = do
  getLine
  s <- getLine
  print $ solve s 0 0

solve :: String -> Int -> Int -> Int
solve []       _   max = max
solve ('I':as) now max
  | now + 1 > max = solve as (now + 1) (now + 1)
  | otherwise     = solve as (now + 1) max
solve ('D':as) now max = solve as (now - 1) max

Score : 200 points

Problem Statement

You have an integer variable x.
Initially, x=0.

Some person gave you a string S of length N, and using the string you performed the following operation N times.
In the i-th operation, you incremented the value of x by 1 if S_i=I, and decremented the value of x by 1 if S_i=D.

Find the maximum value taken by x during the operations (including before the first operation, and after the last operation).

Constraints

1≤N≤100

|S|=N

No characters except I and D occur in S.

Input

The input is given from Standard Input in the following format:

N
S

Output

Print the maximum value taken by x during the operations.

Sample Input 1

5
IIDID

Sample Output 1

2

After each operation, the value of x becomes 1, 2, 1, 2 and 1, respectively. Thus, the output should be 2, the maximum value.

Sample Input 2

7
DDIDDII

Sample Output 2

0

The initial value x=0 is the maximum value taken by x, thus the output should be 0.


factno n =
    length [ k | k <- [1..n], n `mod` k == 0 ]

main = do
  n <- readLn
  print . product $ map factno [1..n]

Score : 300 points

Problem Statement

You are given an integer N.
Find the number of the positive divisors of N!, modulo 10^9+7.

Constraints

1≤N≤10^3

Input

The input is given from Standard Input in the following format:

N

Output

Print the number of the positive divisors of N!, modulo 10^9+7.

Sample Input 1

3

Sample Output 1

4

There are four divisors of 3! =6: 1, 2, 3 and 6. Thus, the output should be 4.

Sample Input 2

6

Sample Output 2

30

Sample Input 3

1000

Sample Output 3

972926972


main = interact $ sol . fmap read . words

sol [sx,sy,tx,ty] = u y ++ r x ++ d y ++ l x ++
  l 1 ++ u (y+1)  ++ r (x+1) ++ d 1 ++ r 1 ++ d (y+1) ++ l (x+1) ++ u 1
  where
  x = tx-sx
  y = ty-sy

u n = replicate n 'U'
d n = replicate n 'D'
l n = replicate n 'L'
r n = replicate n 'R'

Score : 300 points

Problem Statement

Dolphin resides in two-dimensional Cartesian plane, with the positive x-axis pointing right and the positive y-axis pointing up.

Currently, he is located at the point (sx,sy). In each second, he can move up, down, left or right by a distance of 1.

Here, both the x- and y-coordinates before and after each movement must be integers.

He will first visit the point (tx,ty) where sx < tx and sy < ty, then go back to the point (sx,sy), then visit the point (tx,ty) again, and lastly go back to the point (sx,sy).

Here, during the whole travel, he is not allowed to pass through the same point more than once, except the points (sx,sy) and (tx,ty).

Under this condition, find a shortest path for him.

Constraints

-1000 ≤ sx < tx ≤ 1000

-1000 ≤ sy < ty ≤ 1000

sx,sy,tx and ty are integers.

Input

The input is given from Standard Input in the following format:

sx sy tx ty

Output

Print a string S that represents a shortest path for Dolphin.

The i-th character in S should correspond to his i-th movement.

The directions of the movements should be indicated by the following characters:

U: Up

D: Down

L: Left

R: Right

If there exist multiple shortest paths under the condition, print any of them.

Sample Input 1

0 0 1 2

Sample Output 1

UURDDLLUUURRDRDDDLLU

One possible shortest path is:

Going from (sx,sy) to (tx,ty) for the first time: (0,0) → (0,1) → (0,2) → (1,2)

Going from (tx,ty) to (sx,sy) for the first time: (1,2) → (1,1) → (1,0) → (0,0)

Going from (sx,sy) to (tx,ty) for the second time: (0,0) → (-1,0) → (-1,1) → (-1,2) → (-1,3) → (0,3) → (1,3) → (1,2)

Going from (tx,ty) to (sx,sy) for the second time: (1,2) → (2,2) → (2,1) → (2,0) → (2,-1) → (1,-1) → (0,-1) → (0,0)

Sample Input 2

-2 -2 1 1

Sample Output 2

UURRURRDDDLLDLLULUUURRURRDDDLLDL


main = do
 [sx,sy,tx,ty]<-map read. words <$> getLine
 let dx = tx-sx
 let dy = ty-sy
 let l1 = "L"++ (replicate (dy + 1) 'U') ++ (replicate (dx + 1) 'R') ++ "D"
 let l2 = (replicate dx 'L') ++ (replicate dy 'L')
 let l3 = (replicate dx 'R') ++ (replicate dy 'U')
 let l4 = "R" ++ (replicate (dy + 1 ) 'D') ++ (replicate (dx + 1) 'L') ++ "U"
 putStrLn (l1 ++ l2 ++ l3 ++ l4)


{-# LANGUAGE OverloadedStrings #-}
import Data.Maybe
import Data.Char
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.Vector.Unboxed as VU

main :: IO()
main = do
  [sx, sy, tx, ty] <- getIntList
  let (x, y) = (tx - sx, ty- sy)
  putStrLn . concat $ zipWith replicate [x, y+1, x+1, y+1, 1, 1, x+1, y+1, x+1, y] ['R', 'U', 'L', 'D', 'R', 'D', 'R', 'U', 'L', 'D']

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

getInt :: IO Int
getInt = readInt <$> BS.getLine

getIntList :: IO [Int]
getIntList = unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine

getIntVec :: Int -> IO (VU.Vector Int)
getIntVec n = VU.unfoldrN n (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine


n_char::Char -> Int -> String
n_char c 0=[]
n_char c n=c:(n_char c (n-1))

type Coord = (Int,Int)

forth_1:: Coord -> Coord -> String
forth_1 (s_x,s_y) (t_x,t_y) = (n_char 'U' (t_y-s_y))++(n_char 'R' (t_x-s_x))

back_1:: Coord -> Coord -> String
back_1 (s_x,s_y) (t_x,t_y) = (n_char 'D' (t_y-s_y))++(n_char 'L' (t_x-s_x))

forth_2:: Coord -> Coord -> String
forth_2 (s_x,s_y) (t_x,t_y) = "L"++(n_char 'U' ((t_y-s_y)+1))++(n_char 'R' ((t_x-s_x)+1))++"D"

back_2:: Coord -> Coord -> String
back_2 (s_x,s_y) (t_x,t_y) = "R"++(n_char 'D' ((t_y-s_y)+1))++(n_char 'L' ((t_x-s_x)+1))++"U"

solver::Coord->Coord->String
solver s t = (forth_1 s t)++(back_1 s t)++(forth_2 s t)++ (back_2 s t)

main::IO()
main = do
  d<-getLine
  let s_x:s_y:t_x:t_y:[]= map read (words d) ::[Int]
  putStr (solver (s_x,s_y) (t_x,t_y))
  putStr "\n"


import Data.Graph.Inductive
import Control.Monad
import Data.List(foldl')
import qualified Data.List as L
import Data.Set
import qualified Data.Set as S

main = do
    [n_, m_] <- return . L.map read . words =<< getLine
    let readEdge = do
	    [a,b,c] <- return . L.map read . words =<< getLine
	    return (a,b,c)
    edges <- replicateM m_ readEdge
    let nodes = L.map (\i->(i,())) [1..n_]
	gr = mkGraph nodes edges	::Gr () Int
	edgeSet:: Set (Node,Node) -> LPath Int ->  Set (Node,Node)
	edgeSet set (LP []) = set
	edgeSet set (LP [node]) = set
	edgeSet set (LP ((nodeId1,_):(nodeId2,_):path)) =
	    edgeSet (insert (nodeId1,nodeId2) set) $ LP ((nodeId2,0::Int):path)
	rltree = msTree (undir gr)
	lastSet = L.foldl' edgeSet S.empty rltree
    print $ m_ - (size lastSet)

Score : 400 points

Problem Statement

You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.

The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.

Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).

A connected graph is a graph where there is a path between every pair of different vertices.

Find the number of the edges that are not contained in any shortest path between any pair of different vertices.

Constraints

2≤N≤100

N-1≤M≤min(N(N-1)/2,1000)

1≤a_i,b_i≤N

1≤c_i≤1000

c_i is an integer.

The given graph contains neither self-loops nor double edges.

The given graph is connected.

Input

The input is given from Standard Input in the following format:

N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M

Output

Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.

Sample Input 1

3 3
1 2 1
1 3 1
2 3 3

Sample Output 1

1

In the given graph, the shortest paths between all pairs of different vertices are as follows:

The shortest path from vertex 1 to vertex 2 is: vertex 1 → vertex 2, with the length of 1.

The shortest path from vertex 1 to vertex 3 is: vertex 1 → vertex 3, with the length of 1.

The shortest path from vertex 2 to vertex 1 is: vertex 2 → vertex 1, with the length of 1.

The shortest path from vertex 2 to vertex 3 is: vertex 2 → vertex 1 → vertex 3, with the length of 2.

The shortest path from vertex 3 to vertex 1 is: vertex 3 → vertex 1, with the length of 1.

The shortest path from vertex 3 to vertex 2 is: vertex 3 → vertex 1 → vertex 2, with the length of 2.

Thus, the only edge that is not contained in any shortest path, is the edge of length 3 connecting vertex 2 and vertex 3, hence the output should be 1.

Sample Input 2

3 2
1 2 1
2 3 1

Sample Output 2

0

Every edge is contained in some shortest path between some pair of different vertices.


import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class
import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)
import Text.Printf
import Debug.Trace
import Data.Array.IArray
import Data.Array.IO

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

inf = 1000000000

main = do
  [n,m] <- getInts
  dt <- newArray ((1,1),(n,n)) inf :: IO (IOArray (Int,Int) Int)
  es <- replicateM m getInts
  forM_ es $ \[a,b,c] -> do
    writeArray dt (a,b) c
    writeArray dt (b,a) c
  forM_ [1..n] $ \k ->
    forM_ [1..n] $ \i ->
      forM_ [1..n] $ \j -> do
        a <- readArray dt (i,k)
        b <- readArray dt (k,j)
        pv <- readArray dt (i,j)
        writeArray dt (i,j) (min pv (a+b))
  arr <- (flip filterM) es $ \[a,b,c] -> do
    v <- readArray dt (a,b)
    return $ v /= c
  print $ length arr


main=do
 [a,b]<-map read.words<$>getLine
 print$(+1)$minimum$map abs[a+b,b-a-1]

Score : 300 points

Problem Statement

Snuke has a calculator. It has a display and two buttons.

Initially, the display shows an integer x.
Snuke wants to change this value into another integer y, by pressing the following two buttons some number of times in arbitrary order:

Button A: When pressed, the value on the display is incremented by 1.

Button B: When pressed, the sign of the value on the display is reversed.

Find the minimum number of times Snuke needs to press the buttons to achieve his objective.
It can be shown that the objective is always achievable regardless of the values of the integers x and y.

Constraints

x and y are integers.

|x|, |y| ≤ 10^9

x and y are different.

Input

The input is given from Standard Input in the following format:

x y

Output

Print the minimum number of times Snuke needs to press the buttons to achieve his objective.

Sample Input 1

10 20

Sample Output 1

10

Press button A ten times.

Sample Input 2

10 -10

Sample Output 2

1

Press button B once.

Sample Input 3

-10 -20

Sample Output 3

12

Press the buttons as follows:

Press button B once.

Press button A ten times.

Press button B once.


main = do
 [as,op,bs]<-words <$> getLine
 let [a,b]= map read [as,bs]
 print $ if op=="+" then a+b else a-b

Score : 100 points

Problem Statement

Joisino wants to evaluate the formula "A op B".
Here, A and B are integers, and the binary operator op is either + or -.
Your task is to evaluate the formula instead of her.

Constraints

1≦A,B≦10^9

op is either + or -.

Input

The input is given from Standard Input in the following format:

A op B

Output

Evaluate the formula and print the result.

Sample Input 1

1 + 2

Sample Output 1

3

Since 1 + 2 = 3, the output should be 3.

Sample Input 2

5 - 7

Sample Output 2

-2


import Data.List

main :: IO ()
main =
	words <$> getLine >>=
		putStrLn.show.(\[a,op,b] -> if(op=="+")then(read a + read b)else(read a - read b))


import Control.Applicative

main :: IO ()
main = do
  [a,op,b] <- words <$> getLine
  print $ solve2 a op b

solve2 :: String -> String -> String -> Int
solve2 a op b
  | op == "+" = (read a :: Int) + (read b :: Int)
  | op == "-" = (read a :: Int) - (read b :: Int)


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

solve :: Num a => [Char] -> a -> a -> a
solve "+" = (+)
solve "-" = (-)


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

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

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

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

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

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

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

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

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

countIf f = length . filter f

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

safeHead [] = Nothing
safeHead (x:_) = Just x

--
--
--

main = do
    _ <- getLine
    ts <- getIs
    m <- getI
    drinks <- replicateM m getIs
    let originalSum = sum ts
        v = V.fromList ts
        eachSums = map (\[x, y] -> show $ originalSum - (v V.! (x - 1)) + y)  drinks
    forM eachSums putStrLn >> return ()

Score : 200 points

Problem Statement

Joisino is about to compete in the final round of a certain programming competition.
In this contest, there are N problems, numbered 1 through N.
Joisino knows that it takes her T_i seconds to solve problem i(1≦i≦N).

Also, there are M kinds of drinks offered to the contestants, numbered 1 through M.
If Joisino takes drink i(1≦i≦M), her brain will be stimulated and the time it takes for her to solve problem P_i will become X_i seconds.
It does not affect the time to solve the other problems.

A contestant is allowed to take exactly one of the drinks before the start of the contest.
For each drink, Joisino wants to know how many seconds it takes her to solve all the problems if she takes that drink.
Here, assume that the time it takes her to solve all the problems is equal to the sum of the time it takes for her to solve individual problems.
Your task is to write a program to calculate it instead of her.

Constraints

All input values are integers.

1≦N≦100

1≦T_i≦10^5

1≦M≦100

1≦P_i≦N

1≦X_i≦10^5

Input

The input is given from Standard Input in the following format:

N
T_1 T_2 ... T_N
M
P_1 X_1
P_2 X_2
:
P_M X_M

Output

For each drink, calculate how many seconds it takes Joisino to solve all the problems if she takes that drink, and print the results, one per line.

Sample Input 1

3
2 1 4
2
1 1
2 3

Sample Output 1

6
9

If Joisino takes drink 1, the time it takes her to solve each problem will be 1, 1 and 4 seconds, respectively, totaling 6 seconds.

If Joisino takes drink 2, the time it takes her to solve each problem will be 2, 3 and 4 seconds, respectively, totaling 9 seconds.

Sample Input 2

5
7 2 3 8 5
3
4 2
1 7
4 13

Sample Output 2

19
25
30


main :: IO ()
main = do
  n <- readLn :: IO Int
  ts <- map read . words <$> getLine
  m <- readLn :: IO Int
  pxs <- mapM readPX [1..m] :: IO [(Int, Int)]
  print pxs
  mapM (putStrLn . solve ts) pxs
  return ()
  where
    readPX _ = do
      [p, x] <- map read . words <$> getLine
      return (p,x)
    solve ts (p, x) =
      show $ foldl (add' (p, x)) (1, 0) ts
      where
        add' (p, x) (i, l) r =
          if p == i
          then (i+1, l + x)
          else (i+1, l + r)


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

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

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

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

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

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

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

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

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

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

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

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

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

yesNoUpper b | b         = putStrLn "YES"
             | otherwise = putStrLn "NO"

yesNo b | b         = putStrLn "Yes"
        | otherwise = putStrLn "No"

main = do
  c <- getLine
  let b =not (any ((\x->x/='a'&&x/='i'&&x/='u'&&x/='e'&&x/='o') . head) (group $ sort c)) in if b then putStrLn  "vowel" else putStrLn "consonant"

Score : 100 points

Problem Statement

Given a lowercase English letter c, determine whether it is a vowel. Here, there are five vowels in the English alphabet: a, e, i, o and u.

Constraints

c is a lowercase English letter.

Input

The input is given from Standard Input in the following format:

c

Output

If c is a vowel, print vowel. Otherwise, print consonant.

Sample Input 1

a

Sample Output 1

vowel

Since a is a vowel, print vowel.

Sample Input 2

z

Sample Output 2

consonant

Sample Input 3

s

Sample Output 3

consonant


main :: IO ()
main = do
  c <- head <$> getLine :: IO Char
  putStrLn $ if elem c "aeiou" then "vowel" else "consonant"


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

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

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

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

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

main = getChar >>= putStrLn . which "vowel" "consonant" . ( `elem` "aeiou" )


solve "a" = "vowel"
solve "i" = "vowel"
solve "u" = "vowel"
solve "e" = "vowel"
solve "o" = "vowel"
solve _ = "consonant"

main = do
  s <- getLine
  putStrLn $ solve s


main :: IO ()
main = getLine >> interact solve

solve :: String -> String
solve = unlines . dup . lines

dup :: [a] -> [a]
dup [] = []
dup (x:xs) = x : x : dup xs


main :: IO ()
main = putStrLn =<< map head . words <$> getLine

Score : 100 points

Problem Statement

Snuke is going to open a contest named "AtCoder s Contest".
Here, s is a string of length 1 or greater, where the first character is an uppercase English letter, and the second and subsequent characters are lowercase English letters.

Snuke has decided to abbreviate the name of the contest as "AxC".
Here, x is the uppercase English letter at the beginning of s.

Given the name of the contest, print the abbreviation of the name.

Constraints

The length of s is between 1 and 100, inclusive.

The first character in s is an uppercase English letter.

The second and subsequent characters in s are lowercase English letters.

Input

The input is given from Standard Input in the following format:

AtCoder s Contest

Output

Print the abbreviation of the name of the contest.

Sample Input 1

AtCoder Beginner Contest

Sample Output 1

ABC

The contest in which you are participating now.

Sample Input 2

AtCoder Snuke Contest

Sample Output 2

ASC

This contest does not actually exist.

Sample Input 3

AtCoder X Contest

Sample Output 3

AXC


main = putStrLn . map head . words =<< getLine


import Control.Monad
import Data.List
import Data.Bits
import Debug.Trace
import Data.Maybe
import qualified Data.ByteString.Char8 as C

main :: IO ()
main = do
  xs <- words <$> getLine
  putStrLn $ map head xs

-- 以下ライブラリ

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

readNInts :: Int -> IO [[Int]]
readNInts = flip replicateM readInts

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

readNIntegers :: Int -> IO [[Integer]]
readNIntegers = flip replicateM readIntegers

getNLns :: Int -> IO [String]
getNLns = flip replicateM getLine

toTup2 :: [[a]] -> [(a, a)]
toTup2 = map (\ys -> case ys of y : z : zs -> (y, z))

encIdx2 :: Int -> (Int, Int) -> Int
encIdx2 mx (y, x) = y * mx + x

decIdx2 :: Int -> Int -> (Int, Int)
decIdx2 mx idx = (idx `div` mx, idx `mod` mx)

encIdx3 :: (Int, Int) -> (Int, Int, Int) -> Int
encIdx3 (my, mx) (z, y, x) = z * my * mx + y * mx + x

decIdx3 :: (Int, Int) -> Int -> (Int, Int, Int)
decIdx3 (my, mx) idx = (z, y, x)
  where
    basez = my * mx
    z = idx `div` basez
    y = (idx `mod` basez) `div` mx
    x = idx `mod` mx

while :: Monad m => m Bool -> m () -> m ()
while cond body = do
  b <- cond
  when b $ do
    body
    while cond body


main = do
    [a, b, x] <- map read . words <$> getLine :: IO [Integer]
    let t = (b - a + 1) `divMod` x
    print $ fst t + if null [ e | e <- [a .. a + snd t], e `mod` x == 0 ]
        then 0
        else 1

Score : 200 points

Problem Statement

You are given nonnegative integers a and b (a ≤ b), and a positive integer x.
Among the integers between a and b, inclusive, how many are divisible by x?

Constraints

0 ≤ a ≤ b ≤ 10^{18}

1 ≤ x ≤ 10^{18}

Input

The input is given from Standard Input in the following format:

a b x

Output

Print the number of the integers between a and b, inclusive, that are divisible by x.

Sample Input 1

4 8 2

Sample Output 1

3

There are three integers between 4 and 8, inclusive, that are divisible by 2: 4, 6 and 8.

Sample Input 2

0 5 1

Sample Output 2

6

There are six integers between 0 and 5, inclusive, that are divisible by 1: 0, 1, 2, 3, 4 and 5.

Sample Input 3

9 9 2

Sample Output 3

0

There are no integer between 9 and 9, inclusive, that is divisible by 2.

Sample Input 4

1 1000000000000000000 3

Sample Output 4

333333333333333333

Watch out for integer overflows.


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

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

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

main :: IO ()
main = do
  [w,h,n] <- getParms
  xya     <- replicateM n getParms
  print $ area $ f w h xya

initialize
  :: Int -> Int -> ([Int],[Int])
initialize w h = ([0 .. w-1], [0 .. h-1])

cut :: ([Int],[Int]) -> [Int] -> ([Int], [Int])
cut (xs,ys) [x,y,a]
  | a == 1 = (xs1, ys)
  | a == 2 = (xs2, ys)
  | a == 3 = (xs,  ys3)
  | a == 4 = (xs,  ys4)
  where
    xs1 = dropWhile (< x) xs
    xs2 = takeWhile (< x) xs
    ys3 = dropWhile (< y) ys
    ys4 = takeWhile (< y) ys

f :: Int -> Int -> [[Int]] -> ([Int], [Int])
f w h = foldl cut (initialize w h)

area (xs,ys) = length xs * length ys

Score : 200 points

Problem Statement

There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white.

Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) point was (x_i, y_i).

Then, he created an integer sequence a of length N, and for each 1 ≦ i ≦ N, he painted some region within the rectangle black, as follows:

If a_i = 1, he painted the region satisfying x < x_i within the rectangle.

If a_i = 2, he painted the region satisfying x > x_i within the rectangle.

If a_i = 3, he painted the region satisfying y < y_i within the rectangle.

If a_i = 4, he painted the region satisfying y > y_i within the rectangle.

Find the area of the white region within the rectangle after he finished painting.

Constraints

1 ≦ W, H ≦ 100

1 ≦ N ≦ 100

0 ≦ x_i ≦ W (1 ≦ i ≦ N)

0 ≦ y_i ≦ H (1 ≦ i ≦ N)

W, H (21:32, added), x_i and y_i are integers.

a_i (1 ≦ i ≦ N) is 1, 2, 3 or 4.

Input

The input is given from Standard Input in the following format:

W H N
x_1 y_1 a_1
x_2 y_2 a_2
:
x_N y_N a_N

Output

Print the area of the white region within the rectangle after Snuke finished painting.

Sample Input 1

5 4 2
2 1 1
3 3 4

Sample Output 1

9

The figure below shows the rectangle before Snuke starts painting.

First, as (x_1, y_1) = (2, 1) and a_1 = 1, he paints the region satisfying x < 2 within the rectangle:

Then, as (x_2, y_2) = (3, 3) and a_2 = 4, he paints the region satisfying y > 3 within the rectangle:

Now, the area of the white region within the rectangle is 9.

Sample Input 2

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

Sample Output 2

0

It is possible that the whole region within the rectangle is painted black.

Sample Input 3

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

Sample Output 3

64


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

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

main = do
    getLine
    as <- getIntList
    let zs = zipWith (\r l -> (r-l,r)) rs (tail ls)
            where ls = scanl min 1000000001 as
                  rs = scanr max 0 as
    let m = maximum $ map fst zs
    let ans = length . group $ filter ((== m).fst) zs
    print ans

Score : 400 points

Problem Statement

There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples.

Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows:

Move: When at town i (i < N), move to town i + 1.

Merchandise: Buy or sell an arbitrary number of apples at the current town. Here, it is assumed that one apple can always be bought and sold for A_i yen (the currency of Japan) at town i (1 ≦ i ≦ N), where A_i are distinct integers. Also, you can assume that he has an infinite supply of money.

For some reason, there is a constraint on merchandising apple during the travel: the sum of the number of apples bought and the number of apples sold during the whole travel, must be at most T. (Note that a single apple can be counted in both.)

During the travel, Takahashi will perform actions so that the profit of the travel is maximized. Here, the profit of the travel is the amount of money that is gained by selling apples, minus the amount of money that is spent on buying apples. Note that we are not interested in apples in his possession at the end of the travel.

Aoki, a business rival of Takahashi, wants to trouble Takahashi by manipulating the market price of apples. Prior to the beginning of Takahashi's travel, Aoki can change A_i into another arbitrary non-negative integer A_i' for any town i, any number of times. The cost of performing this operation is |A_i - A_i'|. After performing this operation, different towns may have equal values of A_i.

Aoki's objective is to decrease Takahashi's expected profit by at least 1 yen. Find the minimum total cost to achieve it. You may assume that Takahashi's expected profit is initially at least 1 yen.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)

A_i are distinct.

2 ≦ T ≦ 10^9

In the initial state, Takahashi's expected profit is at least 1 yen.

Input

The input is given from Standard Input in the following format:

N T
A_1 A_2 ... A_N

Output

Print the minimum total cost to decrease Takahashi's expected profit by at least 1 yen.

Sample Input 1

3 2
100 50 200

Sample Output 1

1

In the initial state, Takahashi can achieve the maximum profit of 150 yen as follows:

Move from town 1 to town 2.

Buy one apple for 50 yen at town 2.

Move from town 2 to town 3.

Sell one apple for 200 yen at town 3.

If, for example, Aoki changes the price of an apple at town 2 from 50 yen to 51 yen, Takahashi will not be able to achieve the profit of 150 yen. The cost of performing this operation is 1, thus the answer is 1.

There are other ways to decrease Takahashi's expected profit, such as changing the price of an apple at town 3 from 200 yen to 199 yen.

Sample Input 2

5 8
50 30 40 10 20

Sample Output 2

2

Sample Input 3

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

Sample Output 3

2


import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)
import Text.Printf
import Debug.Trace
import qualified Data.Set as S

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

inf = 10000000000
solve n as = snd $ foldl f zero as
  where
    dr = snd $ foldl (\(mn,d) x -> (min mn x, max d (x-mn))) (inf,0) as
    zero = (S.empty, 0)
    f (s,a) x = (S.insert x s, a + if (x-dr) `S.member` s then 1 else 0)

main = do
  [n,t] <- getInts
  as <- getInts
  print $ solve n as


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

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

--------------------------------------------------------------------------
solve xs ys n i = and $ zipWith (==) (drop (n-i) xs) (take i ys)

main = do
    n <- int
    xs <- str
    ys <- str
    print $ 2*n - (maximum $ [i | i<-[0..n], solve xs ys n i])
--------------------------------------------------------------------------

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

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

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

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

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

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

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

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

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

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

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

sLineToDoubleL :: IO [Double]
sLineToDoubleL = fromSLineL bsToDouble

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Score : 200 points

Problem Statement

Snuke is interested in strings that satisfy the following conditions:

The length of the string is at least N.

The first N characters equal to the string s.

The last N characters equal to the string t.

Find the length of the shortest string that satisfies the conditions.

Constraints

1≤N≤100

The lengths of s and t are both N.

s and t consist of lowercase English letters.

Input

The input is given from Standard Input in the following format:

N
s
t

Output

Print the length of the shortest string that satisfies the conditions.

Sample Input 1

3
abc
cde

Sample Output 1

5

The shortest string is abcde.

Sample Input 2

1
a
z

Sample Output 2

2

The shortest string is az.

Sample Input 3

4
expr
expr

Sample Output 3

4

The shortest string is expr.


toStrList x = map return x::[String]
fil x = filter (\t -> t == "C" || t == "F") x
check :: String -> String
check str = if(take 2 str  == "CF")then  "Yes" else if length(str) == 1 then "No" else  check (drop 1 str)
main = do
        n <- getLine
        putStrLn ((check.concat.fil.toStrList) n)

Score : 100 points

Problem Statement

This contest is CODEFESTIVAL, which can be shortened to the string CF by deleting some characters.

Mr. Takahashi, full of curiosity, wondered if he could obtain CF from other strings in the same way.

You are given a string s consisting of uppercase English letters.
Determine whether the string CF can be obtained from the string s by deleting some characters.

Constraints

2 ≤ |s| ≤ 100

All characters in s are uppercase English letters (A-Z).

Input

The input is given from Standard Input in the following format:

s

Output

Print Yes if the string CF can be obtained from the string s by deleting some characters.
Otherwise print No.

Sample Input 1

CODEFESTIVAL

Sample Output 1

Yes

CF is obtained by deleting characters other than the first character C and the fifth character F.

Sample Input 2

FESTIVALCODE

Sample Output 2

No

FC can be obtained but CF cannot be obtained because you cannot change the order of the characters.

Sample Input 3

CF

Sample Output 3

Yes

It is also possible not to delete any characters.

Sample Input 4

FCF

Sample Output 4

Yes

CF is obtained by deleting the first character.


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

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

--------------------------------------------------------------------------
makePair xs acc
    | l == 1 = (acc+1, maximum xs)
    | l == 2 = makePair xs' acc
    | otherwise = makePair xs' (acc+1)
    where
        l = length $ filter (/=0) xs
        xs' = map (\x -> max 0 (x-1)) xs

solve xs
    | a >= b = 0
    | otherwise = b - a
    where
        -- a 隙間の数
        -- b 余った数
        (a,b) = makePair xs 0

main = do
    [k,t] <- sLineToIntL
    xs <- sLineToIntL
    print $
        if  |   t == 1 -> k - 1
            |   otherwise -> solve xs
--------------------------------------------------------------------------

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

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

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

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

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

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

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

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

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

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

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

sLineToDoubleL :: IO [Double]
sLineToDoubleL = fromSLineL bsToDouble

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Score : 200 points

Problem Statement

There are K pieces of cakes.
Mr. Takahashi would like to eat one cake per day, taking K days to eat them all.

There are T types of cake, and the number of the cakes of type i (1 ≤ i ≤ T) is a_i.

Eating the same type of cake two days in a row would be no fun,
so Mr. Takahashi would like to decide the order for eating cakes that minimizes the number of days on which he has to eat the same type of cake as the day before.

Compute the minimum number of days on which the same type of cake as the previous day will be eaten.

Constraints

1 ≤ K ≤ 10000

1 ≤ T ≤ 100

1 ≤ a_i ≤ 100

a_1 + a_2 + ... + a_T = K

Input

The input is given from Standard Input in the following format:

K T
a_1 a_2 ... a_T

Output

Print the minimum number of days on which the same type of cake as the previous day will be eaten.

Sample Input 1

7 3
3 2 2

Sample Output 1

0

For example, if Mr. Takahashi eats cakes in the order of 2, 1, 2, 3, 1, 3, 1, he can avoid eating the same type of cake as the previous day.

Sample Input 2

6 3
1 4 1

Sample Output 2

1

There are 6 cakes.
For example, if Mr. Takahashi eats cakes in the order of 2, 3, 2, 2, 1, 2, he has to eat the same type of cake (i.e., type 2) as the previous day only on the fourth day.
Since this is the minimum number, the answer is 1.

Sample Input 3

100 1
100

Sample Output 3

99

Since Mr. Takahashi has only one type of cake, he has no choice but to eat the same type of cake as the previous day from the second day and after.


main :: IO ()
main = do
  [k, t] <- map read . words <$> getLine
  a <- map read . words <$> getLine
  let
    m = maximum a
  print $ if m > (k+1) `div` 2
    then 2*m-k-1
    else 0


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE NumDecimals #-}
module Main (main) where
import Data.List
import Debug.Trace

getInt :: IO Integer
getInt = read <$> getLine

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

main :: IO ()
main = do
  n <- getInt
  ts <- getInts
  as <- getInts
  print $ solve n ts as
  return ()
solve :: Integer -> [Integer] -> [Integer] -> Integer
solve n ts as
  | n == 1 = 1
  | otherwise = prod' s12
  where
    s1 = determine ts
    s2 = reverse $ determine $ reverse as
    s12 = zipWith f s1 s2
      where
        f (a,False) (b,False)        = min a b
        f (a,True) (b,True) | a /= b = 0
        f _ _                        = 1

prod' :: [Integer] -> Integer
prod' = foldl f 1
  where
    f a b = a * b `mod` (1e9 + 7)

determine :: [Integer] -> [(Integer,Bool)]
determine xs = (head xs,True) : zip (tail xs) sublist
  where
    sublist = zipWith (/=) xs $ tail xs

Score : 400 points

Problem Statement

Mountaineers Mr. Takahashi and Mr. Aoki recently trekked across a certain famous mountain range.
The mountain range consists of N mountains, extending from west to east in a straight line as Mt. 1, Mt. 2, ..., Mt. N.
Mr. Takahashi traversed the range from the west and Mr. Aoki from the east.

The height of Mt. i is h_i, but they have forgotten the value of each h_i.
Instead, for each i (1 ≤ i ≤ N), they recorded the maximum height of the mountains climbed up to the time they reached the peak of Mt. i (including Mt. i).
Mr. Takahashi's record is T_i and Mr. Aoki's record is A_i.

We know that the height of each mountain h_i is a positive integer.
Compute the number of the possible sequences of the mountains' heights, modulo 10^9 + 7.

Note that the records may be incorrect and thus there may be no possible sequence of the mountains' heights.
In such a case, output 0.

Constraints

1 ≤ N ≤ 10^5

1 ≤ T_i ≤ 10^9

1 ≤ A_i ≤ 10^9

T_i ≤ T_{i+1} (1 ≤ i ≤ N - 1)

A_i ≥ A_{i+1} (1 ≤ i ≤ N - 1)

Input

The input is given from Standard Input in the following format:

N
T_1 T_2 ... T_N
A_1 A_2 ... A_N

Output

Print the number of possible sequences of the mountains' heights, modulo 10^9 + 7.

Sample Input 1

5
1 3 3 3 3
3 3 2 2 2

Sample Output 1

4

The possible sequences of the mountains' heights are:

1, 3, 2, 2, 2

1, 3, 2, 1, 2

1, 3, 1, 2, 2

1, 3, 1, 1, 2

for a total of four sequences.

Sample Input 2

5
1 1 1 2 2
3 2 1 1 1

Sample Output 2

0

The records are contradictory, since Mr. Takahashi recorded 2 as the highest peak after climbing all the mountains but Mr. Aoki recorded 3.

Sample Input 3

10
1 3776 3776 8848 8848 8848 8848 8848 8848 8848
8848 8848 8848 8848 8848 8848 8848 8848 3776 5

Sample Output 3

884111967

Don't forget to compute the number modulo 10^9 + 7.

Sample Input 4

1
17
17

Sample Output 4

1

Some mountain ranges consist of only one mountain.


{-# LANGUAGE NumDecimals #-}
module Main where
import Data.List
import Debug.Trace

getInt :: IO Integer
getInt = read <$> getLine

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

main :: IO ()
main = do
  n <- getInt
  ts <- getInts
  as <- getInts
  print $ solve ts as
  return ()
solve :: [Integer] -> [Integer] -> Integer
solve ts as = prod' s12
  where
    s1 = determine ts
    s2 = reverse $ determine $ reverse as
    s12 = zipWith f s1 s2
      where
        f (a,False) (b,False)        = min a b
        f (a,True) (b,True) | a /= b = 0
        f _ _                        = 1

prod' :: [Integer] -> Integer
prod' = foldl f 1
  where
    f a b = a * b `mod` (1e9 + 7)

determine :: [Integer] -> [(Integer,Bool)]
determine xs = (head xs,True) : zip (tail xs) sublist
  where
    sublist = zipWith (/=) xs $ tail xs


{-# LANGUAGE NumDecimals #-}
module Main where
import Data.List
import Debug.Trace

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

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

main :: IO ()
main = do
  n <- getInt
  ts <- getInts
  as <- getInts
  print $ solve ts as
  return ()
solve :: [Int] -> [Int] -> Int
solve ts as = prod' s12
  where
    s1 = determine ts
    s2 = reverse $ determine $ reverse as
    s12 = zipWith f s1 s2
      where
        f (Just a) (Just b) = min a b
        f _ _ = 1
prod' :: [Int] -> Int
prod' = foldl f 1
  where
    f a b = a * b `mod` (1e9 + 7)

determine :: [Int] -> [Maybe Int]
determine xs = Nothing : zipWith f sublist (tail xs)
  where
    sublist = map (>=0) . zipWith (-) xs $ tail xs
    f b x = if b
            then Just x
            else Nothing


import Data.List
main = getLine >>= print . length . group . sort . words

Score : 100 points

Problem Statement

AtCoDeer the deer recently bought three paint cans.
The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c.
Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.

Since he is forgetful, he might have bought more than one paint can in the same color.
Count the number of different kinds of colors of these paint cans and tell him.

Constraints

1≦a,b,c≦100

Input

The input is given from Standard Input in the following format:

a b c

Output

Print the number of different kinds of colors of the paint cans.

Sample Input 1

3 1 4

Sample Output 1

3

Three different colors: 1, 3, and 4.

Sample Input 2

3 3 33

Sample Output 2

2

Two different colors: 3 and 33.


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

Score : 200 points

Problem Statement

There are N balls placed in a row.
AtCoDeer the deer is painting each of these in one of the K colors of his paint cans.
For aesthetic reasons, any two adjacent balls must be painted in different colors.

Find the number of the possible ways to paint the balls.

Constraints

1≦N≦1000

2≦K≦1000

The correct answer is at most 2^{31}-1.

Input

The input is given from Standard Input in the following format:

N K

Output

Print the number of the possible ways to paint the balls.

Sample Input 1

2 2

Sample Output 1

2

We will denote the colors by 0 and 1. There are two possible ways: we can either paint the left ball in color 0 and the right ball in color 1, or paint the left in color 1 and the right in color 0.

Sample Input 2

1 10

Sample Output 2

10

Since there is only one ball, we can use any of the ten colors to paint it. Thus, the answer is ten.


import Data.List

main :: IO ()
main = do
  line <- getLine
  let [n, k] = fmap read $ words line :: [Int]
  print $ head $ drop (n - 1) $ iterate (* (k - 1)) k


{-# LANGUAGE BangPatterns #-}

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

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

readInts :: IO [Int]
readInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

solve :: [[Int]] -> Int
solve = go 0 0

go :: Int -> Int -> [[Int]] -> Int
go !n !m []          = n + m
go !n !m ([t,a]:tas) = go (t * k) (a * k) tas
    where
        k = head $ filter (\k' -> t * k' >= n && a * k' >= m) [1..]

Score : 300 points

Problem Statement

AtCoDeer the deer is seeing a quick report of election results on TV.
Two candidates are standing for the election: Takahashi and Aoki.
The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes.
AtCoDeer has checked the report N times, and when he checked it for the i-th (1≦i≦N) time, the ratio was T_i:A_i.
It is known that each candidate had at least one vote when he checked the report for the first time.

Find the minimum possible total number of votes obtained by the two candidates when he checked the report for the N-th time.
It can be assumed that the number of votes obtained by each candidate never decreases.

Constraints

1≦N≦1000

1≦T_i,A_i≦1000 (1≦i≦N)

T_i and A_i (1≦i≦N) are coprime.

It is guaranteed that the correct answer is at most 10^{18}.

Input

The input is given from Standard Input in the following format:

N
T_1 A_1
T_2 A_2
:
T_N A_N

Output

Print the minimum possible total number of votes obtained by Takahashi and Aoki when AtCoDeer checked the report for the N-th time.

Sample Input 1

3
2 3
1 1
3 2

Sample Output 1

10

When the numbers of votes obtained by the two candidates change as 2,3 → 3,3 → 6,4, the total number of votes at the end is 10, which is the minimum possible number.

Sample Input 2

4
1 1
1 1
1 5
1 100

Sample Output 2

101

It is possible that neither candidate obtained a vote between the moment when he checked the report, and the moment when he checked it for the next time.

Sample Input 3

5
3 10
48 17
31 199
231 23
3 2

Sample Output 3

6930


main :: IO ()
main = do
    s <- getLine
    let p = length . filter (== 'p') $ s
    let n = length s
    print $ div n 2 - p

Score : 300 points

Problem Statement

AtCoDeer the deer and his friend TopCoDeer is playing a game.
The game consists of N turns.
In each turn, each player plays one of the two gestures, Rock and Paper, as in Rock-paper-scissors, under the following condition:

(※) After each turn, (the number of times the player has played Paper)≦(the number of times the player has played Rock).

Each player's score is calculated by (the number of turns where the player wins) - (the number of turns where the player loses), where the outcome of each turn is determined by the rules of Rock-paper-scissors.

(For those who are not familiar with Rock-paper-scissors: If one player plays Rock and the other plays Paper, the latter player will win and the former player will lose. If both players play the same gesture, the round is a tie and neither player will win nor lose.)

With his supernatural power, AtCoDeer was able to foresee the gesture that TopCoDeer will play in each of the N turns, before the game starts.
Plan AtCoDeer's gesture in each turn to maximize AtCoDeer's score.

The gesture that TopCoDeer will play in each turn is given by a string s. If the i-th (1≦i≦N) character in s is g, TopCoDeer will play Rock in the i-th turn. Similarly, if the i-th (1≦i≦N) character of s in p, TopCoDeer will play Paper in the i-th turn.

Constraints

1≦N≦10^5

N=|s|

Each character in s is g or p.

The gestures represented by s satisfy the condition (※).

Input

The input is given from Standard Input in the following format:

s

Output

Print the AtCoDeer's maximum possible score.

Sample Input 1

gpg

Sample Output 1

0

Playing the same gesture as the opponent in each turn results in the score of 0, which is the maximum possible score.

Sample Input 2

ggppgggpgg

Sample Output 2

2

For example, consider playing gestures in the following order: Rock, Paper, Rock, Paper, Rock, Rock, Paper, Paper, Rock, Paper. This strategy earns three victories and suffers one defeat, resulting in the score of 2, which is the maximum possible score.


import Control.Monad
import Data.List

main = do
    n <- readLn :: IO Int
    ta <- replicateM n $ do
            [t,a] <- map read . words <$> getLine :: IO [Int]
            return (t,a)
    let f (x,y) (t,a) = (k*t, k*a)
            where k = max ((x-1) `div` t + 1) ((y-1) `div` a +　1)
    let (x, y) = foldl' f (1,1) ta
    print $ x + y


import Data.Bool  (bool)
import Data.Ratio

import Control.Monad

main :: IO ()
main = do
    n  <- read <$> getLine
    rs <- replicateM n getPair
    print $ solve rs

getPair = (\(x:y:_) -> (x, y)) . fmap read . words <$> getLine

solve :: [(Int, Int)] -> Int
solve = inner (1, 1)
  where
    inner (a, b)           []  = a + b
    inner (a, b) ((x, y) : rs)
      | a <= x && b <= y = inner (x, y) rs
      | a >  x && b <= y = go (a, b) (x, y) False rs
      | a <= x && b >  y = go (b, a) (y, x) True  rs
      | a % x > b % y    = go (a, b) (x, y) False rs
      | otherwise        = go (b, a) (y, x) True  rs

    go (p, _) (u, v) = inner . bool (n, m) (m, n)
      where
        q = p `div` u
        r = head [x | x <- [q, q + 1], u * x >= p]
        n = u * r
        m = v * r


main = do
  x <- getLine
  print . length . g (length x `div` 2) $ f x

f :: String -> String
f [] = []
f ('S':'T':xs) = f xs
f (x:xs) = x : f xs

g :: Int -> String -> String
g n xs
  | n == 0 = xs
  | length xs' < length xs = g (n - 1) xs'
  | otherwise = xs'
    where xs' = f xs

Score : 300 points

Problem Statement

We have a string X, which has an even number of characters. Half the characters are S, and the other half are T.

Takahashi, who hates the string ST, will perform the following operation 10^{10000} times:

Among the occurrences of ST in X as (contiguous) substrings, remove the leftmost one. If there is no occurrence, do nothing.

Find the eventual length of X.

Constraints

2 ≦ |X| ≦ 200,000

The length of X is even.

Half the characters in X are S, and the other half are T.

Partial Scores

In test cases worth 200 points, |X| ≦ 200.

Input

The input is given from Standard Input in the following format:

X

Output

Print the eventual length of X.

Sample Input 1

TSTTSS

Sample Output 1

4

In the 1-st operation, the 2-nd and 3-rd characters of TSTTSS are removed.
X becomes TTSS, and since it does not contain ST anymore, nothing is done in the remaining 10^{10000}-1 operations.
Thus, the answer is 4.

Sample Input 2

SSTTST

Sample Output 2

0

X will eventually become an empty string: SSTTST ⇒ STST ⇒ ST ⇒ ``.

Sample Input 3

TSSTTTSS

Sample Output 3

4

X will become: TSSTTTSS ⇒ TSTTSS ⇒ TTSS.


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

count :: Int -> Int -> Int
count n i = sum [ minimum [i, l, n-i+1, n-l+1] | l <- [1..n] ]

solve :: V.Vector Int -> Int
solve v = if V.null v then 0 else mv * count (V.length v) (m+1) + solve l + solve (V.tail r)
  where
    m = V.minIndex v
    mv = v V.! m
    (l, r) = V.splitAt m v

main :: IO ()
main = do
  getLine
  a <- V.fromList . map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine
  let n = V.length a
  print $ if a == V.fromList [1..n] || a == V.fromList [n, n-1..1]
    then n * (n+1) * (n+2) `div` 6
    else solve a

Score : 400 points

Problem Statement

One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend.

Find the following:

Constraints

1 ≦ N ≦ 200,000

(a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N).

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the answer.

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

Sample Input 1

3
2 1 3

Sample Output 1

9

Sample Input 2

4
1 3 2 4

Sample Output 2

19

Sample Input 3

8
5 4 8 1 2 6 7 3

Sample Output 3

85


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

count :: Int -> Int -> Int
count n i = sum [ minimum [i, l, n-i+1, n-l+1] | l <- [1..n] ]

solve :: V.Vector Int -> Int
solve v = if V.null v then 0 else mv * count (V.length v) (m+1) + solve l + solve (V.tail r)
  where
    m = V.minIndex v
    mv = v V.! m
    (l, r) = V.splitAt m v

main :: IO ()
main = do
  getLine
  a <- V.fromList . map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine
  print $ solve a


main :: IO ()
main = getLine >>= \s -> putStrLn $ (take 4 s) ++ " " ++ (drop 4 s)

Score : 100 points

Problem Statement

This contest is CODE FESTIVAL.
However, Mr. Takahashi always writes it CODEFESTIVAL, omitting the single space between CODE and FESTIVAL.

So he has decided to make a program that puts the single space he omitted.

You are given a string s with 12 letters.
Output the string putting a single space between the first 4 letters and last 8 letters in the string s.

Constraints

s contains exactly 12 letters.

All letters in s are uppercase English letters.

Input

The input is given from Standard Input in the following format:

s

Output

Print the string putting a single space between the first 4 letters and last 8 letters in the string s.
Put a line break at the end.

Sample Input 1

CODEFESTIVAL

Sample Output 1

CODE FESTIVAL

Putting a single space between the first 4 letters and last 8 letters in CODEFESTIVAL makes it CODE FESTIVAL.

Sample Input 2

POSTGRADUATE

Sample Output 2

POST GRADUATE

Sample Input 3

ABCDEFGHIJKL

Sample Output 3

ABCD EFGHIJKL


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

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

-- data OrdQ = Ascending | Descending

--------------------------------------------------------------------------
intToChar :: Int -> Char
intToChar i = chr (i `mod` 26 + ord 'a')

charToInt :: Char -> Int
charToInt c = ord c - ord 'a'

solve :: VU.Vector Int -> Int -> VU.Vector Char
solve xs k =
    runST $ do
        let l = VU.length xs
        m <- newSTRef k
        table <- VUM.replicate l '.' :: ST s (VUM.STVector s Char)
        forM_ [0 .. l - 1] $ \i -> do
            let x = xs VU.! i
                d = 26 - x
            r <- readSTRef m
            if | x == 0 -> VUM.write table i 'a'
               | r >= d -> VUM.write table i 'a' >> modifySTRef' m (\x -> x - d)
               | otherwise -> VUM.write table i $ intToChar x
        rest <- readSTRef m
        when (rest > 0) $ do
            v <- charToInt <$> VUM.read table (l - 1)
            VUM.write table (l - 1) (intToChar $ v + rest)
        VU.unsafeFreeze table

main = do
    xs <- VU.map charToInt . VU.fromList <$> str
    k <- int
    putStrLn $ VU.toList $ solve xs k
--------------------------------------------------------------------------

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

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

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

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

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

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

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

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

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

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

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

sLineToDoubleL :: IO [Double]
sLineToDoubleL = fromSLineL bsToDouble

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

m1 :: Int -> Int
m1 = subtract 1

toDouble :: Int -> Double
toDouble = fromIntegral

toInt :: Double -> Int
toInt = floor

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

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

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

Score : 400 points

Problem Statement

Mr. Takahashi has a string s consisting of lowercase English letters.
He repeats the following operation on s exactly K times.

Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of z is a.

For example, if you perform an operation for the second letter on aaz, aaz becomes abz.
If you then perform an operation for the third letter on abz, abz becomes aba.

Mr. Takahashi wants to have the lexicographically smallest string after performing exactly K operations on s.
Find the such string.

Constraints

1≤|s|≤10^5

All letters in s are lowercase English letters.

1≤K≤10^9

Input

The input is given from Standard Input in the following format:

s
K

Output

Print the lexicographically smallest string after performing exactly K operations on s.

Sample Input 1

xyz
4

Sample Output 1

aya

For example, you can perform the following operations: xyz, yyz, zyz, ayz, aya.

Sample Input 2

a
25

Sample Output 2

z

You have to perform exactly K operations.

Sample Input 3

codefestival
100

Sample Output 3

aaaafeaaivap


import Data.Array
alp = array ('a','z') (zip ['a'..'z'] (0:[25,24..1]))
main=do
 s<-getLine;k<-readLn
 putStrLn(f s k)
  where f [c] k = [([c..'z']++['a'..'z'])!!(mod k 26)]
        f (c:s) k = if (alp!c)<=k then ('a':(f s (k-(alp!c)))) else (c:(f s k))


import Data.Char

main :: IO ()
main = do
  s <- map (subtract (ord 'a').ord) <$> getLine
  k <- readLn
  putStrLn $ map (chr . (+(ord 'a'))) $ calc s k

m :: Int -> Int
m = (`mod`26)

calc :: [Int] -> Int -> [Int]
calc [x] i = [m $ x+i]
calc (x:xs) i = if x + i >= 26 then 0 : calc xs (i-(26-x)) else x:calc xs i


main :: IO ()
main = do
    a <- readLn
    b <- readLn
    h <- readLn
    print $ (a+b)*h `div` 2

Score : 100 points

Problem Statement

You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively.

An example of a trapezoid

Find the area of this trapezoid.

Constraints

1≦a≦100

1≦b≦100

1≦h≦100

All input values are integers.

h is even.

Input

The input is given from Standard Input in the following format:

a
b
h

Output

Print the area of the given trapezoid. It is guaranteed that the area is an integer.

Sample Input 1

3
4
2

Sample Output 1

7

When the lengths of the upper base, lower base, and height are 3, 4, and 2, respectively, the area of the trapezoid is (3+4)×2/2 = 7.

Sample Input 2

4
4
4

Sample Output 2

16

In this case, a parallelogram is given, which is also a trapezoid.


main :: IO ()
main = do
    a <- readLn :: IO Int
    b <- readLn :: IO Int
    h <- readLn :: IO Int
    print $ (a + b) * h `div` 2


{-# LANGUAGE ScopedTypeVariables #-}

import qualified Data.List as List

main :: IO ()
main = do
    [a, b, h] <- map read . words <$> getContents
    print $ (a + b) * h `div` 2


solve a b c t
    | t == 'a' && null a = "A"
    | t == 'b' && null b = "B"
    | t == 'c' && null c = "C"
    | t == 'a' = solve (tail a) b c (head a)
    | t == 'b' = solve a (tail b) c (head b)
    | t == 'c' = solve a b (tail c) (head c)

main = do
    a <- getLine
    b <- getLine
    c <- getLine
    putStrLn $ solve a b c (head a)

Score : 200 points

Problem Statement

Alice, Bob and Charlie are playing Card Game for Three, as below:

At first, each of the three players has a deck consisting of some number of cards. Each card has a letter a, b or c written on it. The orders of the cards in the decks cannot be rearranged.

The players take turns. Alice goes first.

If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says a, Alice takes the next turn.)

If the current player's deck is empty, the game ends and the current player wins the game.

You are given the initial decks of the players.
More specifically, you are given three strings S_A, S_B and S_C. The i-th (1≦i≦|S_A|) letter in S_A is the letter on the i-th card in Alice's initial deck. S_B and S_C describes Bob's and Charlie's initial decks in the same way.

Determine the winner of the game.

Constraints

1≦|S_A|≦100

1≦|S_B|≦100

1≦|S_C|≦100

Each letter in S_A, S_B, S_C is a, b or c.

Input

The input is given from Standard Input in the following format:

S_A
S_B
S_C

Output

If Alice will win, print A. If Bob will win, print B. If Charlie will win, print C.

Sample Input 1

aca
accc
ca

Sample Output 1

A

The game will progress as below:

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice discards the top card in her deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, a. Alice takes the next turn.

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice's deck is empty. The game ends and Alice wins the game.

Sample Input 2

abcb
aacb
bccc

Sample Output 2

C


import Control.Monad

main = do
    decks <- replicateM 3 getLine
    putStrLn $ game 'a' decks

type Turn = Char
type Deck = String
type Player = String

proceed :: Turn -> [Deck] -> (Turn, [Deck])
proceed 'a' [a, b, c] = (head a, [drop 1 a, b, c])
proceed 'b' [a, b, c] = (head b, [a, drop 1 b, c])
proceed 'c' [a, b, c] = (head c, [a, b, drop 1 c])

game :: Turn -> [Deck] -> Player
game 'a' ["", _, _] = "A"
game 'b' [_, "", _] = "B"
game 'c' [_, _, ""] = "C"
game turn decks = game $% proceed turn decks

($%) :: (a -> b -> c) -> (a, b) -> c
f $% t = f (fst t) (snd t)


import Control.Applicative
import Control.Monad
import Data.List
import Data.Char
import Data.Maybe

main :: IO ()
main = do
    -- 文字列の入力
    sa <- filter (`elem` ['a'..'c']) <$> getLine
    sb <- filter (`elem` ['a'..'c']) <$> getLine
    sc <- filter (`elem` ['a'..'c']) <$> getLine
    -- 出力
    putStrLn $ solve sa sb sc 'a'

solve :: String -> String -> String -> Char -> String
solve [] _ _ 'a' = "A"
solve _ [] _ 'b' = "B"
solve _ _ [] 'c' = "C"
solve (a:sa) sb sc 'a' = solve sa sb sc a
solve sa (b:sb) sc 'b' = solve sa sb sc b
solve sa sb (c:sc) 'c' = solve sa sb sc c