import Data.Char

winner _ [] _ _ = 'a'
winner _ _ [] _ = 'b'
winner _ _ _ [] = 'c'
winner n (a:as) (b:bs) (c:cs)
    | n == 'a' = winner a as (b:bs) (c:cs)
    | n == 'b' = winner a (a:as) bs (c:cs)
    | n == 'c' = winner a (a:as) (b:bs) cs

main = do
    sa <- getLine
    sb <- getLine
    sc <- getLine
    putStrLn [toUpper $ winner (head sa) sa sb sc]


import Control.Applicative
import Control.Monad
import Data.List
import Data.Char
import Data.Maybe
strToInt s = (read :: String -> Int) s
strToInteger s = (read :: String -> Integer) s
strToDouble s = (read :: String -> Double) s

main :: IO ()
main = do
    -- 文字列の入力
    s <- filter (`elem` ['0'..'9']) <$> getLine
    let ps = subsequences [1..(length s - 1)]
    -- 出力
    putStrLn . show $ solve s ps

solve :: String -> [[Int]] -> Integer
solve s = sum . map (sum . map read . mulSplit s)

mulSplit :: String -> [Int] -> [String]
mulSplit s [] = [s]
mulSplit s (i:ix) = (take i s) : (mulSplit (drop i s) (map (subtract i) ix))

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

Score : 300 points

Problem Statement

You are given a string S consisting of digits between 1 and 9, inclusive.
You can insert the letter + into some of the positions (possibly none) between two letters in this string.
Here, + must not occur consecutively after insertion.

All strings that can be obtained in this way can be evaluated as formulas.

Evaluate all possible formulas, and print the sum of the results.

Constraints

1 \leq |S| \leq 10

All letters in S are digits between 1 and 9, inclusive.

Input

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

S

Output

Print the sum of the evaluated value over all possible formulas.

Sample Input 1

125

Sample Output 1

176

There are 4 formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated,

125

1+25=26

12+5=17

1+2+5=8

Thus, the sum is 125+26+17+8=176.

Sample Input 2

9999999999

Sample Output 2

12656242944

Submitted source-code file size, in bytes.

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

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


{-# LANGUAGE OverloadedStrings #-}
module Main where

import Data.List
import Data.Bits
import Data.Char (digitToInt)
import Control.Monad
import Debug.Trace
import qualified Data.ByteString.Char8 as BC
import Data.Maybe (fromJust, fromMaybe)
import qualified Data.Map.Strict as M
import qualified Data.Vector.Unboxed as V
import qualified Data.Set as S

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

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

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

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

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

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

bitSearch :: Int -> [[Bool]]
bitSearch keta = each <$> [0..2^keta - 1] where
    each :: Int -> [Bool]
    each bits = (\d -> shift bits (negate d) .&. 1 == 1) <$>  [0..(keta - 1)]

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

fastPowerMod :: Int -> Int -> Int -> Int
fastPowerMod b 0 _ = 1
fastPowerMod b 1 modnum = b `mod` modnum
fastPowerMod b n modnum
            | even n = (fastPowerMod b (n `div` 2) modnum ^ 2) `mod` modnum
            | otherwise = (fastPowerMod b (n - 1) modnum * b) `mod` modnum

solve :: BC.ByteString -> Int
solve n = let
    numList = fmap digitToInt . BC.unpack $ n
    kanouseiList = bitSearch $ length numList - 1
    go kanousei = let
        (first:latter) = numList
        initial = (0, first)
        lst = zip kanousei latter
        inner (total, stack) (True, num) = (total + stack, num)
        inner (total, stack) (False, num) = (total, stack * 10 + num)
        (total, stack) = foldl' inner initial lst
        in
        total + stack
    in
    sum $ go <$> kanouseiList

main :: IO ()
main = do
    n <- BC.getLine
    print $ solve n


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

main :: IO ()
main = do
  [n, x] <- map read . words <$> getLine
  a <- map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine
  let
    solve [] (_, i) = (0, i)
    solve (y:ys) (s, i) =
      let
        (next, j) = if s + x * (i+1) < y then (s, i+1) else (y, i)
      in (\x1 (x2, y2) -> (x1 + x2, y2)) next $ solve ys (next, j)
    ans = flip map [1..n] $ \i -> let
        (l, r) = splitAt i a
        (v, j) = solve (r++l) (10^9+1, 0)
      in v + x * j
  print $ minimum ans

Score : 400 points

Problem Statement

Snuke lives in another world, where slimes are real creatures and kept by some people.
Slimes come in N colors. Those colors are conveniently numbered 1 through N.
Snuke currently has no slime. His objective is to have slimes of all the colors together.

Snuke can perform the following two actions:

Select a color i (1≤i≤N), such that he does not currently have a slime in color i, and catch a slime in color i. This action takes him a_i seconds.

Cast a spell, which changes the color of all the slimes that he currently has. The color of a slime in color i (1≤i≤N-1) will become color i+1, and the color of a slime in color N will become color 1. This action takes him x seconds.

Find the minimum time that Snuke needs to have slimes in all N colors.

Constraints

2≤N≤2,000

a_i are integers.

1≤a_i≤10^9

x is an integer.

1≤x≤10^9

Input

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

N x
a_1 a_2 ... a_N

Output

Find the minimum time that Snuke needs to have slimes in all N colors.

Sample Input 1

2 10
1 100

Sample Output 1

12

Snuke can act as follows:

Catch a slime in color 1. This takes 1 second.

Cast the spell. The color of the slime changes: 1 → 2. This takes 10 seconds.

Catch a slime in color 1. This takes 1 second.

Sample Input 2

3 10
100 1 100

Sample Output 2

23

Snuke can act as follows:

Catch a slime in color 2. This takes 1 second.

Cast the spell. The color of the slime changes: 2 → 3. This takes 10 seconds.

Catch a slime in color 2. This takes 1 second.

Cast the soell. The color of each slime changes: 3 → 1, 2 → 3. This takes 10 seconds.

Catch a slime in color 2. This takes 1 second.

Sample Input 3

4 10
1 2 3 4

Sample Output 3

10

Snuke can act as follows:

Catch a slime in color 1. This takes 1 second.

Catch a slime in color 2. This takes 2 seconds.

Catch a slime in color 3. This takes 3 seconds.

Catch a slime in color 4. This takes 4 seconds.


main = do
    [n,k,x,y] <- map read . lines <$> getContents
    print $ min n k * x + max (n - k) 0 * y

Score : 100 points

Problem Statement

There is a hotel with the following accommodation fee:

X yen (the currency of Japan) per night, for the first K nights

Y yen per night, for the (K+1)-th and subsequent nights

Tak is staying at this hotel for N consecutive nights.
Find his total accommodation fee.

Constraints

1 \leq N, K \leq 10000

1 \leq Y < X \leq 10000

N,\,K,\,X,\,Y are integers.

Input

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

N
K
X
Y

Output

Print Tak's total accommodation fee.

Sample Input 1

5
3
10000
9000

Sample Output 1

48000

The accommodation fee is as follows:

10000 yen for the 1-st night

10000 yen for the 2-nd night

10000 yen for the 3-rd night

9000 yen for the 4-th night

9000 yen for the 5-th night

Thus, the total is 48000 yen.

Sample Input 2

2
3
10000
9000

Sample Output 2

20000


import Control.Monad
main=do
 [a,b,c,d]<-map read<$>replicateM 4 getLine
 print$if a>b then b*c+(a-b)*d else a*c


import Data.List
f []=True
f (s:a)=if(mod(length s)2)==0 then f a else False
main=do
 s<-group.sort<$>getLine
 putStrLn$if f s then"Yes"else"No"

Score : 200 points

Problem Statement

Let w be a string consisting of lowercase letters.
We will call w beautiful if the following condition is satisfied:

Each lowercase letter of the English alphabet occurs even number of times in w.

You are given the string w. Determine if w is beautiful.

Constraints

1 \leq |w| \leq 100

w consists of lowercase letters (a-z).

Input

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

w

Output

Print Yes if w is beautiful. Print No otherwise.

Sample Input 1

abaccaba

Sample Output 1

Yes

a occurs four times, b occurs twice, c occurs twice and the other letters occur zero times.

Sample Input 2

hthth

Sample Output 2

No


ave :: (Real a) => [a] -> Double
ave s = (realToFrac $ sum s) / fromIntegral (length s)
f a s= ave s == a
main=do
 [nr,a]<-map read.words<$>getLine
 let nrr = show nr
 let n = read nrr :: Int
 xn<-map read.words<$>getLine
 let xs=[drop p(take q xn)|p<-[0..n],q<-[0..n],p<q]
 print$length$filter (f a) xs

Score : 300 points

Problem Statement

Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i.
He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A.
In how many ways can he make his selection?

Constraints

1 \leq N \leq 50

1 \leq A \leq 50

1 \leq x_i \leq 50

N,\,A,\,x_i are integers.

Partial Score

200 points will be awarded for passing the test set satisfying 1 \leq N \leq 16.

Input

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

N A
x_1 x_2 ... x_N

Output

Print the number of ways to select cards such that the average of the written integers is exactly A.

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

The following are the 5 ways to select cards such that the average is 8:

Select the 3-rd card.

Select the 1-st and 2-nd cards.

Select the 1-st and 4-th cards.

Select the 1-st, 2-nd and 3-rd cards.

Select the 1-st, 3-rd and 4-th cards.

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

33 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Sample Output 4

8589934591

The answer may not fit into a 32-bit integer.


-- AtCoder My Practice
-- author: Leonardone @ NEETSDKASU

-- 解説読後
-- http://arc060.contest.atcoder.jp/data/arc/060/editorial.pdf
-- s > n のときは -1 を入れないと TLEすることも

import qualified Data.List as L

main = print . solve . map read . lines =<< getContents

f b n
    | n < b     = n
    | otherwise = let (dv, md) = divMod n b in md + f b dv

solve [n, s]
    | n == s    = n + 1
    | s >  n    = -1
    | otherwise = ans where
        en = maximum . takeWhile (\i -> i * i <= n) $ [1 .. ]
        ans = case L.find ((==) s . snd) . map (\i -> (i, f i n)) $ [2 .. en] of
            Just (i, _) -> i
            Nothing -> if en > 0 then ans' else -1 where
                ans' = case L.find ((==) s . snd) . map (\i -> (i, f i n)) $ bs of
                    Just (j, _) -> j
                    Nothing -> -1
                bs = map ((+) 1 . fst) . filter ((==) 0 . snd) . map (divMod (n - s)) $ [ en - k | k <- [0 .. en - 1]]

Score : 500 points

Problem Statement

For integers b (b \geq 2) and n (n \geq 1), let the function f(b,n) be defined as follows:

f(b,n) = n, when n < b

f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when n \geq b

Here, {\rm floor}(n / b) denotes the largest integer not exceeding n / b,
and n \ {\rm mod} \ b denotes the remainder of n divided by b.

Less formally, f(b,n) is equal to the sum of the digits of n written in base b.
For example, the following hold:

f(10,\,87654)=8+7+6+5+4=30

f(100,\,87654)=8+76+54=138

You are given integers n and s.
Determine if there exists an integer b (b \geq 2) such that f(b,n)=s.
If the answer is positive, also find the smallest such b.

Constraints

1 \leq n \leq 10^{11}

1 \leq s \leq 10^{11}

n,\,s are integers.

Input

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

n
s

Output

If there exists an integer b (b \geq 2) such that f(b,n)=s, print the smallest such b.
If such b does not exist, print -1 instead.

Sample Input 1

87654
30

Sample Output 1

10

Sample Input 2

87654
138

Sample Output 2

100

Sample Input 3

87654
45678

Sample Output 3

-1

Sample Input 4

31415926535
1

Sample Output 4

31415926535

Sample Input 5

1
31415926535

Sample Output 5

-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.Vector.Algorithms.Merge as VAM
-- import qualified Data.Heap as HP
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.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

--------------------------------------------------------------------------
solve mp
    | cond1 && cond2 =  "Yes"
    | otherwise = "No"
    where
        cond1 = (n > 0 && s > 0) || (n == 0 && s == 0)
        cond2 = (e > 0 && w > 0) || (e == 0 && w == 0)
        Just e = MP.lookup 'E' mp
        Just w = MP.lookup 'W' mp
        Just n = MP.lookup 'N' mp
        Just s = MP.lookup 'S' mp

main = do
    mp <- foldl' (\m l -> MP.insertWith (+) l 1 m) (MP.fromList [('E',0),('W',0),('N',0),('S',0)]) <$> str
    putStrLn $ solve mp
--------------------------------------------------------------------------

-- Input Util
int :: IO Int
int = readLn

double :: IO Double
double = readLn

str :: IO String
str = getLine

strBC :: IO BC.ByteString
strBC = BC.getLine

sLineToIntL :: IO [Int]
sLineToIntL = getLine >>= return . map read . words

sLineToDoubleL :: IO [Double]
sLineToDoubleL = getLine >>= return . map read . words

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

sLineToDoubleV :: Int -> IO (VU.Vector Double)
sLineToDoubleV n = BC.getLine >>= return . VU.fromList . map (read . BC.unpack) . BC.words

mLinesToIntL :: Int -> IO [Int]
mLinesToIntL n = replicateM n readLn

mLinesToDoubleL :: Int -> IO [Double]
mLinesToDoubleL n = replicateM n readLn

mLinesToIntV :: Int -> IO (VU.Vector Int)
mLinesToIntV n = VU.replicateM n readLn

mLinesToDoubleV :: Int -> IO (VU.Vector Double)
mLinesToDoubleV n = VU.replicateM n (BC.getLine >>= return . read . BC.unpack)

mLinesToTupleL :: Int -> IO [(Int, Int)]
mLinesToTupleL n = replicateM n (getLine >>= return . (\[a,b] -> (a,b)) . map read . words)

mLinesToTupleV :: Int -> IO (VU.Vector (Int, Int))
mLinesToTupleV n = VU.replicateM n $ do
    bs <- strBC
    let
        Just (a, bs') = BC.readInt $ BC.dropWhile isSpace bs
        Just (b, _) = BC.readInt $ BC.dropWhile isSpace bs'
    return (a,b)

mLinesToTripleV :: Int -> IO (VU.Vector (Int, Int, Int))
mLinesToTripleV n = VU.replicateM n $ do
    bs <- strBC
    let
        Just (a, bs') = BC.readInt $ BC.dropWhile isSpace bs
        Just (b, bs'') = BC.readInt $ BC.dropWhile isSpace bs'
        Just (c, _) = BC.readInt $ BC.dropWhile isSpace bs''
    return (a,b,c)

-- 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 lives on an infinite two-dimensional plane. He is going on an N-day trip.
At the beginning of Day 1, he is at home. His plan is described in a string S of length N.
On Day i(1 ≦ i ≦ N), he will travel a positive distance in the following direction:

North if the i-th letter of S is N

West if the i-th letter of S is W

South if the i-th letter of S is S

East if the i-th letter of S is E

He has not decided each day's travel distance. Determine whether it is possible to set each day's travel distance so that he will be back at home at the end of Day N.

Constraints

1 ≦ | S | ≦ 1000

S consists of the letters N, W, S, E.

Input

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

S

Output

Print Yes if it is possible to set each day's travel distance so that he will be back at home at the end of Day N. Otherwise, print No.

Sample Input 1

SENW

Sample Output 1

Yes

If Snuke travels a distance of 1 on each day, he will be back at home at the end of day 4.

Sample Input 2

NSNNSNSN

Sample Output 2

Yes

Sample Input 3

NNEW

Sample Output 3

No

Sample Input 4

W

Sample Output 4

No


import Control.Monad
import Data.IntMap
import Data.List (sort)

main :: IO ()
main = do
  n <- readLn
  a <- replicateM n readLn
  let
    po = fromList $ zip a [1..]
    meu = fromList $ zip (sort a) [1..]
    solve [] = 0
    solve (x:xs) = if (po ! x + meu ! x) `mod` 2 == 0
      then solve xs
      else 1 + solve xs
  print $ sum meu + sum po

Score : 600 points

Problem Statement

Snuke got an integer sequence of length N from his mother, as a birthday present. The i-th (1 ≦ i ≦ N) element of the sequence is a_i. The elements are pairwise distinct.
He is sorting this sequence in increasing order.
With supernatural power, he can perform the following two operations on the sequence in any order:

Operation 1: choose 2 consecutive elements, then reverse the order of those elements.

Operation 2: choose 3 consecutive elements, then reverse the order of those elements.

Snuke likes Operation 2, but not Operation 1. Find the minimum number of Operation 1 that he has to perform in order to sort the sequence in increasing order.

Constraints

1 ≦ N ≦ 10^5

0 ≦ A_i ≦ 10^9

If i ≠ j, then A_i ≠ A_j.

All input values are integers.

Input

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

N
A_1
:
A_N

Output

Print the minimum number of times Operation 1 that Snuke has to perform.

Sample Input 1

4
2
4
3
1

Sample Output 1

1

The given sequence can be sorted as follows:

First, reverse the order of the last three elements. The sequence is now: 2,1,3,4.

Then, reverse the order of the first two elements. The sequence is now: 1,2,3,4.

In this sequence of operations, Operation 1 is performed once. It is not possible to sort the sequence with less number of Operation 1, thus the answer is 1.

Sample Input 2

5
10
8
5
3
2

Sample Output 2

0


import Data.Bifunctor (bimap, first, second)
import Data.Foldable  (and, or, product, sum)
import Data.Function
import Data.Monoid    ((<>))

import qualified Data.List as L

import Control.Applicative
import Control.Monad

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

type Answer = (Int, Int)
answer :: Answer -> IO ()
answer (a, b) = putStrLn $ show a ++ " " ++ show b

solve :: String -> Answer
solve s =
  let
    l       = L.length s
    substrs = s
        & L.init . L.tails
        & L.concatMap (L.tail . L.inits)
        & L.zip [(a, b) | a <- [1 .. l], b <- [a .. l]]
  in case L.map fst $ L.filter (unbalanced . snd) substrs of
    []      -> (-1, -1)
    range:_ -> range

unbalanced :: String -> Bool
unbalanced s =
  let
    nummode = L.maximum . L.map L.length . L.group $ L.sort s
    l       = L.length s
  in
    l >= 2 && l - nummode < nummode

Score : 400 points

Problem Statement

Given a string t, we will call it unbalanced if and only if the length of t is at least 2, and more than half of the letters in t are the same. For example, both voodoo and melee are unbalanced, while neither noon nor a is.

You are given a string s consisting of lowercase letters. Determine if there exists a (contiguous) substring of s that is unbalanced. If the answer is positive, show a position where such a substring occurs in s.

Constraints

2 ≦ |s| ≦ 10^5

s consists of lowercase letters.

Partial Score

200 points will be awarded for passing the test set satisfying 2 ≦ N ≦ 100.

Input

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

s

Output

If there exists no unbalanced substring of s, print -1 -1.

If there exists an unbalanced substring of s, let one such substring be s_a s_{a+1} ... s_{b} (1 ≦ a < b ≦ |s|), and print a b. If there exists more than one such substring, any of them will be accepted.

Sample Input 1

needed

Sample Output 1

2 5

The string s_2 s_3 s_4 s_5 = eede is unbalanced. There are also other unbalanced substrings. For example, the output 2 6 will also be accepted.

Sample Input 2

atcoder

Sample Output 2

-1 -1

The string atcoder contains no unbalanced substring.


{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Monoid
import Data.Array.Unboxed
import Data.Array.ST
import Data.Array.Base
import Data.Function(on)
import Data.Tuple(swap)
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

main :: IO ()
main = do
    (n,c) <- readIntPair
    as <- readInts
    bs <- readInts
    let arr :: Array (Int,Int) Modulo
        arr = runSTArray $ do
            vis <- newUArray ((0,0),(c,n)) False
            dp <- newArray ((0,0),(c,n)) 0
            let go v _ [] = if v == 0 then return 1 else return 0
                go v i (x:xs) = do
                    b <- readArray vis (v,i)
                    if b then
                        readArray dp (v,i)
                    else do
                        r <- fmap sum $ forM [0..v] $ \a -> do
                            r <- go (v - a) (i+1) xs
                            return $ (fromInteger (fromIntegral x))^a * r
                        writeArray vis (v,i) True
                        r `seq` thru (writeArray dp (v,i)) r
            go c 0 as
            return dp
    print $ arr ! (c,0)

modulo :: Int64
modulo = 1000000007

newtype Modulo = Modulo { getInteger :: Int64 } deriving(Eq,Ord)
instance Num Modulo where
    Modulo a + Modulo b = Modulo ((a+b) `mod` modulo)
    Modulo a - Modulo b = Modulo ((a-b) `mod` modulo)
    Modulo a * Modulo b = Modulo ((a*b) `mod` modulo)
    abs (Modulo a) = Modulo (abs a)
    signum (Modulo a) = Modulo (signum a)
    fromInteger i = Modulo (fromInteger i)
instance Fractional Modulo where
    recip (Modulo !a) = Modulo (modInv a)
    fromRational = undefined

instance Enum Modulo where
    toEnum x = fromIntegral x
    fromEnum x = fromIntegral $ getInteger x

instance Show Modulo where
    show (Modulo i) = show i

modInv i = (modulo + x `mod` modulo) `mod` modulo
    where
    (x,y) = go i modulo
    go !a 0 = (1,0)
    go !a b = let (!y,!x) = go b (a `mod` b) in (x,y - a `div` b * x)

-- IO
readInt :: B.ByteString -> Int
readInt = fromJust . fmap fst . B.readInt
readInts :: IO [Int]
readInts = map readInt . B.words <$> B.getLine
readIntPair :: IO (Int,Int)
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readAllInts :: IO [[Int]]
readAllInts = map (map readInt . B.words) . B.lines <$> B.getContents
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine

-- Utilities
l2p :: [a] -> (a,a)
l2p (a:b:_) = (a,b)
l2p _ = error "l2p: the input list is too short"
p2l :: (a,a) -> [a]
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
inf :: Int
inf = maxBound `div` 2

-- Monad
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i0 judge incr step = sub i0 where
    sub i | judge i = step i >> sub (incr i)
          | otherwise = return ()
rep_ :: Monad m => Int -> (Int -> m ()) -> m ()
rep_ n = stepM_ 0 (<n) (+1)
thru :: Monad m => (v -> m ()) -> v -> m v
thru m v = m v >> return v
memoize :: (Monad m) => (k -> m (Maybe v)) -> (k -> v -> m ()) -> k -> m v -> m v
memoize getter setter key action = do
    mv <- getter key
    case mv of
        Just v -> return v
        Nothing -> action >>= thru (setter key)

-- Array
newUArray :: (MArray (STUArray s) e (ST s),Ix i) =>
             (i,i) -> e -> ST s (STUArray s i e)
newUArray = newArray
newBArray :: (Ix i) => (i,i) -> e -> ST s (STArray s i e)
newBArray = newArray
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
fromEdges :: Ix i => (i,i) -> [(i,e)] -> Array i [e]
fromEdges = accumArray (flip (:)) []

Score : 800 points

Problem Statement

12:17 (UTC): The sample input 1 and 2 were swapped. The error is now fixed. We are very sorry for your inconvenience.

There are N children in AtCoder Kindergarten, conveniently numbered 1 through N. Mr. Evi will distribute C indistinguishable candies to the children.

If child i is given a candies, the child's happiness will become x_i^a, where x_i is the child's excitement level. The activity level of the kindergarten is the product of the happiness of all the N children.

For each possible way to distribute C candies to the children by giving zero or more candies to each child, calculate the activity level of the kindergarten. Then, calculate the sum over all possible way to distribute C candies. This sum can be seen as a function of the children's excitement levels x_1,..,x_N, thus we call it f(x_1,..,x_N).

You are given integers A_i,B_i (1≦i≦N). Find modulo 10^9+7.

Constraints

1≦N≦400

1≦C≦400

1≦A_i≦B_i≦400 (1≦i≦N)

Partial Score

400 points will be awarded for passing the test set satisfying A_i=B_i (1≦i≦N).

Input

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

N C
A_1 A_2 ... A_N
B_1 B_2 ... B_N

Output

Print the value of modulo 10^9+7.

Sample Input 1

2 3
1 1
1 1

Sample Output 1

4

This case is included in the test set for the partial score, since A_i=B_i.
We only have to consider the sum of the activity level of the kindergarten where the excitement level of both child 1 and child 2 are 1 (f(1,1)).

If child 1 is given 0 candy, and child 2 is given 3 candies, the activity level of the kindergarten is 1^0*1^3=1.

If child 1 is given 1 candy, and child 2 is given 2 candies, the activity level of the kindergarten is 1^1*1^2=1.

If child 1 is given 2 candies, and child 2 is given 1 candy, the activity level of the kindergarten is 1^2*1^1=1.

If child 1 is given 3 candies, and child 2 is given 0 candy, the activity level of the kindergarten is 1^3*1^0=1.

Thus, f(1,1)=1+1+1+1=4, and the sum over all f is also 4.

Sample Input 2

1 2
1
3

Sample Output 2

14

Since there is only one child, child 1's happiness itself will be the activity level of the kindergarten. Since the only possible way to distribute 2 candies is to give both candies to child 1, the activity level in this case will become the value of f.

When the excitement level of child 1 is 1, f(1)=1^2=1.

When the excitement level of child 1 is 2, f(2)=2^2=4.

When the excitement level of child 1 is 3, f(3)=3^2=9.

Thus, the answer is 1+4+9=14.

Sample Input 3

2 3
1 1
2 2

Sample Output 3

66

Since it can be seen that f(1,1)=4 , f(1,2)=15 , f(2,1)=15 , f(2,2)=32, the answer is 4+15+15+32=66.

Sample Input 4

4 8
3 1 4 1
3 1 4 1

Sample Output 4

421749

This case is included in the test set for the partial score.

Sample Input 5

3 100
7 6 5
9 9 9

Sample Output 5

139123417


import Control.Applicative

getInt :: IO Int
getInt = (\a -> read a :: Int) <$> getLine

getInteger :: IO Integer
getInteger = (\a -> read a :: Integer) <$> getLine

sum_all :: Integer -> Integer
sum_all n = n * (n + 1) `div` 2

main = do
    print =<< sum_all <$> getInteger

Score : 100 points

Problem Statement

There are N children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total?

Constraints

1≦N≦100

Input

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

N

Output

Print the necessary number of candies in total.

Sample Input 1

3

Sample Output 1

6

The answer is 1+2+3=6.

Sample Input 2

10

Sample Output 2

55

The sum of the integers from 1 to 10 is 55.

Sample Input 3

1

Sample Output 3

1

Only one child. The answer is 1 in this case.


main = getLine >>= putStrLn . foldl write ""

write :: String -> Char -> String
write "" 'B' = ""
write s 'B' = init s
write s c = s ++ [c]

Score : 200 points

Problem Statement

Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the 0 key, the 1 key and the backspace key.

To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this string is empty. When each key on the keyboard is pressed, the following changes occur to the string:

The 0 key: a letter 0 will be inserted to the right of the string.

The 1 key: a letter 1 will be inserted to the right of the string.

The backspace key: if the string is empty, nothing happens. Otherwise, the rightmost letter of the string is deleted.

Sig has launched the editor, and pressed these keys several times. You are given a string s, which is a record of his keystrokes in order. In this string, the letter 0 stands for the 0 key, the letter 1 stands for the 1 key and the letter B stands for the backspace key. What string is displayed in the editor now?

Constraints

1 ≦ |s| ≦ 10 (|s| denotes the length of s)

s consists of the letters 0, 1 and B.

The correct answer is not an empty string.

Input

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

s

Output

Print the string displayed in the editor in the end.

Sample Input 1

01B0

Sample Output 1

00

Each time the key is pressed, the string in the editor will change as follows: 0, 01, 0, 00.

Sample Input 2

0BB1

Sample Output 2

1

Each time the key is pressed, the string in the editor will change as follows: 0, (empty), (empty), 1.


module Main where

main = do
  s <- getLine
  putStrLn $ reverse $ foldl op [] s
  return ()

op str c
  | c == 'B' = if null str
               then str
               else tail str
  | otherwise = c:str


module Main where
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B8
import Data.Maybe (fromJust)

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

solve :: [Int] -> Int -> Int
solve as n = min (calcSum as (k `div` n)) (calcSum as (k `div` n + 1))
  where
    k = sum as

calcSum :: [Int] -> Int -> Int
calcSum xs n = sum $ map (\x -> (x - n)*(x-n)) xs

Score : 200 points

Problem Statement

Evi has N integers a_1,a_2,..,a_N. His objective is to have N equal integers by transforming some of them.

He may transform each integer at most once. Transforming an integer x into another integer y costs him (x-y)^2 dollars. Even if a_i=a_j (i≠j), he has to pay the cost separately for transforming each of them (See Sample 2).

Find the minimum total cost to achieve his objective.

Constraints

1≦N≦100

-100≦a_i≦100

Input

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

N
a_1 a_2 ... a_N

Output

Print the minimum total cost to achieve Evi's objective.

Sample Input 1

2
4 8

Sample Output 1

8

Transforming the both into 6s will cost (4-6)^2+(8-6)^2=8 dollars, which is the minimum.

Sample Input 2

3
1 1 3

Sample Output 2

3

Transforming the all into 2s will cost (1-2)^2+(1-2)^2+(3-2)^2=3 dollars. Note that Evi has to pay (1-2)^2 dollar separately for transforming each of the two 1s.

Sample Input 3

3
4 2 5

Sample Output 3

5

Leaving the 4 as it is and transforming the 2 and the 5 into 4s will achieve the total cost of (2-4)^2+(5-4)^2=5 dollars, which is the minimum.

Sample Input 4

4
-100 -100 -100 -100

Sample Output 4

0

Without transforming anything, Evi's objective is already achieved. Thus, the necessary cost is 0.


main :: IO ()
main = do
    (n, k) <- getPair :: IO (Pair Int)
    ds     <- filter (/= ' ') <$> getLine
    print $ solve n ds

type Pair a = (a, a)
getPair = (\(x:y:_) -> (x, y)) . map read . words <$> getLine :: Read a => IO (Pair a)

solve :: Int -> [Char] -> Int
solve n ds
  | all (`notElem` ds) $ show n = n
  | otherwise                   = solve (succ n) ds

Score : 300 points

Problem Statement

Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K.

She is shopping, and now paying at the cashier.
Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change).

However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money.

Find the amount of money that she will hand to the cashier.

Constraints

1 ≦ N < 10000

1 ≦ K < 10

0 ≦ D_1 < D_2 < … < D_K≦9

\{D_1,D_2,...,D_K\} ≠ \{1,2,3,4,5,6,7,8,9\}

Input

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

N K
D_1 D_2 … D_K

Output

Print the amount of money that Iroha will hand to the cashier.

Sample Input 1

1000 8
1 3 4 5 6 7 8 9

Sample Output 1

2000

She dislikes all digits except 0 and 2.

The smallest integer equal to or greater than N=1000 whose decimal notation contains only 0 and 2, is 2000.

Sample Input 2

9999 1
0

Sample Output 2

9999


import           Control.Monad
import           Control.Monad.ST
import qualified Data.Array                    as A
import qualified Data.Array.ST                 as ST
import qualified Data.Array.Unboxed            as AU
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import           Data.Int
import qualified Data.IntMap                   as IM
import           Data.List
import qualified Data.Map                      as M
import           Data.Maybe
import           Data.Ord
import qualified Data.Set                      as S
import           Data.Time
import qualified Data.Vector                   as V
import qualified Data.Vector.Mutable           as VM
import qualified Data.Vector.Unboxed           as VU
import qualified Data.Vector.Unboxed.Mutable   as VUM

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

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

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

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

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

main = do
    [n, k] <- readInt
    d      <- words <$> getLine
    let m = filter (\m-> all (\dd -> head dd `notElem` show m ) d ) [n, n+1 .. ] in print $ head m


import Data.List

f [] bs = []
f (a:as) bs =
    if elem a bs
    then a : f as bs
    else (head (filter (>a) bs)) : zipWith (\_ _ -> head bs) as [1..]

main :: IO ()
main = do
    [n, k] <- words <$> getLine
    ds <- concat . words <$> getLine
    putStrLn $ f n ("0123456789" \\ ds)


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

ds2int :: [Int] -> Int
ds2int = read . concatMap show

main :: IO ()
main = do
    [n, _] <- fmap read . words <$> getLine :: IO [Int]
    ds <- fmap read . words <$> getLine :: IO [Int]

    let cs = [0 .. 9] \\ ds
    let c  = head $ dropWhile (== 0) cs
    let a1 = c : replicate 4 0

    let cs' = concatMap show cs
    let f x = all (`elem` cs') (show x)
    let a2 = filter f [n .. 9999]

    if null a2
        then print $ ds2int a1
        else print $ head a2


import Data.Bits
import Data.List
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Generic as G

modulo :: Int
modulo = 1000000007

(+~) :: Int -> Int -> Int
a +~ b = (a + b) `mod` modulo

(*~) :: Int -> Int -> Int
a *~ b = (a * b) `mod` modulo

powMod :: Int -> Int -> Int
powMod a b = foldl' step 1 [63, 62 .. 0]
  where step x n = let pow2 = x *~ x in
                    if b `testBit` n then pow2 *~ a else pow2

invMod :: Int -> Int
invMod a = powMod (a `mod` modulo) (modulo - 2)

facts :: U.Vector Int
facts = 1 `G.cons` G.scanl1 (*~) (G.enumFromTo 1 200001)

factMod :: Int -> Int
factMod n = facts G.! n

combMod :: Int -> Int -> Int
combMod n r = factMod n *~ invMod (factMod r *~ factMod (n - r))

patterns :: Int -> Int -> Int
patterns h w = combMod (h + w) h

main :: IO ()
main = do
  [h, w, a, b] <- mapM readIO . words =<< getLine
  print $ foldl' (+~) 0 [ patterns row (b - 1) *~ patterns (h - row - 1) (w - b - 1)
                        | row <- [0 .. h - a - 1]
                        ]

Score : 400 points

Problem Statement

We have a large square grid with H rows and W columns.
Iroha is now standing in the top-left cell.
She will repeat going right or down to the adjacent cell, until she reaches the bottom-right cell.

However, she cannot enter the cells in the intersection of the bottom A rows and the leftmost B columns. (That is, there are A×B forbidden cells.) There is no restriction on entering the other cells.

Find the number of ways she can travel to the bottom-right cell.

Since this number can be extremely large, print the number modulo 10^9+7.

Constraints

1 ≦ H, W ≦ 100,000

1 ≦ A < H

1 ≦ B < W

Input

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

H W A B

Output

Print the number of ways she can travel to the bottom-right cell, modulo 10^9+7.

Sample Input 1

2 3 1 1

Sample Output 1

2

We have a 2×3 grid, but entering the bottom-left cell is forbidden. The number of ways to travel is two: "Right, Right, Down" and "Right, Down, Right".

Sample Input 2

10 7 3 4

Sample Output 2

3570

There are 12 forbidden cells.

Sample Input 3

100000 100000 99999 99999

Sample Output 3

1

Sample Input 4

100000 100000 44444 55555

Sample Output 4

738162020


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

type Table = IOUArray Int Int

modN :: Int
modN = 10^9+7

main = do
  [h,w,a,b] <- map read . words <$> getLine :: IO [Int]
  let h' = h - 1
      w' = w - 1
      a' = a - 1
      b' = b - 1
      n = h' + w'
  table <- newArray (0, n+1) 0 :: IO Table
  factTable <- newArray (0, n) 0 :: IO Table
  foldM factT factTable [0..n]
  makeTable table n n
  let path = [b..w']
  ans <- foldl1 (\x y -> flip mod modN $ x + y) <$> mapM (solve table factTable a' w' (h-a-1)) path
  print ans

solve :: Table -> Table -> Int -> Int -> Int -> Int -> IO Int
solve table factTable a w l i = do
  cn1 <- readArray factTable $ l+i
  cn2 <- readArray factTable $ a+w-i
  x <- comb table cn1 (l+i) i
  y <- comb table cn2 (a+w-i) a
  return $ flip mod modN $ x * y

factT :: Table -> Int -> IO Table
factT table 0 = do
  writeArray table 0 1
  return table
factT table n = do
  pre <- readArray table $ n-1
  writeArray table n $ flip mod modN $ pre * n
  return table

--x^n (mod modN)
(|^) :: Int -> Int -> Int
(|^) x n
  | n == 0    = 1
  | even n    = (mod (x * x) modN) |^ (n `div` 2)
  | otherwise = (flip mod modN) . (*x) $ x |^ (n - 1)

--x! (mod modN)
fact :: Int -> Int
fact n
  | n == 0    = 1
  | otherwise = (flip mod modN) . (*n) $ fact (n-1)

--nCk cn:n!
comb :: Table -> Int -> Int -> Int -> IO Int
comb memo cn n k
  |n >= k = do
    ik <- readArray memo k
    ink <- readArray memo $ n - k
    let tmp = flip mod modN $ cn * ik
        ans = flip mod modN $ tmp * ink
    return ans
  | otherwise = return 0

makeTable :: Table -> Int -> Int -> IO Table
makeTable table n (-1) = return table
makeTable table n i
  | n == i = do
    writeArray table i $ (fact n) |^ (10^9+5)
    makeTable table i $ i-1
  | otherwise = do
    ie <- readArray table (i+1)
    writeArray table i $ flip mod modN $ ie * (i+1)
    makeTable table i $ i-1


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

main :: IO ()
main = do
    n <- readLn :: IO Int
    ls <- fmap read . words <$> getLine :: IO [Int]
    let go [] = 0
        go (a:b:bs) = min a b + go bs
    print $ go (sort ls)

Score : 200 points

Problem Statement

Snuke is having a barbeque party.

At the party, he will make N servings of Skewer Meal.

Example of a serving of Skewer Meal

He has a stock of 2N skewers, all of which will be used in Skewer Meal. The length of the i-th skewer is L_i.
Also, he has an infinite supply of ingredients.

To make a serving of Skewer Meal, he picks 2 skewers and threads ingredients onto those skewers.
Let the length of the shorter skewer be x, then the serving can hold the maximum of x ingredients.

What is the maximum total number of ingredients that his N servings of Skewer Meal can hold, if he uses the skewers optimally?

Constraints

1≦N≦100

1≦L_i≦100

For each i, L_i is an integer.

Input

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

N
L_1 L_2 ... L_{2N}

Output

Print the maximum total number of ingredients that Snuke's N servings of Skewer Meal can hold.

Sample Input 1

2
1 3 1 2

Sample Output 1

3

If he makes a serving using the first and third skewers, and another using the second and fourth skewers, each serving will hold 1 and 2 ingredients, for the total of 3.

Sample Input 2

5
100 1 2 3 14 15 58 58 58 29

Sample Output 2

135


import Data.Bool
import Data.Char
import Data.List
import qualified Data.ByteString.Char8 as B
import qualified Data.Vector as V
main=print.solve.map(unfoldr$B.readInt.B.dropWhile isSpace).B.lines=<<B.getContents
solve([n,k]:ab)=if odd k then r1 else r2 where
  d=k`div`2
  es=map(\[a,b]->(a-1,b-1))ab
  g=V.accum(flip(:))(V.replicate n[])$concatMap(\(a,b)->[(a,b),(b,a)])es
  r1=minimum$map(\(a,b)->f 0 a b+f 0 b a)es
  r2=minimum$map(\i->f 0 i i)[0..n-1]
  f i p v=foldr(+)(bool 0 1(i>d)).map(f(i+1)v).filter(/=p)$g V.! v

Score : 600 points

Problem Statement

Given an undirected tree, let the distance between vertices u and v be the
number of edges on the simple path from u to v.
The diameter of a tree is the maximum among the distances between any two vertices.
We will call a tree good if and only if its diameter is at most K.

You are given an undirected tree with N vertices numbered 1 through N.
For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i.

You want to remove zero or more vertices from the tree, so that the resulting tree is good.
When a vertex is removed, all incident edges will also be removed.
The resulting graph must be connected.

Find the minimum number of vertices that you need to remove in order to produce a good tree.

Constraints

2≦N≦2000

1≦K≦N-1

1≦A_i≦N, 1≦B_i≦N

The graph defined by A_i and B_i is a tree.

Input

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

N K
A_1 B_1
A_2 B_2
:
A_{N-1} B_{N-1}

Output

Print the minimum number of vertices that you need to remove in order to produce a good tree.

Sample Input 1

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

Sample Output 1

2

The tree is shown below. Removing vertices 5 and 6 will result in a good tree with the diameter of 2.

Sample Input 2

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

Sample Output 2

0

Since the given tree is already good, you do not need to remove any vertex.