import Control.Monad

main :: IO ()
main = do
  _ <- getLine
  a <- reverse . map read . words <$> getLine
  let ans = foldl po (Just (2, 2)) a
  putStrLn $ case ans of
    Nothing       -> "-1"
    Just (mi, ma) -> unwords $ map show [mi, ma]

po :: Maybe (Int, Int) -> Int -> Maybe (Int, Int)
po range x = do
  (mi, ma) <- range
  guard $ ma >= x
  let
    nmi = if mi `mod` x == 0     then mi else mi + x - (mi `mod` x)
    nma = if ma `mod` x == x - 1 then ma else ma + x - (ma `mod` x) - 1
  return (nmi, nma)

Score : 500 points

Problem Statement

An adult game master and N children are playing a game on an ice rink.
The game consists of K rounds.
In the i-th round, the game master announces:

Form groups consisting of A_i children each!

Then the children who are still in the game form as many groups of A_i children as possible.
One child may belong to at most one group.
Those who are left without a group leave the game. The others proceed to the next round.
Note that it's possible that nobody leaves the game in some round.

In the end, after the K-th round, there are exactly two children left, and they are declared the winners.

You have heard the values of A_1, A_2, ..., A_K. You don't know N, but you want to estimate it.

Find the smallest and the largest possible number of children in the game before the start, or determine that no valid values of N exist.

Constraints

1 \leq K \leq 10^5

2 \leq A_i \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

K
A_1 A_2 ... A_K

Output

Print two integers representing the smallest and the largest possible value of N, respectively,
or a single integer -1 if the described situation is impossible.

Sample Input 1

4
3 4 3 2

Sample Output 1

6 8

For example, if the game starts with 6 children, then it proceeds as follows:

In the first round, 6 children form 2 groups of 3 children, and nobody leaves the game.

In the second round, 6 children form 1 group of 4 children, and 2 children leave the game.

In the third round, 4 children form 1 group of 3 children, and 1 child leaves the game.

In the fourth round, 3 children form 1 group of 2 children, and 1 child leaves the game.

The last 2 children are declared the winners.

Sample Input 2

5
3 4 100 3 2

Sample Output 2

-1

This situation is impossible.
In particular, if the game starts with less than 100 children, everyone leaves after the third round.

Sample Input 3

10
2 2 2 2 2 2 2 2 2 2

Sample Output 3

2 3


import qualified Data.ByteString.Char8 as BC
import qualified Data.Sequence as S
import qualified Data.IntMap as M
import Data.Maybe (fromJust)
import Data.List

main = do
  k <- readLn :: IO Int
  a <- map bsToInt . reverse . BC.words <$> BC.getLine
  let ans = solve a (2, 2)
  if ans == Nothing
    then print $ negate 1
    else let (l, r) = fromJust ans
         in putStrLn $ show l ++ " " ++ show r

solve :: [Int] -> (Int, Int) -> Maybe (Int, Int)
solve [] (l, r) = Just (l, r)
solve (a:as) (l, r) =
  let m = div l a
      n = div r a
      o = div (l-1) a
  in if n - o > 0
       then if mod l a == 0
              then solve as (a*m, a*(n+1)-1)
              else solve as (a*(m+1), a*(n+1)-1)
       else Nothing

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

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

Submitted source-code file size, in bytes.

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

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


import Control.Applicative

main :: IO ()
main = do
    s <- getLine
    putStrLn $ ("2018" ++ (drop 4 s))

Score : 100 points

Problem Statement

On some day in January 2018, Takaki is writing a document. The document has a column where the current date is written in yyyy/mm/dd format. For example, January 23, 2018 should be written as 2018/01/23.

After finishing the document, she noticed that she had mistakenly wrote 2017 at the beginning of the date column. Write a program that, when the string that Takaki wrote in the date column, S, is given as input, modifies the first four characters in S to 2018 and prints it.

Constraints

S is a string of length 10.

The first eight characters in S are 2017/01/.

The last two characters in S are digits and represent an integer between 1 and 31 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

Replace the first four characters in S with 2018 and print it.

Sample Input 1

2017/01/07

Sample Output 1

2018/01/07

Sample Input 2

2017/01/31

Sample Output 2

2018/01/31


main = do
    s <- getLine
    putStrLn $ "2018" ++ drop 4 s


module Main (main) where

import qualified Data.ByteString.Char8     as C8

main :: IO ()
main = do
  [s] <- readStrings
  print . showAnswer $ solve s

type Input  = (String)
type Output = String

solve :: Input -> Output
solve = ("2019" ++) . drop 4

showAnswer :: Output -> Answer
showAnswer = String

-- utils
readStrings :: IO [String]
readStrings = map C8.unpack . C8.words <$> C8.getLine

data Answer
  = YesNo Bool
  | YESNO Bool
  | AB Bool
  | Number Int
  | String String
  | Compare Ordering
  | Compare2 Ordering

instance Show Answer where
  show (YesNo b)   = if b then "Yes" else "No"
  show (YESNO b)   = if b then "YES" else "NO"
  show (AB b)      = if b then "A"   else "B"
  show (Number i)  = show i
  show (String s)  = s
  show (Compare o)
    | o == EQ = "="
    | o == LT = "<"
    | o == GT = ">"
  show (Compare2 o)
    | o == EQ = "Balanced"
    | o == LT = "Right"
    | o == GT = "Left"


main = do
  -- [n, y] <- map read . words <$> getLine :: IO [Int]
  s <- drop 4 <$> getLine
  putStrLn $ "2018"++s


main :: IO ()
main = putStr "2018" >> getLine >>= putStrLn . drop 4


import Control.Monad
import System.Random

main :: IO ()
main = do
    n <- fmap read getLine
    as <- (replicateM n (fmap read getLine)) :: IO [Int]
    putStrLn (show $ pirupiru as)

pirupiru :: [Int] -> Int
pirupiru ns =   if ns == [] then 0
                else 1 + pirupiru (deletesuru (maximum ns) ns)

deletesuru :: Int -> [Int] -> [Int]
deletesuru x xs = filter (/= x) xs

Score : 200 points

Problem Statement

An X-layered kagami mochi (X ≥ 1) is a pile of X round mochi (rice cake) stacked vertically where each mochi (except the bottom one) has a smaller diameter than that of the mochi directly below it. For example, if you stack three mochi with diameters of 10, 8 and 6 centimeters from bottom to top in this order, you have a 3-layered kagami mochi; if you put just one mochi, you have a 1-layered kagami mochi.

Lunlun the dachshund has N round mochi, and the diameter of the i-th mochi is d_i centimeters. When we make a kagami mochi using some or all of them, at most how many layers can our kagami mochi have?

Constraints

1 ≤ N ≤ 100

1 ≤ d_i ≤ 100

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
d_1
:
d_N

Output

Print the maximum number of layers in a kagami mochi that can be made.

Sample Input 1

4
10
8
8
6

Sample Output 1

3

If we stack the mochi with diameters of 10, 8 and 6 centimeters from bottom to top in this order, we have a 3-layered kagami mochi, which is the maximum number of layers.

Sample Input 2

3
15
15
15

Sample Output 2

1

When all the mochi have the same diameter, we can only have a 1-layered kagami mochi.

Sample Input 3

7
50
30
50
100
50
80
30

Sample Output 3

4


import Control.Applicative

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

solve :: Int -> Int
solve = (48 -)

Score : 100 points

Problem Statement

How many hours do we have until New Year at M o'clock (24-hour notation) on 30th, December?

Constraints

1≤M≤23

M is an integer.

Input

Input is given from Standard Input in the following format:

M

Output

If we have x hours until New Year at M o'clock on 30th, December, print x.

Sample Input 1

21

Sample Output 1

27

We have 27 hours until New Year at 21 o'clock on 30th, December.

Sample Input 2

12

Sample Output 2

36


main = do
  xs <- fmap (read :: String -> Int) . words <$> getLine
  putStrLn $ show $ 48 - (head xs)


module Main where

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

main :: IO ()
main = do
    [a, b] <- fmap read . words <$> getLine :: IO [Int]
    ss <- getLine
    let c1 = take a ss
    let c2 = head $ drop a ss
    let c3 = take b $ drop (a + 1) ss
    if and [ all isAlphaNum c1
           , c2 == '-'
           , all isAlphaNum c3
           ]
        then putStrLn "Yes"
        else putStrLn "No"

Score : 200 points

Problem Statement

The postal code in Atcoder Kingdom is A+B+1 characters long, its (A+1)-th character is a hyphen -, and the other characters are digits from 0 through 9.

You are given a string S. Determine whether it follows the postal code format in Atcoder Kingdom.

Constraints

1≤A,B≤5

|S|=A+B+1

S consists of - and digits from 0 through 9.

Input

Input is given from Standard Input in the following format:

A B
S

Output

Print Yes if S follows the postal code format in AtCoder Kingdom; print No otherwise.

Sample Input 1

3 4
269-6650

Sample Output 1

Yes

The (A+1)-th character of S is -, and the other characters are digits from 0 through 9, so it follows the format.

Sample Input 2

1 1
---

Sample Output 2

No

S contains unnecessary -s other than the (A+1)-th character, so it does not follow the format.

Sample Input 3

1 2
7444

Sample Output 3

No


import Data.Int
import Data.Array.IArray

solve :: Int -> Array Int (Int64,Int64,Int64) -> [Int64]
solve n a = map (go 0) [1..n]
  where
    go :: Int64 -> Int -> Int64
    go t i
      | i == n = t
      | t <= s = go (s+c) (i+1)
      | otherwise = let t' = if t `mod` f == 0
                               then t else t + f - (t `mod` f)
                     in go (t' + c) (i+1)
      where
        (c,s,f) = a!i

main :: IO ()
main = do
    n <- readLn :: IO Int
    a <- listArray (1,n-1) . map ((\[a,b,c] -> (a,b,c)) . (map read . words))
       . lines <$> getContents :: IO (Array Int (Int64,Int64,Int64))
    mapM_ print $ solve n a

Score : 300 points

Problem Statement

A railroad running from west to east in Atcoder Kingdom is now complete.

There are N stations on the railroad, numbered 1 through N from west to east.

Tomorrow, the opening ceremony of the railroad will take place.

On this railroad, for each integer i such that 1≤i≤N-1, there will be trains that run from Station i to Station i+1 in C_i seconds. No other trains will be operated.

The first train from Station i to Station i+1 will depart Station i S_i seconds after the ceremony begins. Thereafter, there will be a train that departs Station i every F_i seconds.

Here, it is guaranteed that F_i divides S_i.

That is, for each Time t satisfying S_i≤t and t％F_i=0, there will be a train that departs Station i t seconds after the ceremony begins and arrives at Station i+1 t+C_i seconds after the ceremony begins, where A％B denotes A modulo B, and there will be no other trains.

For each i, find the earliest possible time we can reach Station N if we are at Station i when the ceremony begins, ignoring the time needed to change trains.

Constraints

1≤N≤500

1≤C_i≤100

1≤S_i≤10^5

1≤F_i≤10

S_i％F_i=0

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
C_1 S_1 F_1
:
C_{N-1} S_{N-1} F_{N-1}

Output

Print N lines. Assuming that we are at Station i (1≤i≤N) when the ceremony begins, if the earliest possible time we can reach Station N is x seconds after the ceremony begins, the i-th line should contain x.

Sample Input 1

3
6 5 1
1 10 1

Sample Output 1

12
11
0

We will travel from Station 1 as follows:

5 seconds after the beginning: take the train to Station 2.

11 seconds: arrive at Station 2.

11 seconds: take the train to Station 3.

12 seconds: arrive at Station 3.

We will travel from Station 2 as follows:

10 seconds: take the train to Station 3.

11 seconds: arrive at Station 3.

Note that we should print 0 for Station 3.

Sample Input 2

4
12 24 6
52 16 4
99 2 2

Sample Output 2

187
167
101
0

Sample Input 3

4
12 13 1
44 17 17
66 4096 64

Sample Output 3

4162
4162
4162
0


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

isPrime :: Integral a => a -> Bool
isPrime n
  | n <= 2    = n == 2
  | otherwise = odd n && f 3
  where
    f i
      | i^2 > n   = True
      | otherwise = n `rem` i /= 0 && f (i+2)

primesArray :: Int -> Array Int Bool
primesArray n = listArray (0,n) $ map isPrime [0..n]

main :: IO ()
main = do
    _ <- getLine
    lr <- map ((\[a,b] -> (a,b))
        . map (fst . fromJust . BS.readInt) . BS.words) . BS.lines
        <$> BS.getContents :: IO [(Int,Int)]
    let m = 10^5
        p = primesArray m
        f n = p!n && p!((n+1) `div` 2)
        c = listArray (0,m)
                $ scanl (\a i -> if f i then a+1 else a)
                0 [1..m] :: Array Int Int
        solve l r = (c!r) - (c!(l-1))
    mapM_ (print . uncurry solve) lr

Score : 400 points

Problem Statement

We say that a odd number N is similar to 2017 when both N and (N+1)/2 are prime.

You are given Q queries.

In the i-th query, given two odd numbers l_i and r_i, find the number of odd numbers x similar to 2017 such that l_i ≤ x ≤ r_i.

Constraints

1≤Q≤10^5

1≤l_i≤r_i≤10^5

l_i and r_i are odd.

All input values are integers.

Input

Input is given from Standard Input in the following format:

Q
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line (1≤i≤Q) should contain the response to the i-th query.

Sample Input 1

1
3 7

Sample Output 1

2

3 is similar to 2017, since both 3 and (3+1)/2=2 are prime.

5 is similar to 2017, since both 5 and (5+1)/2=3 are prime.

7 is not similar to 2017, since (7+1)/2=4 is not prime, although 7 is prime.

Thus, the response to the first query should be 2.

Sample Input 2

4
13 13
7 11
7 11
2017 2017

Sample Output 2

1
0
0
1

Note that 2017 is also similar to 2017.

Sample Input 3

6
1 53
13 91
37 55
19 51
73 91
13 49

Sample Output 3

4
4
1
1
1
2


import Control.Monad
import Control.Monad.ST
import Data.List
import Control.Monad.Trans.State.Strict
import Data.Char (isSpace)
import Data.Maybe (fromJust)
import qualified Data.Vector.Unboxed as UV
import qualified Data.Vector.Unboxed.Mutable as MV

import qualified Data.ByteString.Char8 as B

type Parser a = StateT B.ByteString Maybe a

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

parseInt2 :: Parser (Int,Int)
parseInt2 = liftM2 (,) parseInt parseInt

parse :: Parser [(Int,Int)]
parse = do
    q<-parseInt
    replicateM q parseInt2

pr=2:q
q=3:5:7:3#q
m#(a:b:x)=[n|n<-[a^2,a^2+2..b^2-2],gcd n m<2]++(m*b)#(b:x)

prs = takeWhile (<=100000) pr

csum = UV.create $ do
    pv <- MV.replicate 100001 0:: ST s (MV.STVector s Int)
    sv <- MV.replicate 100001 0:: ST s (MV.STVector s Int)
    forM_ prs $ \p -> MV.write pv p 1
    forM_ prs $ \p -> do
        a <- MV.read pv ((p+1)`div`2)
        when (a == 1) $ MV.write sv p 1
    forM_ [1..100000] $ \i -> do
        si <- MV.read sv i
        si0 <- MV.read sv (i-1)
        MV.write sv i (si+si0)
    return sv

main = do
    lrs<- fromJust.evalStateT parse <$> B.getContents::IO[(Int,Int)]
    putStr $ unlines $ map (show.(\(l,r)-> (csum UV.! r) - (csum UV.! (l-1)))) lrs


import Control.Monad
import Data.IntSet as S hiding (foldl, map)
import Data.Map as M hiding (foldl, map)

count :: Int -> Int -> Int
count l r =
  like2017s!!r - like2017s!!l

like2017s :: [Int]
like2017s =
  scanl (+) 0 l
  where
    l = map (\x -> if elem x p && elem (div (x+1) 2) p then 1 else 0) [0,1..10^5]
    p = primes [2,3..10^5]

primes :: [Int] -> [Int]
primes = S.toList . (seive 2) . S.fromList

seive :: Int -> IntSet-> IntSet
seive p xs
  | p*p > S.findMax xs = xs
  | otherwise = seive (p+1) $! foldl (\acc x -> S.delete x acc) xs [2*p,3*p..q]
  where q = S.findMax xs

solve :: [(Int,Int)] -> [Int] -> [Int]
solve [] ac = ac
solve ((l,r):lrs) ac=
  solve lrs $! count l r : ac

main = do
  q <- read <$> getLine
  lrs <- replicateM q $ (\(x:y:[]) -> (read x,read y)) . words <$> getLine
  forM_ (reverse $ solve lrs []) $ print


import Control.Monad
import Data.Maybe
import Control.Monad.ST
import Data.List
import Data.Array
import Data.Array.ST
import qualified Data.ByteString.Char8 as B

main = do
  let a = buildSum (sieve 100000)
  q <- readLn
  forM_ [1..q] $ \_ -> do
    [l, r] <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
    print $ a!(r+1) - a!l

sieve :: Int -> Array Int Bool
sieve n = runST $ do
  a <- newArray (0, n) True :: ST s (STUArray s Int Bool)
  writeArray a 0 False
  writeArray a 1 False
  forM_ [2..n] $ \i -> do
    x <- readArray a i
    when x $ do
      forM_ [i*2, i*3 .. n] $ \j -> writeArray a j False
  freeze a

buildSum :: Array Int Bool -> Array Int Int
buildSum s = let n = length s - 1
             in listArray (0, n+1) . scanl (+) 0 . map (\i -> if s!i && s!((i+1)`div`2) then 1 else 0) $ [0..n]


{-# LANGUAGE ScopedTypeVariables, LambdaCase #-}

import qualified Data.List as List
import qualified Data.Set as Set

main :: IO ()
main = do
    [a, b, c, d] <- map read . words <$> getLine
    case compare (a + b) (c + d) of
        LT -> putStrLn "Right"
        GT -> putStrLn "Left"
        EQ -> putStrLn "Balanced"

Score : 100 points

Problem Statement

A balance scale tips to the left if L>R, where L is the total weight of the masses on the left pan and R is the total weight of the masses on the right pan. Similarly, it balances if L=R, and tips to the right if L<R.

Takahashi placed a mass of weight A and a mass of weight B on the left pan of a balance scale, and placed a mass of weight C and a mass of weight D on the right pan.

Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right.

Constraints

1\leq A,B,C,D \leq 10

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right.

Sample Input 1

3 8 7 1

Sample Output 1

Left

The total weight of the masses on the left pan is 11, and the total weight of the masses on the right pan is 8. Since 11>8, we should print Left.

Sample Input 2

3 4 5 2

Sample Output 2

Balanced

The total weight of the masses on the left pan is 7, and the total weight of the masses on the right pan is 7. Since 7=7, we should print Balanced.

Sample Input 3

1 7 6 4

Sample Output 3

Right

The total weight of the masses on the left pan is 8, and the total weight of the masses on the right pan is 10. Since 8<10, we should print Right.


main = do
  (a:b:c:d:_) <- getLine >>= return . map read . words :: IO [Int]
  putStrLn $ f (a+b) (c+d)
  where
    f x y
      | x < y = "Right"
      | x > y = "Left"
      | otherwise = "Balanced"


(|>) :: a -> (a -> b) -> b
infixl 1 |>
x |> f = f x

($>) :: (Functor m) => m a -> (a -> b) -> m b
infixl 1 $>
x $> f = fmap f x

getNums = getLine $> words $> map read

main = do
    x:y:_ <- getNums :: IO [Float]
    (y / x) |> logBase 2 |> floor |> (+1) |> print

Score : 300 points

Problem Statement

As a token of his gratitude, Takahashi has decided to give his mother an integer sequence.
The sequence A needs to satisfy the conditions below:

A consists of integers between X and Y (inclusive).

For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.

Find the maximum possible length of the sequence.

Constraints

1 \leq X \leq Y \leq 10^{18}

All input values are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the maximum possible length of the sequence.

Sample Input 1

3 20

Sample Output 1

3

The sequence 3,6,18 satisfies the conditions.

Sample Input 2

25 100

Sample Output 2

3

Sample Input 3

314159265 358979323846264338

Sample Output 3

31


main=do
 [x,y]<-map read.words<$>getLine
 print$f x y
f x y
 |x<=y=1+f(2*x)y
 |otherwise=0


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

Score : 100 points

Problem Statement

You are given two positive integers a and b.
Let x be the average of a and b.
Print x rounded up to the nearest integer.

Constraints

a and b are integers.

1 \leq a, b \leq 100

Input

Input is given from Standard Input in the following format:

a b

Output

Print x rounded up to the nearest integer.

Sample Input 1

1 3

Sample Output 1

2

The average of 1 and 3 is 2.0, and it will be rounded up to the nearest integer, 2.

Sample Input 2

7 4

Sample Output 2

6

The average of 7 and 4 is 5.5, and it will be rounded up to the nearest integer, 6.

Sample Input 3

5 5

Sample Output 3

5


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


main::IO()
main=do
  abc<-getLine
  let a:b:[]=map read (words abc)
  let (x,y)= divMod (a+b) 2
  print (x+y)


import Control.Monad(replicateM)
import Data.List(sort)
main = do
    [s1,s2] <- replicateM 2 getLine
    putStrLn $ f s1 s2
        where f s y = if sort s < reverse (sort y) then "Yes" else "No"

Score : 200 points

Problem Statement

You are given strings s and t, consisting of lowercase English letters.
You will create a string s' by freely rearranging the characters in s.
You will also create a string t' by freely rearranging the characters in t.
Determine whether it is possible to satisfy s' < t' for the lexicographic order.

Notes

For a string a = a_1 a_2 ... a_N of length N and a string b = b_1 b_2 ... b_M of length M, we say a < b for the lexicographic order if either one of the following two conditions holds true:

N < M and a_1 = b_1, a_2 = b_2, ..., a_N = b_N.

There exists i (1 \leq i \leq N, M) such that a_1 = b_1, a_2 = b_2, ..., a_{i - 1} = b_{i - 1} and a_i < b_i. Here, letters are compared using alphabetical order.

For example, xy < xya and atcoder < atlas.

Constraints

The lengths of s and t are between 1 and 100 (inclusive).

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If it is possible to satisfy s' < t', print Yes; if it is not, print No.

Sample Input 1

yx
axy

Sample Output 1

Yes

We can, for example, rearrange yx into xy and axy into yxa. Then, xy < yxa.

Sample Input 2

ratcode
atlas

Sample Output 2

Yes

We can, for example, rearrange ratcode into acdeort and atlas into tslaa. Then, acdeort < tslaa.

Sample Input 3

cd
abc

Sample Output 3

No

No matter how we rearrange cd and abc, we cannot achieve our objective.

Sample Input 4

w
ww

Sample Output 4

Yes

Sample Input 5

zzz
zzz

Sample Output 5

No


import Data.List

($>) :: (Functor m) => m a -> (a -> b) -> m b
infixl 1 $>
x $> f = fmap f x

main = do
  s <- getLine $> sort
  t <- getLine $> sort $> reverse
  putStrLn $ if s < t then "Yes" else "No"


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8 as BC
import           Data.List             (foldl')
import           Data.Maybe            (fromJust)

main :: IO ()
main = do
  s <- getLine
  [x, y] <- readInts
  putStrLn . showResult $ solve s x y

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

showResult True  = "Yes"
showResult False = "No"

solve :: String -> Int -> Int -> Bool
solve s x y = check dxs x && check (0:dys) y where
  (dxs, dys) = divide2 . map length $ splitOnT s

divide2 xs = (evens, odds) where
  xis   = xs `zip` [0 .. ]
  evens = [x | (x, i) <- xis, i `mod` 2 == 0]
  odds  = [x | (x, i) <- xis, i `mod` 2 == 1]

splitOnT :: String -> [String]
splitOnT = reverse . go [] [] where
  go acc1 acc2 []       = acc2 : acc1
  go acc1 acc2 ('T':xs) = go (acc2 : acc1) [] xs
  go acc1 acc2 (x:xs)   = go acc1 (x : acc2) xs

check :: [Int] -> Int -> Bool
check [] x = x == 0
check (d:ds) x = dp ! x where
  dp = foldl' folder dp0 ds
  dp0 = array (-s, s) $ (d, True) : [(i, False) | i <- [-s .. s], i /= d] :: UArray Int Bool

folder :: UArray Int Bool -> Int -> UArray Int Bool
folder bs d = array (-s, s) [(i, bs `at` (i - d) || bs `at` (i + d)) | i <- [-s .. s]]

s = 8001

at :: UArray Int Bool -> Int -> Bool
at bs i
  | i < -s = False
  | i > s  = False
  | otherwise = bs ! i

Score : 500 points

Problem Statement

A robot is put at the origin in a two-dimensional plane.
Initially, the robot is facing in the positive x-axis direction.

This robot will be given an instruction sequence s.
s consists of the following two kinds of letters, and will be executed in order from front to back.

F : Move in the current direction by distance 1.

T : Turn 90 degrees, either clockwise or counterclockwise.

The objective of the robot is to be at coordinates (x, y) after all the instructions are executed.
Determine whether this objective is achievable.

Constraints

s consists of F and T.

1 \leq |s| \leq 8 000

x and y are integers.

|x|, |y| \leq |s|

Input

Input is given from Standard Input in the following format:

s
x y

Output

If the objective is achievable, print Yes; if it is not, print No.

Sample Input 1

FTFFTFFF
4 2

Sample Output 1

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning clockwise in the second T.

Sample Input 2

FTFFTFFF
-2 -2

Sample Output 2

Yes

The objective can be achieved by, for example, turning clockwise in the first T and turning clockwise in the second T.

Sample Input 3

FF
1 0

Sample Output 3

No

Sample Input 4

TF
1 0

Sample Output 4

No

Sample Input 5

FFTTFF
0 0

Sample Output 5

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning counterclockwise in the second T.

Sample Input 6

TTTT
1 0

Sample Output 6

No


f :: Integer -> Integer
f x
  | even x = 1 + f (x `div` 2)
  | otherwise =  0

main :: IO()
main = do
  _ <- getLine
  a <- map read . words <$> getLine
  print $ minimum $ map f a

Score : 200 points

Problem Statement

There are N positive integers written on a blackboard: A_1, ..., A_N.

Snuke can perform the following operation when all integers on the blackboard are even:

Replace each integer X on the blackboard by X divided by 2.

Find the maximum possible number of operations that Snuke can perform.

Constraints

1 \leq N \leq 200

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible number of operations that Snuke can perform.

Sample Input 1

3
8 12 40

Sample Output 1

2

Initially, [8, 12, 40] are written on the blackboard.
Since all those integers are even, Snuke can perform the operation.

After the operation is performed once, [4, 6, 20] are written on the blackboard.
Since all those integers are again even, he can perform the operation.

After the operation is performed twice, [2, 3, 10] are written on the blackboard.
Now, there is an odd number 3 on the blackboard, so he cannot perform the operation any more.

Thus, Snuke can perform the operation at most twice.

Sample Input 2

4
5 6 8 10

Sample Output 2

0

Since there is an odd number 5 on the blackboard already in the beginning, Snuke cannot perform the operation at all.

Sample Input 3

6
382253568 723152896 37802240 379425024 404894720 471526144

Sample Output 3

8


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
import qualified Data.ByteString.Char8 as BC
import           Data.List             (unfoldr)
import           Data.Maybe            (fromJust)

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

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

solve :: Int -> [Int] -> Int
solve n as = length $ unfoldr unfolder as

unfolder :: [Int] -> Maybe ((), [Int])
unfolder as
  | all even as = Just ((), map (`div` 2) as)
  | otherwise = Nothing


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

main :: IO ()
main = do
    [_,k] <- map read . words <$> getLine :: IO [Int]
    a <- map (fst . fromJust . BS.readInt)
        . BS.words <$> BS.getLine :: IO [Int]
    let g = sortOn Down . map length . group . sort $ a
    print $ sum . drop k $ g

Score : 300 points

Problem Statement

Takahashi has N balls. Initially, an integer A_i is written on the i-th ball.

He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls.

Find the minimum number of balls that Takahashi needs to rewrite the integers on them.

Constraints

1 \leq K \leq N \leq 200000

1 \leq A_i \leq N

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of balls that Takahashi needs to rewrite the integers on them.

Sample Input 1

5 2
1 1 2 2 5

Sample Output 1

1

For example, if we rewrite the integer on the fifth ball to 2, there are two different integers written on the balls: 1 and 2.
On the other hand, it is not possible to rewrite the integers on zero balls so that there are at most two different integers written on the balls, so we should print 1.

Sample Input 2

4 4
1 1 2 2

Sample Output 2

0

Already in the beginning, there are two different integers written on the balls, so we do not need to rewrite anything.

Sample Input 3

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

Sample Output 3

3


import qualified Data.ByteString.Char8 as C
import Data.Maybe ( fromJust )
import Data.Char ( digitToInt )

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

main :: IO ()
main = do
  n <- readInt
  putStrLn $ if isHarshad n then "Yes" else "No"

isHarshad
  :: Int -> Bool
isHarshad x
  = let fx = sumDigits x
    in 0 == x `rem` fx

sumDigits, sumDigits'
  :: Int -> Int
sumDigits = sum . map digitToInt . show

sumDigits' = sum . int2lst
int2lst n
  | q == 0 = [r]
  | otherwise = r : int2lst q
  where
    (q,r) = divMod n 10

Score : 200 points

Problem Statement

An integer X is called a Harshad number if X is divisible by f(X), where f(X) is the sum of the digits in X when written in base 10.

Given an integer N, determine whether it is a Harshad number.

Constraints

1?N?10^8

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print Yes if N is a Harshad number; print No otherwise.

Sample Input 1

12

Sample Output 1

Yes

f(12)=1+2=3. Since 12 is divisible by 3, 12 is a Harshad number.

Sample Input 2

57

Sample Output 2

No

f(57)=5+7=12. Since 57 is not divisible by 12, 12 is not a Harshad number.

Sample Input 3

148

Sample Output 3

No


import Control.Monad
import Control.Applicative
import Data.List
import Data.Array
strToInt s = (read :: String -> Int) s

main = do
    n <- getLine
    let m = read n :: Int
    let an = sum (map (strToInt . \a -> [a]) n)
    if (mod m an) == 0 then putStrLn "Yes"
                       else putStrLn "No"


main = do
  s <- getLine
  let xs = [length $ filter (== x) s | x <- "abc"]
  putStrLn $ if maximum xs - minimum xs < 2 then "YES" else "NO"

Score : 400 points

Problem Statement

Snuke has a string S consisting of three kinds of letters: a, b and c.

He has a phobia for palindromes, and wants to permute the characters in S so that S will not contain a palindrome of length 2 or more as a substring. Determine whether this is possible.

Constraints

1 \leq |S| \leq 10^5

S consists of a, b and c.

Input

Input is given from Standard Input in the following format:

S

Output

If the objective is achievable, print YES; if it is unachievable, print NO.

Sample Input 1

abac

Sample Output 1

YES

As it stands now, S contains a palindrome aba, but we can permute the characters to get acba, for example, that does not contain a palindrome of length 2 or more.

Sample Input 2

aba

Sample Output 2

NO

Sample Input 3

babacccabab

Sample Output 3

YES


import Control.Monad.Trans.State

main :: IO ()
main = do
  n <- readLn
  print $ evalState (step n) (2, 1)

step :: Int -> State (Int, Int) Int
step 0 = fst <$> get
step 1 = snd <$> get
step n = get >>= put . lucas >> step (n - 1)
  where lucas (x, y) = (y, x + y)

Score : 200 points

Problem Statement

It is November 18 now in Japan. By the way, 11 and 18 are adjacent Lucas numbers.

You are given an integer N. Find the N-th Lucas number.

Here, the i-th Lucas number L_i is defined as follows:

L_0=2

L_1=1

L_i=L_{i-1}+L_{i-2} (i≥2)

Constraints

1≤N≤86

It is guaranteed that the answer is less than 10^{18}.

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the N-th Lucas number.

Sample Input 1

5

Sample Output 1

11

L_0=2

L_1=1

L_2=L_0+L_1=3

L_3=L_1+L_2=4

L_4=L_2+L_3=7

L_5=L_3+L_4=11

Thus, the 5-th Lucas number is 11.

Sample Input 2

86

Sample Output 2

939587134549734843


import Control.Monad

main :: IO ()
main = readLn >>= print . solve
    where
        solve n = xs !! n
            where
                xs = 2 : 1 : calc xs

        calc (x : y : zs) = (x + y) : calc (y : zs)


import Data.List
main = do
  nk <- map (read :: String -> Int) . words <$> getLine
  card <- reverse . sort . map (read :: String -> Int) . words <$> getLine
  putStrLn . show . length $ solve 0 0 (last nk) card

solve :: Int -> Int -> Int -> [Int] -> [Int]
solve n x k []      = []
solve n x k s@(y:ys)
  | n >= k        = solve (n-x) 0 k s
  | n + sum s < k = s
  | otherwise     = solve (n+y) y k ys

Score : 300 points

Problem Statement

Sitting in a station waiting room, Joisino is gazing at her train ticket.

The ticket is numbered with four digits A, B, C and D in this order, each between 0 and 9 (inclusive).

In the formula A op1 B op2 C op3 D = 7, replace each of the symbols op1, op2 and op3 with + or - so that the formula holds.

The given input guarantees that there is a solution. If there are multiple solutions, any of them will be accepted.

Constraints

0≤A,B,C,D≤9

All input values are integers.

It is guaranteed that there is a solution.

Input

Input is given from Standard Input in the following format:

ABCD

Output

Print the formula you made, including the part =7.

Use the signs + and -.

Do not print a space between a digit and a sign.

Sample Input 1

1222

Sample Output 1

1+2+2+2=7

This is the only valid solution.

Sample Input 2

0290

Sample Output 2

0-2+9+0=7

0 - 2 + 9 - 0 = 7 is also a valid solution.

Sample Input 3

3242

Sample Output 3

3+2+4-2=7


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

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

main = do
    [h,w] <- getIntList
    cs <- concat <$> replicateM 10 getIntList
    as <- replicateM h getIntList
    let ds :: [((Int,Int),Int)]
        ds = zip [(i,j)| i <- [0..9], j <- [0..9]] cs
    let wf :: Array (Int,Int) Int
        wf = runSTArray $ do
               arr <- newArray ((0,0),(9,9)) 1000
               sequence_ [writeArray arr ij d | (ij,d) <- ds ]
               forM_ [0..9] $ \k -> do
                   forM_ [0..9] $ \i -> do
                       forM_ [0..9] $ \j -> do
                           dij <- readArray arr (i,j)
                           dik <- readArray arr (i,k)
                           dkj <- readArray arr (k,j)
                           writeArray arr (i,j) $ min dij (dik + dkj)
               return arr
    print . sum $ map (sum . (map (\i -> if i == (-1) then 0 else wf ! (i,1)))) as

Score : 400 points

Problem Statement

Joisino the magical girl has decided to turn every single digit that exists on this world into 1.

Rewriting a digit i with j (0≤i,j≤9) costs c_{i,j} MP (Magic Points).

She is now standing before a wall. The wall is divided into HW squares in H rows and W columns, and at least one square contains a digit between 0 and 9 (inclusive).

You are given A_{i,j} that describes the square at the i-th row from the top and j-th column from the left, as follows:

If A_{i,j}≠-1, the square contains a digit A_{i,j}.

If A_{i,j}=-1, the square does not contain a digit.

Find the minimum total amount of MP required to turn every digit on this wall into 1 in the end.

Constraints

1≤H,W≤200

1≤c_{i,j}≤10^3 (i≠j)

c_{i,j}=0 (i=j)

-1≤A_{i,j}≤9

All input values are integers.

There is at least one digit on the wall.

Input

Input is given from Standard Input in the following format:

H W
c_{0,0} ... c_{0,9}
:
c_{9,0} ... c_{9,9}
A_{1,1} ... A_{1,W}
:
A_{H,1} ... A_{H,W}

Output

Print the minimum total amount of MP required to turn every digit on the wall into 1 in the end.

Sample Input 1

2 4
0 9 9 9 9 9 9 9 9 9
9 0 9 9 9 9 9 9 9 9
9 9 0 9 9 9 9 9 9 9
9 9 9 0 9 9 9 9 9 9
9 9 9 9 0 9 9 9 9 2
9 9 9 9 9 0 9 9 9 9
9 9 9 9 9 9 0 9 9 9
9 9 9 9 9 9 9 0 9 9
9 9 9 9 2 9 9 9 0 9
9 2 9 9 9 9 9 9 9 0
-1 -1 -1 -1
8 1 1 8

Sample Output 1

12

To turn a single 8 into 1, it is optimal to first turn 8 into 4, then turn 4 into 9, and finally turn 9 into 1, costing 6 MP.

The wall contains two 8s, so the minimum total MP required is 6×2=12.

Sample Input 2

5 5
0 999 999 999 999 999 999 999 999 999
999 0 999 999 999 999 999 999 999 999
999 999 0 999 999 999 999 999 999 999
999 999 999 0 999 999 999 999 999 999
999 999 999 999 0 999 999 999 999 999
999 999 999 999 999 0 999 999 999 999
999 999 999 999 999 999 0 999 999 999
999 999 999 999 999 999 999 0 999 999
999 999 999 999 999 999 999 999 0 999
999 999 999 999 999 999 999 999 999 0
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

Sample Output 2

0

Note that she may not need to change any digit.

Sample Input 3

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

Sample Output 3

47


import Data.Char
import qualified Data.Map.Strict as M
import Data.Map.Strict ((!))

main = putStrLn . (results!) . (\[l,r] -> compare l r) . map digitToInt . filter isHexDigit =<< getLine

results = M.fromDistinctAscList [(LT,"<"), (EQ,"="), (GT,">")]

Score : 100 points

Problem Statement

In programming, hexadecimal notation is often used.

In hexadecimal notation, besides the ten digits 0, 1, ..., 9, the six letters A, B, C, D, E and F are used to represent the values 10, 11, 12, 13, 14 and 15, respectively.

In this problem, you are given two letters X and Y. Each X and Y is A, B, C, D, E or F.

When X and Y are seen as hexadecimal numbers, which is larger?

Constraints

Each X and Y is A, B, C, D, E or F.

Input

Input is given from Standard Input in the following format:

X Y

Output

If X is smaller, print <; if Y is smaller, print >; if they are equal, print =.

Sample Input 1

A B

Sample Output 1

<

10 < 11.

Sample Input 2

E C

Sample Output 2

>

14 > 12.

Sample Input 3

F F

Sample Output 3

=

15 = 15.


{-# LANGUAGE BangPatterns         #-}
{-# LANGUAGE DerivingStrategies   #-}
{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE RankNTypes           #-}
{-# LANGUAGE ScopedTypeVariables  #-}
{-# LANGUAGE UndecidableInstances #-}
import           Control.Monad.State.Strict
import qualified Data.ByteString.Char8      as BS
import           Data.Char
import           Data.List

main :: IO ()
main = do
  [n,m] <- readLnAsListWith unconsInt

  print $ (2^m) * (1900*m + 100*(n-m))

-- converter
unconsInt :: StateT BS.ByteString Maybe Int
unconsInt = StateT $ BS.readInt . BS.dropWhile isSpace

-- 1D Data
-- for list
readLnAsListWith :: StateT BS.ByteString Maybe a -> IO [a]
readLnAsListWith !st = unfoldr (runStateT st) <$> BS.getLine

Score : 300 points

Problem Statement

Takahashi is now competing in a programming contest, but he received TLE in a problem where the answer is YES or NO.

When he checked the detailed status of the submission, there were N test cases in the problem, and the code received TLE in M of those cases.

Then, he rewrote the code to correctly solve each of those M cases with 1/2 probability in 1900 milliseconds, and correctly solve each of the other N-M cases without fail in 100 milliseconds.

Now, he goes through the following process:

Submit the code.

Wait until the code finishes execution on all the cases.

If the code fails to correctly solve some of the M cases, submit it again.

Repeat until the code correctly solve all the cases in one submission.

Let the expected value of the total execution time of the code be X milliseconds. Print X (as an integer).

Constraints

All input values are integers.

1 \leq N \leq 100

1 \leq M \leq {\rm min}(N, 5)

Input

Input is given from Standard Input in the following format:

N M

Output

Print X, the expected value of the total execution time of the code, as an integer. It can be proved that, under the constraints in this problem, X is an integer not exceeding 10^9.

Sample Input 1

1 1

Sample Output 1

3800

In this input, there is only one case. Takahashi will repeatedly submit the code that correctly solves this case with 1/2 probability in 1900 milliseconds.

The code will succeed in one attempt with 1/2 probability, in two attempts with 1/4 probability, and in three attempts with 1/8 probability, and so on.

Thus, the answer is 1900 \times 1/2 + (2 \times 1900) \times 1/4 + (3 \times 1900) \times 1/8 + ... = 3800.

Sample Input 2

10 2

Sample Output 2

18400

The code will take 1900 milliseconds in each of the 2 cases, and 100 milliseconds in each of the 10-2=8 cases. The probability of the code correctly solving all the cases is 1/2 \times 1/2 = 1/4.

Sample Input 3

100 5

Sample Output 3

608000


import Data.List

main :: IO ()
main = do
    [_,z,w] <- fmap read . words <$> getLine :: IO [Int]
    ls <- fmap read . words <$> getLine :: IO [Int]
    print $ solve ls z w

solve :: [Int] -> Int -> Int -> Int
solve ls z w    | length ls == 1 = abs (w - head ls)
                | otherwise = max (maximum $ abs <$> [w - head ls',w - ls' !! 1]) ot where
                    ls' = reverse ls
                    lss = takeWhile (== (maximum ls)) (reverse ls)
                    ot = if (lss /= []) && (last ls == maximum lss) then abs $ (maximum ls) - last ls else 0


main = readLn >>= print . solve

solve = (^ 2) . floor . sqrt

Score : 200 points

Problem Statement

Find the largest square number not exceeding N. Here, a square number is an integer that can be represented as the square of an integer.

Constraints

1 \leq N \leq 10^9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the largest square number not exceeding N.

Sample Input 1

10

Sample Output 1

9

10 is not square, but 9 = 3 × 3 is. Thus, we print 9.

Sample Input 2

81

Sample Output 2

81

Sample Input 3

271828182

Sample Output 3

271821169


import Data.Int (Int64)

maxSquareLE :: Integral a => a -> a
maxSquareLE n = (\x -> x * x) $ floor $ sqrt (fromIntegral n :: Double)

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


import qualified Data.Vector.Unboxed as VU
import qualified Data.ByteString.Char8 as B
import Data.Array
import Data.Maybe
import Data.List

type S = Array Int Int

-- 下限境界 (Array 付き)
lowerBoundA :: Array Int Int -> (Int, Int) -> Int -> Int
lowerBoundA arr (from, to) target
    | from == to = from
    | mValue >= target = lowerBoundA arr (from, mid) target
    | mValue < target = lowerBoundA arr (mid + 1, to) target
        where
            mid = (from + to) `div` 2
            mValue = arr ! mid

-- 上限境界 (Array 付き)
upperBoundA :: Array Int Int -> (Int, Int) -> Int -> Int
upperBoundA arr (from, to) target
    | from == to = from
    | mValue > target = upperBoundA arr (from, mid) target
    | mValue <= target = upperBoundA arr (mid + 1, to) target
        where
            mid = (from + to) `div` 2
            mValue = arr ! mid

solve :: S -> S -> S -> Int -> Int -> Int
solve xs ys zs n i
  | i >= n = 0
  | otherwise = res + solve xs ys zs n (i+1)
    where
      res = lb * (n - ub)
      y = ys ! i
      lb = lowerBoundA xs (0,n) y
      ub = upperBoundA zs (0,n) y

main = do
  n <- readLn :: IO Int
  xs <- listArray (0,n-1) . sort . map (fst . fromJust . B.readInt) . B.words <$> B.getLine :: IO S
  ys <- listArray (0,n-1) . sort . map (fst . fromJust . B.readInt) . B.words <$> B.getLine :: IO S
  zs <- listArray (0,n-1) . sort . map (fst . fromJust . B.readInt) . B.words <$> B.getLine :: IO S
  print $ solve xs ys zs n 0

Score : 300 points

Problem Statement

The season for Snuke Festival has come again this year. First of all, Ringo will perform a ritual to summon Snuke. For the ritual, he needs an altar, which consists of three parts, one in each of the three categories: upper, middle and lower.

He has N parts for each of the three categories. The size of the i-th upper part is A_i, the size of the i-th middle part is B_i, and the size of the i-th lower part is C_i.

To build an altar, the size of the middle part must be strictly greater than that of the upper part, and the size of the lower part must be strictly greater than that of the middle part. On the other hand, any three parts that satisfy these conditions can be combined to form an altar.

How many different altars can Ringo build? Here, two altars are considered different when at least one of the three parts used is different.

Constraints

1 \leq N \leq 10^5

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

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

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

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N
B_1 ... B_N
C_1 ... C_N

Output

Print the number of different altars that Ringo can build.

Sample Input 1

2
1 5
2 4
3 6

Sample Output 1

3

The following three altars can be built:

Upper: 1-st part, Middle: 1-st part, Lower: 1-st part

Upper: 1-st part, Middle: 1-st part, Lower: 2-nd part

Upper: 1-st part, Middle: 2-nd part, Lower: 2-nd part

Sample Input 2

3
1 1 1
2 2 2
3 3 3

Sample Output 2

27

Sample Input 3

6
3 14 159 2 6 53
58 9 79 323 84 6
2643 383 2 79 50 288

Sample Output 3

87


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

f [] _ _ = []
f (b:bs) [] n = 0 : (f bs [] n)
f (b:bs) (c:cs) n
  | b < c = n : (f bs (c:cs) n)
  | b >= c = (f (b:bs) cs (n-1))

g [] _ _ = []
g (a:as) [] [] = 0 : (g as [] [])
g (a:as) (b:bs) (b':bs')
  | a < b = b' : (g as (b:bs) (b':bs'))
  | a >= b = (g (a:as) bs bs')

main = do
  n <- readLn :: IO Int
  a <- BS.getLine >>= return . sort . (map (fst . fromJust . BS.readInt)) . BS.words :: IO [Int]
  b <- BS.getLine >>= return . sort . (map (fst . fromJust . BS.readInt)) . BS.words :: IO [Int]
  c <- BS.getLine >>= return . sort . (map (fst . fromJust . BS.readInt)) . BS.words :: IO [Int]

  let b' = (reverse . tail . (scanl (+) 0) .  reverse) $ f b c (length c)

  print $ sum $ g a b b'


import Control.Monad
import Data.Array.Unboxed
import Data.List

main :: IO ()
main = do
    n  <- read <$> getLine :: IO Int
    as <- listArray (0,n-1) . sort . map read . words <$> getLine :: IO (UArray Int Int)
    bs <- map read . words <$> getLine :: IO [Int]
    cs <- listArray (0,n-1) . sort . map read . words <$> getLine :: IO (UArray Int Int)
    let ns = map (\x -> (lowerBound as x) * (n - upperBound cs x)) bs
    print $ sum ns

sub :: Int -> Int -> Int
sub = (-)

lowerBound' :: UArray Int Int
            -> (Int, Int)
            -> Int
            -> Int
lowerBound' arr (first, last) n =
    let mid = div (first+last) 2
    in if last - first <= 1
        then if (arr!first) < n then last else first
        else if (arr!mid) < n
            then lowerBound' arr (mid, last)  n
            else lowerBound' arr (first, mid) n

lowerBound :: UArray Int Int -> Int -> Int
lowerBound arr n = let
    (start, last) = bounds arr
    in if (arr!last) < n then last+1
              else lowerBound' arr (start, last) n

upperBound :: UArray Int Int -> Int -> Int
upperBound arr n = lowerBound arr (n+1)


import Control.Monad
main = do
    n <- readLn
    ss <- (map ((map read) . words)) <$> replicateM 3 getLine
    print $ solve n ss
solve :: Int -> [[Int]] -> Int
solve n (a:b:c:d) = f b where
    f [] = 0
    f (x:xs) = fil' (x<) c * fil' (x>) a + f xs
    fil' _ []    = 0
    fil' g (x:xs)
      | g x         = 1 + fil' g xs
      | otherwise      = 0 + fil' g xs


module Main where
import Data.List

int = read::String -> Int
main = interact $ printer . solver . parser

printer = unlines . (:[]) . show
parser = int

solver :: Int -> Int
solver k = minimum $ take 10000 $ map target [k,(k*2)..]

target 0 = 0
target n = r + target q
  where
    (q,r) = divMod n 10

Score : 700 points

Problem Statement

Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Constraints

2 \leq K \leq 10^5

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Sample Input 1

6

Sample Output 1

3

12=6×2 yields the smallest sum.

Sample Input 2

41

Sample Output 2

5

11111=41×271 yields the smallest sum.

Sample Input 3

79992

Sample Output 3

36


main = print =<< (\n k -> (iterate (minimum . ([(2*), (k+)] <*>) . pure) 1) !! n) <$> readLn <*> readLn

Score : 200 points

Problem Statement

Square1001 has seen an electric bulletin board displaying the integer 1.
He can perform the following operations A and B to change this value:

Operation A: The displayed value is doubled.

Operation B: The displayed value increases by K.

Square1001 needs to perform these operations N times in total.
Find the minimum possible value displayed in the board after N operations.

Constraints

1 \leq N, K \leq 10

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
K

Output

Print the minimum possible value displayed in the board after N operations.

Sample Input 1

4
3

Sample Output 1

10

The value will be minimized when the operations are performed in the following order: A, A, B, B.

In this case, the value will change as follows: 1 → 2 → 4 → 7 → 10.

Sample Input 2

10
10

Sample Output 2

76

The value will be minimized when the operations are performed in the following order: A, A, A, A, B, B, B, B, B, B.

In this case, the value will change as follows: 1 → 2 → 4 → 8 → 16 → 26 → 36 → 46 → 56 → 66 → 76.

By the way, this contest is AtCoder Beginner Contest 076.


import Data.Array

main = do
  s <- getLine
  let ans = compute s
  print ans

{-
sを両側から突き合わせる。
両方同じ文字なら、消費する。
両方違う非x文字なら、失敗する。
片方がxでもう片方が違うなら、x入れたことにして消費する。
同じ文字にたどり着くか行きすぎたら成功。
-}

compute :: String -> Int
compute s = loop 0 1 n
  where
    n = length s
    arr = listArray (1,n) s
    loop cnt i j
      | i >= j = cnt
      | c == d = loop cnt (succ i) (pred j)
      | c == 'x' = loop (succ cnt) (succ i) j
      | d == 'x' = loop (succ cnt) i (pred j)
      | True   = -1
      where
        c = arr ! i
        d = arr ! j

Score : 400 points

Problem Statement

We have a string s consisting of lowercase English letters.
Snuke can perform the following operation repeatedly:

Insert a letter x to any position in s of his choice, including the beginning and end of s.

Snuke's objective is to turn s into a palindrome.
Determine whether the objective is achievable. If it is achievable, find the minimum number of operations required.

Notes

A palindrome is a string that reads the same forward and backward.
For example, a, aa, abba and abcba are palindromes, while ab, abab and abcda are not.

Constraints

1 \leq |s| \leq 10^5

s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

If the objective is achievable, print the number of operations required.
If it is not, print -1 instead.

Sample Input 1

xabxa

Sample Output 1

2

One solution is as follows (newly inserted x are shown in bold):

xabxa → xaxbxa → xaxbxax

Sample Input 2

ab

Sample Output 2

-1

No sequence of operations can turn s into a palindrome.

Sample Input 3

a

Sample Output 3

0

s is a palindrome already at the beginning.

Sample Input 4

oxxx

Sample Output 4

3

One solution is as follows:

oxxx → xoxxx → xxoxxx → xxxoxxx


import Control.Applicative
import Data.Maybe
import qualified Data.Sequence as S
import Data.Sequence (Seq, fromList, (<|), (|>), viewl, viewr, ViewL(..), ViewR(..))

main = getLine >>= print . fromMaybe (-1) . solve . fromList

solve :: Seq Char -> Maybe Int
solve q | S.length q <= 1 = Just 0
solve q
  | l == r    = solve ms
  | l == 'x'  = succ <$> solve (q |> 'x')
  | r == 'x'  = succ <$> solve ('x' <| q)
  | otherwise = Nothing
  where
    (l :< rs) = viewl q
    (ms :> r) = viewr rs


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
import           Control.Monad (replicateM)
import           Data.Int      (Int64)
import           Data.List     (minimum, sort)

type Point = (Int64, Int64)
type Rect = (Int64, Int64, Int64, Int64)

main :: IO ()
main = do
  [n, k] <- readInts
  xys <- replicateM n readPoint
  print $ solve n k xys

solve :: Int -> Int -> [Point] -> Int64
solve n k xys = minimum $ map area rs where
  rs = [(x1, x2, y1, y2) | x1 <- init xs
                         , x2 <- tail xs
                         , y1 <- init ys
                         , y2 <- tail ys
                         , isValid (x1, x2, y1, y2)
                         ]
  (xs, ys) = (sort (map fst xys), sort (map snd xys))
  isValid r = length (filter (isIncluded r) xys) >= k

isIncluded :: Rect -> Point -> Bool
isIncluded (x1, x2, y1, y2) (a, b) = x1 <= a && a <= x2 && y1 <= b && b <= y2

area :: Rect -> Int64
area (x1, x2, y1, y2) = (x2 - x1) * (y2 - y1)

readInts :: Read a => IO [a]
readInts = map read . words <$> getLine

readPoint :: IO Point
readPoint = do
  [x, y] <- readInts
  return (x, y)

Score : 400 points

Problem Statement

We have N points in a two-dimensional plane.

The coordinates of the i-th point (1 \leq i \leq N) are (x_i,y_i).

Let us consider a rectangle whose sides are parallel to the coordinate axes that contains K or more of the N points in its interior.

Here, points on the sides of the rectangle are considered to be in the interior.

Find the minimum possible area of such a rectangle.

Constraints

2 \leq K \leq N \leq 50

-10^9 \leq x_i,y_i \leq 10^9 (1 \leq i \leq N)

x_i≠x_j (1 \leq i<j \leq N)

y_i≠y_j (1 \leq i<j \leq N)

All input values are integers. (Added at 21:50 JST)

Input

Input is given from Standard Input in the following format:

N K
x_1 y_1
:
x_{N} y_{N}

Output

Print the minimum possible area of a rectangle that satisfies the condition.

Sample Input 1

4 4
1 4
3 3
6 2
8 1

Sample Output 1

21

One rectangle that satisfies the condition with the minimum possible area has the following vertices: (1,1), (8,1), (1,4) and (8,4).

Its area is (8-1) × (4-1) = 21.

Sample Input 2

4 2
0 0
1 1
2 2
3 3

Sample Output 2

1

Sample Input 3

4 3
-1000000000 -1000000000
1000000000 1000000000
-999999999 999999999
999999999 -999999999

Sample Output 3

3999999996000000001

Watch out for integer overflows.


main :: IO ()
main = getLine >>= putStrLn . solve
    where
        solve x = take (length x - 8) x

Score : 100 points

Problem Statement

Rng is going to a festival.

The name of the festival is given to you as a string S, which ends with FESTIVAL, from input. Answer the question: "Rng is going to a festival of what?" Output the answer.

Here, assume that the name of "a festival of s" is a string obtained by appending FESTIVAL to the end of s.
For example, CODEFESTIVAL is a festival of CODE.

Constraints

9 \leq |S| \leq 50

S consists of uppercase English letters.

S ends with FESTIVAL.

Input

Input is given from Standard Input in the following format:

S

Output

Print the answer to the question: "Rng is going to a festival of what?"

Sample Input 1

CODEFESTIVAL

Sample Output 1

CODE

This is the same as the example in the statement.

Sample Input 2

CODEFESTIVALFESTIVAL

Sample Output 2

CODEFESTIVAL

This string is obtained by appending FESTIVAL to the end of CODEFESTIVAL, so it is a festival of CODEFESTIVAL.

Sample Input 3

YAKINIKUFESTIVAL

Sample Output 3

YAKINIKU


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

import qualified Data.Map.Strict as Map

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 = do
	m1 <- readMap
	m2 <- readMap
	putStrLn $ which "YES" "NO" $ Map.isSubmapOfBy (<=) m2 m1

readMap :: IO ( Map.Map Int Int )
readMap = getLine >> getList >>= return . foldl' f Map.empty

f m a
	| Map.lookup a m /= Nothing = Map.adjust succ a m
	| otherwise = Map.insert a 1 m

Score : 200 points

Problem Statement

Rng is preparing a problem set for a qualification round of CODEFESTIVAL.

He has N candidates of problems. The difficulty of the i-th candidate is D_i.

There must be M problems in the problem set, and the difficulty of the i-th problem must be T_i. Here, one candidate of a problem cannot be used as multiple problems.

Determine whether Rng can complete the problem set without creating new candidates of problems.

Constraints

1 \leq N \leq 200,000

1 \leq D_i \leq 10^9

1 \leq M \leq 200,000

1 \leq T_i \leq 10^9

All numbers in the input are integers.

Partial Score

100 points will be awarded for passing the test set satisfying N \leq 100 and M \leq 100.

Input

Input is given from Standard Input in the following format:

N
D_1 D_2 ... D_N
M
T_1 T_2 ... T_M

Output

Print YES if Rng can complete the problem set without creating new candidates of problems; print NO if he cannot.

Sample Input 1

5
3 1 4 1 5
3
5 4 3

Sample Output 1

YES

Sample Input 2

7
100 200 500 700 1200 1600 2000
6
100 200 500 700 1600 1600

Sample Output 2

NO

Not enough 1600s.

Sample Input 3

1
800
5
100 100 100 100 100

Sample Output 3

NO

Sample Input 4

15
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
9
5 4 3 2 1 2 3 4 5

Sample Output 4

YES


import Data.List
import Data.Maybe

countPower :: Int -> Int -> (Int, Int)
countPower c n = if n `mod` c /= 0 then (n, 0)
                 else (m, 1 + cp)
  where (m, cp) = countPower c (n `div` c)

pfact :: Int -> [(Int, Int)]
pfact n = pfact0 n [2..]  []
  where
    pfact0 :: Int -> [Int] -> [(Int, Int)] -> [(Int, Int)]
    pfact0 n (c : cands) pans =
      let (rem, power) = countPower c n
          nextCands = filter (\x -> x `mod` c /= 0) cands
      in if power >= 1 then pfact0 rem nextCands ((c, power) : pans)
         else if c * c <= n then pfact0 rem nextCands pans
              else if n == 1 then reverse pans
                   else reverse ((n,1) : pans)

divisors :: Int -> [Int]
divisors n = sort (divis0 (pfact n))
  where
    divis0 [] = [1]
    divis0 ((p,r) : prs) =
      concatMap (\x -> map (* x) (divis0 prs)) (take (r + 1) (iterate (* p) 1))

qcOddM :: Int -> [Int]
qcOddM n = head (mapMaybe f [1..])
  where
    f :: Int -> Maybe [Int]
    f r = let (x, y) = (4 * r, n * r) in do
      as <- selSum 3 x (reverse (divisors y))
      return (map (div y) as)

-- Find k members from ys s.t. the sum equals to x.
-- ys are in descending order.
selSum :: Int -> Int -> [Int] -> Maybe [Int]
selSum k x ys
  | k == 0 && x == 0 = Just []
  | k == 0           = Nothing
  | otherwise        = let ys1 = dropWhile (> x) ys in
      case ys1 of
        [] -> Nothing
        (y:ys2) -> case selSum (k - 1) (x - y) ys1 of
          Just as -> Just (y:as)
          Nothing -> selSum k x ys2

qcBody :: Int -> [Int]
qcBody n | n `mod` 2 == 0 = let k = n `div` 2 in [k, 2*k, 2*k]
         | otherwise = qcOddM n

main :: IO ()
main = do
  line <- getLine
  let n = read line :: Int
  putStrLn (concat (intersperse " " (map show (qcBody n))))

Score : 300 points

Problem Statement

You are given an integer N.

Find a triple of positive integers h, n and w such that 4/N = 1/h + 1/n + 1/w.

If there are multiple solutions, any of them will be accepted.

Constraints

It is guaranteed that, for the given integer N, there exists a solution such that h,n,w \leq 3500.

Inputs

Input is given from Standard Input in the following format:

N

Outputs

Print a triple of positive integers h, n and w that satisfies the condition, in the following format:

h n w

Sample Input 1

2

Sample Output 1

1 2 2

4/2 = 1/1 + 1/2 + 1/2.

Sample Input 2

3485

Sample Output 2

872 1012974 1539173474040

It is allowed to use an integer exceeding 3500 in a solution.

Sample Input 3

4664

Sample Output 3

3498 3498 3498


import Data.List
import Data.Ord

main = print . solve . tuplify . map read . drop 1 . words =<< getContents

tuplify [] = []
tuplify (x:y:xs) = (x,y):tuplify xs

solve :: [(Int,Int)] -> Int
solve = (\(f,s) -> f+s) . maximumBy (comparing fst)

Score : 200 points

Problem Statement

A group of people played a game. All players had distinct scores, which are positive integers.

Takahashi knows N facts on the players' scores. The i-th fact is as follows: the A_i-th highest score among the players is B_i.

Find the maximum possible number of players in the game.

Constraints

1 \leq N \leq 10^5

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

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

If i ≠ j, A_i ≠ A_j.

There exists a possible outcome of the game that are consistent with the facts.

All input values are integers.

Inputs

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Outputs

Print the maximum possible number of players in the game.

Sample Input 1

3
4 7
2 9
6 2

Sample Output 1

8

The maximum possible number of players is achieved when, for example, the players have the following scores: 12,9,8,7,5,2,1,0.

Sample Input 2

5
1 10
3 6
5 2
4 4
2 8

Sample Output 2

7

Sample Input 3

2
1 1000000000
1000000000 1

Sample Output 3

1000000001


naive_solver::Int->Int->Int->Bool
naive_solver n m k = not ([] == (dropWhile (\x->x/=k) [(n*j+i*m-2*i*j)|i<-[0..n],j<-[0..m]]))

main::IO()
main=do
  dat<-getLine
  let m:n:k:[]=map read (words dat)
  putStr (if naive_solver n m k then "Yes" else "No")
  putStr "\n"

Score : 200 points

Problem Statement

We have a grid with N rows and M columns of squares. Initially, all the squares are white.

There is a button attached to each row and each column.
When a button attached to a row is pressed, the colors of all the squares in that row are inverted; that is, white squares become black and vice versa.
When a button attached to a column is pressed, the colors of all the squares in that column are inverted.

Takahashi can freely press the buttons any number of times. Determine whether he can have exactly K black squares in the grid.

Constraints

1 \leq N,M \leq 1000

0 \leq K \leq NM

Input

Input is given from Standard Input in the following format:

N M K

Output

If Takahashi can have exactly K black squares in the grid, print Yes; otherwise, print No.

Sample Input 1

2 2 2

Sample Output 1

Yes

Press the buttons in the order of the first row, the first column.

Sample Input 2

2 2 1

Sample Output 2

No

Sample Input 3

3 5 8

Sample Output 3

Yes

Press the buttons in the order of the first column, third column, second row, fifth column.

Sample Input 4

7 9 20

Sample Output 4

No


import Control.Applicative

main :: IO ()
main = do
    n <- readLn
    m <- readLn
    putStrLn $ show (n ^ 2 - m)

Score : 100 points

Problem Statement

We have an N \times N square grid.

We will paint each square in the grid either black or white.

If we paint exactly A squares white, how many squares will be painted black?

Constraints

1 \leq N \leq 100

0 \leq A \leq N^2

Inputs

Input is given from Standard Input in the following format:

N
A

Outputs

Print the number of squares that will be painted black.

Sample Input 1

3
4

Sample Output 1

5

There are nine squares in a 3 \times 3 square grid.
Four of them will be painted white, so the remaining five squares will be painted black.

Sample Input 2

19
100

Sample Output 2

261

Sample Input 3

10
0

Sample Output 3

100

As zero squares will be painted white, all the squares will be painted black.


strip :: [a] -> a
strip [x] = x

main = do
  ns <- fmap (fmap (read :: String -> Int) . words) . lines <$> getContents
  let n = strip $ head ns
  let a = strip $ last ns
  putStrLn $ show $ (n * n - a)


import Data.List

main = do
  (a:b:c:d:e:f:_) <- getLine >>= return . map read . words :: IO [Int]

  let
    sugar = nub $ sort $ (takeWhile (<=f) (iterate (+c) c)) ++ (takeWhile (<=f) (iterate (+d) d))
    water = nub $ sort $ (takeWhile (<=f) (iterate (+(a*100)) (a*100))) ++ (takeWhile (<=f) (iterate (+(b*100)) (b*100)))

    (ws, s) = maximumBy (\(x1,y1) (x2,y2) -> compare (divint y1 x1) (divint y2 x2)) [(w+s,s) | w <- water, s <- sugar, w + s <= f, (div w 100) * e >= s]

  putStr $ show ws
  putStr " "
  putStrLn $ show s

  where
    divint a b = (fromIntegral a) / (fromIntegral b)

Score : 300 points

Problem Statement

Snuke is making sugar water in a beaker.
Initially, the beaker is empty. Snuke can perform the following four types of operations any number of times. He may choose not to perform some types of operations.

Operation 1: Pour 100A grams of water into the beaker.

Operation 2: Pour 100B grams of water into the beaker.

Operation 3: Put C grams of sugar into the beaker.

Operation 4: Put D grams of sugar into the beaker.

In our experimental environment, E grams of sugar can dissolve into 100 grams of water.

Snuke will make sugar water with the highest possible density.

The beaker can contain at most F grams of substances (water and sugar combined), and there must not be any undissolved sugar in the beaker.
Find the mass of the sugar water Snuke will make, and the mass of sugar dissolved in it.
If there is more than one candidate, any of them will be accepted.

We remind you that the sugar water that contains a grams of water and b grams of sugar is \frac{100b}{a + b} percent.
Also, in this problem, pure water that does not contain any sugar is regarded as 0 percent density sugar water.

Constraints

1 \leq A < B \leq 30

1 \leq C < D \leq 30

1 \leq E \leq 100

100A \leq F \leq 3 000

A, B, C, D, E and F are all integers.

Inputs

Input is given from Standard Input in the following format:

A B C D E F

Outputs

Print two integers separated by a space.
The first integer should be the mass of the desired sugar water, and the second should be the mass of the sugar dissolved in it.

Sample Input 1

1 2 10 20 15 200

Sample Output 1

110 10

In this environment, 15 grams of sugar can dissolve into 100 grams of water, and the beaker can contain at most 200 grams of substances.

We can make 110 grams of sugar water by performing Operation 1 once and Operation 3 once.
It is not possible to make sugar water with higher density.
For example, the following sequences of operations are infeasible:

If we perform Operation 1 once and Operation 4 once, there will be undissolved sugar in the beaker.

If we perform Operation 2 once and Operation 3 three times, the mass of substances in the beaker will exceed 200 grams.

Sample Input 2

1 2 1 2 100 1000

Sample Output 2

200 100

There are other acceptable outputs, such as:

400 200

However, the output below is not acceptable:

300 150

This is because, in order to make 300 grams of sugar water containing 150 grams of sugar, we need to pour exactly 150 grams of water into the beaker, which is impossible.

Sample Input 3

17 19 22 26 55 2802

Sample Output 3

2634 934


main :: IO ()
main = do
  n <- getLine
  putStrLn $ if '9' `elem` n then "Yes" else "No"

Score : 100 points

Problem Statement

It is September 9 in Japan now.

You are given a two-digit integer N. Answer the question: Is 9 contained in the decimal notation of N?

Constraints

10≤N≤99

Input

Input is given from Standard Input in the following format:

N

Output

If 9 is contained in the decimal notation of N, print Yes; if not, print No.

Sample Input 1

29

Sample Output 1

Yes

The one's digit of 29 is 9.

Sample Input 2

72

Sample Output 2

No

72 does not contain 9.

Sample Input 3

91

Sample Output 3

Yes


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

main :: IO()
main = do
  n <- readLn :: IO Int
  lst <- replicateM n readLn :: IO [Int]
  let l = (foldl (\x -> \y -> x + ((length y) `mod` 2)) 0  . splitBySame) lst
  print  l

splitBySame ::  (Ord a) => [a] -> [[a]]
splitBySame [] = []
splitBySame list = let (x:xs) = sort list; (lst, rest) = split x [] xs in lst : splitBySame rest
    where
      split :: (Ord a) => a -> [a]-> [a] -> ([a], [a])
      split n acc [] = (n:acc, [])
      split n acc (x:xs)
                  | n == x = split n (x:acc) xs
                  | n /= x = (n:acc, x:xs)


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

-- String, Int, Char, IO

-- e.g.
-- 1
-- [a] <- map read . words <$> getLine => [1] -> a == 1
-- 1
-- a <- readLn
-- 1 2 3
-- lst <- map read . words <$> getLine => [1, 2, 3]
-- 1 2 3
-- [l, m, n] <- map read . words <$. getLine :: IO [Int] => [1, 2, 3]
-- 'a'
-- c <- getChar => c == 'a'

main :: IO()
main = do
  n <- readLn :: IO Int
  lst <- replicateM n readLn :: IO [Int]
  let l = (foldl (\x -> \y -> x + ((length y) `mod` 2)) 0  . splitBySame) lst
  print  l

countBySame' :: [Int] -> [Int]
countBySame' [] = []
countBySame' lst = let x:xs = sort lst  ; (n, list) = (samelist x xs 0) in n : (countBySame' list)
  where
    samelist :: Int -> [Int] ->  Int -> (Int, [Int])
    samelist a [] n = (n+1, [])
    samelist a (x:xs) n
                  | a == x = samelist a xs (n+1)
                  | a /= x = (n+1, x:xs)

splitBySame ::  (Ord a) => [a] -> [[a]]
splitBySame [] = []
splitBySame list = let (x:xs) = sort list; (lst, rest) = split x [] xs in lst : splitBySame rest
    where
      split :: (Ord a) => a -> [a]-> [a] -> ([a], [a])
      split n acc [] = (n:acc, [])
      split n acc (x:xs)
                  | n == x = split n (x:acc) xs
                  | n /= x = (n:acc, x:xs)


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

main :: IO ()
main = do
    as <- tail . map (fst . fromJust . B.readInt) . B.lines <$> B.getContents
    print $ sum $ map (\s -> length s `mod` 2) $ group $ sort as

Score : 300 points

Problem Statement

You are playing the following game with Joisino.

Initially, you have a blank sheet of paper.

Joisino announces a number. If that number is written on the sheet, erase the number from the sheet; if not, write the number on the sheet. This process is repeated N times.

Then, you are asked a question: How many numbers are written on the sheet now?

The numbers announced by Joisino are given as A_1, ... ,A_N in the order she announces them. How many numbers will be written on the sheet at the end of the game?

Constraints

1≤N≤100000

1≤A_i≤1000000000(=10^9)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print how many numbers will be written on the sheet at the end of the game.

Sample Input 1

3
6
2
6

Sample Output 1

1

The game proceeds as follows:

6 is not written on the sheet, so write 6.

2 is not written on the sheet, so write 2.

6 is written on the sheet, so erase 6.

Thus, the sheet contains only 2 in the end. The answer is 1.

Sample Input 2

4
2
5
5
2

Sample Output 2

0

It is possible that no number is written on the sheet in the end.

Sample Input 3

6
12
22
16
22
18
12

Sample Output 3

2


import Control.Monad
import qualified Data.IntSet as S
import Control.Monad.Trans.State

main = do
  n <- readLn
  as <- map read <$> replicateM n getLine
  print $ evalState (solve as) S.empty

solve [] = S.size <$> get
solve (a:as) = do
  s <- get
  put $ if a `S.member` s
    then S.delete a s
    else S.insert a s
  solve as


import qualified Data.ByteString.Char8 as BC
import Data.Maybe (fromJust)
import Data.List
import Data.Array.IO
import Control.Monad

type Memo = IOUArray (Int, Int) Int

main = do
  [n, m, r] <- map read . words <$> getLine :: IO [Int]
  rr <- map read . words <$> getLine :: IO [Int]
  input <- (\[x, y, z] -> zip3 x y z) . transpose <$> getInt2DListBC
  edge <- newArray ((1, 1), (n, n)) (10^9) :: IO Memo
  foldM memoize edge input
  foldM memoize edge [(i, i, 0) | i <- [1..n]]
  let index = [(k, i, j) | k <- [1..n], i <- [1..n], j <- [1..n]]
  foldM warshallFloyd edge index
  ans <- mapM (readMemo edge) $ permutations rr
  putStrLn . show . minimum $ ans

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

getInt2DListBC :: IO [[Int]]
getInt2DListBC = map (map bsToInt . BC.words) . BC.lines <$> BC.getContents

memoize :: Memo -> (Int, Int, Int) -> IO Memo
memoize memo (x, y, d) = do
  writeArray memo (x, y) d
  writeArray memo (y, x) d
  return memo

warshallFloyd :: Memo -> (Int, Int, Int) -> IO Memo
warshallFloyd memo (k, i, j) = do
  x <- readArray memo (i, j)
  y <- readArray memo (i, k)
  z <- readArray memo (k, j)
  let minWeight = min x $ y + z
  writeArray memo (i, j) minWeight
  return memo

readMemo :: Memo -> [Int] -> IO Int
readMemo memo (_:[]) = return 0
readMemo memo (s:t:ts) = do
  d <- readArray memo (s, t)
  sum <- (+d) <$> readMemo memo (t:ts)
  return sum

Score : 400 points

Problem Statement

There are N towns in the State of Atcoder, connected by M bidirectional roads.

The i-th road connects Town A_i and B_i and has a length of C_i.

Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in this order).

She will fly to the first town she visits, and fly back from the last town she visits, but for the rest of the trip she will have to travel by road.

If she visits the towns in the order that minimizes the distance traveled by road, what will that distance be?

Constraints

2≤N≤200

1≤M≤N×(N-1)/2

2≤R≤min(8,N) (min(8,N) is the smaller of 8 and N.)

r_i≠r_j (i≠j)

1≤A_i,B_i≤N, A_i≠B_i

(A_i,B_i)≠(A_j,B_j),(A_i,B_i)≠(B_j,A_j) (i≠j)

1≤C_i≤100000

Every town can be reached from every town by road.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M

Output

Print the distance traveled by road if Joisino visits the towns in the order that minimizes it.

Sample Input 1

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

Sample Output 1

2

For example, if she visits the towns in the order of 1, 2, 3, the distance traveled will be 2, which is the minimum possible.

Sample Input 2

3 3 2
1 3
2 3 2
1 3 6
1 2 2

Sample Output 2

4

The shortest distance between Towns 1 and 3 is 4. Thus, whether she visits Town 1 or 3 first, the distance traveled will be 4.

Sample Input 3

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

Sample Output 3

3


import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import qualified Data.Array.IArray as A
import qualified Data.Map.Strict as M
import Data.List

main = do
  [n,m,r] <- map read . words <$> getLine
  rs <- map (pred . read) . words <$> getLine
  es <- filter (\((s,t),w) -> elem s rs && elem t rs) . readUndirectedEdge <$> B.getContents
  let memo = warshallFloyd r es
  let vs = [(v,w) | v<-rs, w<-rs, v<w]
  print $ sum $ (\xs -> if length xs <= 2 then xs else init xs) $ sort $ map (\e -> memo M.! e) vs

type Memo = M.Map (Vertex, Vertex) Weight

-- 0-indexed vertex
warshallFloyd :: Int -> [Edge] -> Memo
warshallFloyd n es = foldl shorten m0 kij
  where
    m0 = M.fromList es
    kij = [(k, i, j) | k <- [0 .. pred n], i <- [0 .. pred n], j <- [i .. pred n]]

shorten :: Memo -> (Vertex, Vertex, Vertex) -> Memo
shorten m (k, i, j) = case connect m k i j of
  Nothing -> m
  Just w -> M.insertWith min (i, j) w m

connect :: Memo -> Vertex -> Vertex -> Vertex -> Maybe Weight
connect m k i j = do
  w1 <- M.lookup (i, k) m
  w2 <- M.lookup (k, j) m
  return (w1 + w2)

readInt :: B.ByteString -> Int
readInt = maybe undefined fst . B.readInt

type Vertex = Int
type Weight = Int
type Edge = ((Vertex, Vertex), Weight)

readUndirectedEdge :: B.ByteString -> [Edge]
readUndirectedEdge = concatMap (constructTwoWay . map readInt . B.words) . B.lines

constructTwoWay :: [Int] -> [Edge]
constructTwoWay [s,t,w] = [((s-1, t-1), w), ((t-1, s-1), w)]
constructTwoWay _ = undefined


import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import qualified Data.Array.IArray as A
import qualified Data.Map.Strict as M
import Data.List

main = do
  [n,m,r] <- map read . words <$> getLine
  rs <- map (pred . read) . words <$> getLine
  es <- readUndirectedEdge <$> B.getContents
  let g = buildG (0,n-1) es
  let memo = warshallFloyd n es
  let vs = [(v,w) | v<-rs, w<-rs, v<w]
  print $ sum $ (\xs -> if length xs <= 2 then xs else init xs) $ sort $ map (\e -> memo M.! e) vs

type Memo = M.Map (Vertex, Vertex) Weight

-- 0-indexed vertex
warshallFloyd :: Int -> [Edge] -> Memo
warshallFloyd n es = foldl shorten m0 kij
  where
    m0 = M.fromList es
    kij = [(k, i, j) | k <- [0 .. pred n], i <- [0 .. pred n], j <- [0 .. pred n]]

shorten :: Memo -> (Vertex, Vertex, Vertex) -> Memo
shorten m (k, i, j) = case connect m k i j of
  Nothing -> m
  Just w -> M.insertWith min (i, j) w m

connect :: Memo -> Vertex -> Vertex -> Vertex -> Maybe Weight
connect m k i j = do
  w1 <- M.lookup (i, k) m
  w2 <- M.lookup (k, j) m
  return (w1 + w2)

readInt :: B.ByteString -> Int
readInt = maybe undefined fst . B.readInt

type Bound = (Vertex, Vertex)
type Vertex = Int
type Weight = Int
type Edge = ((Vertex, Vertex), Weight)
type Path = [Vertex]
type Graph = A.Array Vertex (S.Set (Vertex, Weight))

buildG :: Bound -> [Edge] -> Graph
buildG b = A.accumArray (flip S.insert) S.empty b . map (\((s, t), w) -> (s, (t, w)))

target :: Graph -> Vertex -> S.Set (Vertex, Weight)
target = (A.!)

size :: Graph -> Int
size g = let (i,j) = A.bounds g in j - i + 1

readUndirectedEdge :: B.ByteString -> [Edge]
readUndirectedEdge = concatMap (constructTwoWay . map readInt . B.words) . B.lines

constructTwoWay :: [Int] -> [Edge]
constructTwoWay [s,t,w] = [((s-1, t-1), w), ((t-1, s-1), w)]
constructTwoWay _ = undefined


main :: IO ()
main = do
  [x, t] <- map read . words <$> getLine
  print $ max 0 (x - t)

Score : 100 points

Problem Statement

We have a sandglass that runs for X seconds. The sand drops from the upper bulb at a rate of 1 gram per second. That is, the upper bulb initially contains X grams of sand.

How many grams of sand will the upper bulb contains after t seconds?

Constraints

1≤X≤10^9

1≤t≤10^9

X and t are integers.

Input

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

X t

Output

Print the number of sand in the upper bulb after t second.

Sample Input 1

100 17

Sample Output 1

83

17 out of the initial 100 grams of sand will be consumed, resulting in 83 grams.

Sample Input 2

48 58

Sample Output 2

0

All 48 grams of sand will be gone, resulting in 0 grams.

Sample Input 3

1000000000 1000000000

Sample Output 3

0


main :: IO ()
main = do
  s <- getLine
  putStrLn $ pickOdds2 s

pickOdds2 = map snd . filter fst . zip (cycle [True, False])

Score : 200 points

Problem Statement

You are given a string s consisting of lowercase English letters. Extract all the characters in the odd-indexed positions and print the string obtained by concatenating them. Here, the leftmost character is assigned the index 1.

Constraints

Each character in s is a lowercase English letter.

1≤|s|≤10^5

Input

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

s

Output

Print the string obtained by concatenating all the characters in the odd-numbered positions.

Sample Input 1

atcoder

Sample Output 1

acdr

Extract the first character a, the third character c, the fifth character d and the seventh character r to obtain acdr.

Sample Input 2

aaaa

Sample Output 2

aa

Sample Input 3

z

Sample Output 3

z

Sample Input 4

fukuokayamaguchi

Sample Output 4

fkoaaauh


import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)
import qualified Data.Map.Strict as M
import qualified Data.Vector.Unboxed as VU

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

lambda::M.Map Int Int->Int->M.Map Int Int
lambda acc v = foldl (\acc x -> if M.member x acc then M.adjust (+1) x acc else M.insert x 1 acc) acc [v-1,v,v+1]

main = do
  n <- getLine
  an <- getInts
  print $ maximum $ M.elems . VU.foldl lambda M.empty $ VU.fromList an

Score : 300 points

Problem Statement

You are given an integer sequence of length N, a_1,a_2,...,a_N.

For each 1≤i≤N, you have three choices: add 1 to a_i, subtract 1 from a_i or do nothing.

After these operations, you select an integer X and count the number of i such that a_i=X.

Maximize this count by making optimal choices.

Constraints

1≤N≤10^5

0≤a_i<10^5 (1≤i≤N)

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

Print the maximum possible number of i such that a_i=X.

Sample Input 1

7
3 1 4 1 5 9 2

Sample Output 1

4

For example, turn the sequence into 2,2,3,2,6,9,2 and select X=2 to obtain 4, the maximum possible count.

Sample Input 2

10
0 1 2 3 4 5 6 7 8 9

Sample Output 2

3

Sample Input 3

1
99999

Sample Output 3

1


import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Data.Maybe (fromJust)
import Data.List
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Set as S

ary :: [Int] -> UArray Int Int
ary xs = runSTUArray $ do
    let gs = group xs
        zs = zip (map head gs) (map length gs)
    a <- newArray (head xs, last xs + 2) 0
    forM_ zs $ \(i,n) -> do
        x <- readArray a i
        writeArray a i (x+n)
    return a

solve :: UArray Int Int -> [Int] -> Int
solve a = foldr f 0
  where
    f x mx = let mx' = (a!x) + (a!(x+1)) + (a!(x+2))
              in max mx mx'

fastnub :: [Int] -> [Int]
fastnub = S.toList . S.fromList

main :: IO ()
main = do
    _ <- getLine
    a <- sort . map (fst . fromJust . BS.readInt)
        . BS.words <$> BS.getLine :: IO [Int]
    print $ solve (ary a) (fastnub a)


import Data.List

count :: Int -> [(Int, Int)] -> Int
count n = sum . map snd . filter (\(x, _) -> x == (n-1) || x == n || x == (n+1))

solve :: [Int] -> Int
solve xs =
    let ys = map (\xs -> (head xs, length xs)) . group . sort $ xs
        zs = concatMap (\x -> [x - 1, x, x + 1]) xs
    in maximum . map (flip count ys) $ zs

main = getLine >> map read . words <$> getLine >>= print . solve


import Data.List
import Data.Bool

main = print . solve . map (\xs -> (head xs, length xs)) . group . sort . map read . drop 1 . words =<< getContents

solve :: [(Int,Int)] -> Int
solve xls = maximum $ zipWith3 (\(a,al) (b,bl) (c,cl) -> bl + (bool 0 al $ abs(a-b) == 1) + (bool 0 cl $ abs(c-b) == 1)) xls' (drop 1 xls') (drop 2 xls')
    where
        xls' = [(0,0)] ++ xls ++ [(0,0)]


h a=read a::Int;i u=(u<$>getLine>>=);main=i(map h.words)$i h.(print.).g;c?d=min(c*2)d;g[t,u,v,w]n=div n 2*p?w+mod n 2*p where p=o?v;o=t?u

Score : 300 points

Problem Statement

You've come to your favorite store Infinitesco to buy some ice tea.

The store sells ice tea in bottles of different volumes at different costs.
Specifically, a 0.25-liter bottle costs Q yen, a 0.5-liter bottle costs H yen, a 1-liter bottle costs S yen, and a 2-liter bottle costs D yen.
The store has an infinite supply of bottles of each type.

You want to buy exactly N liters of ice tea. How many yen do you have to spend?

Constraints

1 \leq Q, H, S, D \leq 10^8

1 \leq N \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

Q H S D
N

Output

Print the smallest number of yen you have to spend to buy exactly N liters of ice tea.

Sample Input 1

20 30 70 90
3

Sample Output 1

150

Buy one 2-liter bottle and two 0.5-liter bottles. You'll get 3 liters for 90 + 30 + 30 = 150 yen.

Sample Input 2

10000 1000 100 10
1

Sample Output 2

100

Even though a 2-liter bottle costs just 10 yen, you need only 1 liter.
Thus, you have to buy a 1-liter bottle for 100 yen.

Sample Input 3

10 100 1000 10000
1

Sample Output 3

40

Now it's better to buy four 0.25-liter bottles for 10 + 10 + 10 + 10 = 40 yen.

Sample Input 4

12345678 87654321 12345678 87654321
123456789

Sample Output 4

1524157763907942


import Data.List
main=getLine>>=print.q
q s=1+d s-(sum.map d.group$sort s)
d=c.genericLength
c n=n*(n-1)`div`2

Score : 500 points

Problem Statement

You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.

You can choose any two indices i and j such that 1 \leq i \leq j \leq n and reverse substring A_i A_{i+1} ... A_j.

You can perform this operation at most once.

How many different strings can you obtain?

Constraints

1 \leq |A| \leq 200,000

A consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

A

Output

Print the number of different strings you can obtain by reversing any substring in A at most once.

Sample Input 1

aatt

Sample Output 1

5

You can obtain aatt (don't do anything), atat (reverse A[2..3]), atta (reverse A[2..4]), ttaa (reverse A[1..4]) and taat (reverse A[1..3]).

Sample Input 2

xxxxxxxxxx

Sample Output 2

1

Whatever substring you reverse, you'll always get xxxxxxxxxx.

Sample Input 3

abracadabra

Sample Output 3

44


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

readInt :: B.ByteString -> Int
readInt = maybe undefined fst . B.readInt

readIntPair :: B.ByteString -> [(Int, Int)]
readIntPair = map (pair . map readInt . B.words) . B.lines

pair :: [t] -> (t, t)
pair [x, y] = (x, y)
pair _ = undefined

main = do
  [x1,y1,x2,y2] <- (\[a,b,c,d] -> if a>c || b>d then [c,d,a,b] else [a,b,c,d]) . map read . words <$> getLine
  _ <- getLine
  xys <- readIntPair <$> B.getContents
  print (walk x1 y1 x2 y2 xys)

walk x1 y1 x2 y2 xys = 100*s - (20 - 5*pi)*p + (10*pi - 20)*q
  where
    s = fromIntegral $ abs (x1-x2) + abs (y1-y2)
    k = fromIntegral $ length $ lis $ map snd $ sort $ filter (\(x,y) -> x1<=x && x<=x2 && y1<=y && y<=y2) xys
    (p, q) = (fromIntegral *** fromIntegral ) $ if k < min (abs (x1-x2)) (abs (y1-y2)) + 1 then (k, 0) else (k - 1, 1)

lis :: Ord a => [a] -> [a]
lis = S.toList . snd . foldl go (S.empty, S.empty)
  where
    go (acc, acc0) x = case S.lookupGT x acc of
      Nothing -> let acc1 = S.insert x acc in (acc1, acc1)
      Just g -> (S.insert x (S.delete g acc), acc0)

Score : 900 points

Problem Statement

In the city of Nevermore, there are 10^8 streets and 10^8 avenues, both numbered from 0 to 10^8-1.
All streets run straight from west to east, and all avenues run straight from south to north.
The distance between neighboring streets and between neighboring avenues is exactly 100 meters.

Every street intersects every avenue. Every intersection can be described by pair (x, y), where x is avenue ID and y is street ID.

There are N fountains in the city, situated at intersections (X_i, Y_i).
Unlike normal intersections, there's a circle with radius 10 meters centered at the intersection, and there are no road parts inside this circle.

The picture below shows an example of how a part of the city with roads and fountains may look like.

City governors don't like encountering more than one fountain while moving along the same road.
Therefore, every street contains at most one fountain on it, as well as every avenue.

Citizens can move along streets, avenues and fountain perimeters.
What is the shortest distance one needs to cover in order to get from intersection (x_1, y_1) to intersection (x_2, y_2)?

Constraints

0 \leq x_1, y_1, x_2, y_2 < 10^8

1 \leq N \leq 200,000

0 \leq X_i, Y_i < 10^8

X_i \neq X_j for i \neq j

Y_i \neq Y_j for i \neq j

Intersections (x_1, y_1) and (x_2, y_2) are different and don't contain fountains.

All input values are integers.

Input

Input is given from Standard Input in the following format:

x_1 y_1 x_2 y_2
N
X_1 Y_1
X_2 Y_2
:
X_N Y_N

Output

Print the shortest possible distance one needs to cover in order to get from intersection (x_1, y_1) to intersection (x_2, y_2), in meters.
Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-11}.

Sample Input 1

1 1 6 5
3
3 2
5 3
2 4

Sample Output 1

891.415926535897938

One possible shortest path is shown on the picture below. The path starts at the blue point, finishes at the purple point and follows along the red line.

Sample Input 2

3 5 6 4
3
3 2
5 3
2 4

Sample Output 2

400.000000000000000

Sample Input 3

4 2 2 2
3
3 2
5 3
2 4

Sample Output 3

211.415926535897938


main = do
    [x, a, b] <- map read . words <$> getLine :: IO [Int]
    putStrLn $ if abs (x - a) <= abs (x - b) then "A" else "B"

Score : 100 points

Problem Statement

Snuke lives at position x on a number line.
On this line, there are two stores A and B, respectively at position a and b, that offer food for delivery.

Snuke decided to get food delivery from the closer of stores A and B.
Find out which store is closer to Snuke's residence.

Here, the distance between two points s and t on a number line is represented by |s-t|.

Constraints

1 \leq x \leq 1000

1 \leq a \leq 1000

1 \leq b \leq 1000

x, a and b are pairwise distinct.

The distances between Snuke's residence and stores A and B are different.

Input

Input is given from Standard Input in the following format:

x a b

Output

If store A is closer, print A; if store B is closer, print B.

Sample Input 1

5 2 7

Sample Output 1

B

The distances between Snuke's residence and stores A and B are 3 and 2, respectively.
Since store B is closer, print B.

Sample Input 2

1 999 1000

Sample Output 2

A


main = interact $ sol . map read . words
sol [x,a,b] = if abs (x-a) < abs (x-b) then "A" else "B"


main :: IO()
main = do
    [x,a,b] <- map read . words <$> getLine
    putStrLn $ atika x a b

atika :: Int -> Int -> Int -> String
atika x a b = if (abs (x-a)) < (abs (x-b)) then "A" else "B"


main = interact $ (\[x, a, b] -> if abs (x - a) < abs (x - b) then "A\n" else "B\n") . map (read :: String -> Int) . words


main :: IO ()
main = do
  s <- getLine
  putStrLn $ solve $ map read $ words s

solve (x:a:b:_)
  |na < nb = "B"
  |na > nb = "A"
  where
    na = abs(x-a)
    nb = abs(x-b)


data Arrange = Twin | Single deriving (Show, Eq)

prime = 1000000007 :: Integer

abbr :: String -> [Arrange] -> [Arrange]
abbr [] xs = xs
abbr [_] xs = Single:xs
abbr (x:y:ys) xs
  | x == y = abbr ys (Twin:xs)
  | x /= y = abbr (y:ys) (Single:xs)

(*->) :: Arrange -> Arrange -> Integer
pre *-> cur
  | pre == Twin && cur == Twin = 3
  | pre == Twin && cur == Single = 1
  | pre == Single && cur == Twin = 2
  | otherwise = 2
infixl 7 *->

solve :: [Arrange] -> Arrange -> Integer
solve [] _ = 1
solve (cur:xs) pre = pre *-> cur * (solve xs cur) `mod` prime

main = do
  getLine
  getLine
  str <- getLine
  let (x:xs) = reverse $ abbr str []
  case xs of
    [] -> print 3
    _ -> print $ (if x == Twin then 6 else 3) * solve xs x `mod` prime

Score : 400 points

Problem Statement

We have a board with a 2 \times N grid.
Snuke covered the board with N dominoes without overlaps.
Here, a domino can cover a 1 \times 2 or 2 \times 1 square.

Then, Snuke decided to paint these dominoes using three colors: red, cyan and green.
Two dominoes that are adjacent by side should be painted by different colors.
Here, it is not always necessary to use all three colors.

Find the number of such ways to paint the dominoes, modulo 1000000007.

The arrangement of the dominoes is given to you as two strings S_1 and S_2 in the following manner:

Each domino is represented by a different English letter (lowercase or uppercase).

The j-th character in S_i represents the domino that occupies the square at the i-th row from the top and j-th column from the left.

Constraints

1 \leq N \leq 52

|S_1| = |S_2| = N

S_1 and S_2 consist of lowercase and uppercase English letters.

S_1 and S_2 represent a valid arrangement of dominoes.

Input

Input is given from Standard Input in the following format:

N
S_1
S_2

Output

Print the number of such ways to paint the dominoes, modulo 1000000007.

Sample Input 1

3
aab
ccb

Sample Output 1

6

There are six ways as shown below:

Sample Input 2

1
Z
Z

Sample Output 2

3

Note that it is not always necessary to use all the colors.

Sample Input 3

52
RvvttdWIyyPPQFFZZssffEEkkaSSDKqcibbeYrhAljCCGGJppHHn
RLLwwdWIxxNNQUUXXVVMMooBBaggDKqcimmeYrhAljOOTTJuuzzn

Sample Output 3

958681902


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

--------------------------------------------------------------------------
solve [] _ = 0
solve ((a,b):xs) acc
    | acc == 0 && b >= 4 = a * a
    | acc == 0 && b >= 2 = solve xs a
    | acc /= 0 && b >= 2 = a * acc
    | otherwise = solve xs acc

main = do
    n <- int
    xs <- sort <$> sLineToIntL
    let ys = sortBy (flip compare) $ map (\ys -> (head ys, length ys)) $ group xs
    print $ solve ys 0
--------------------------------------------------------------------------

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

Score : 300 points

Problem Statement

We have N sticks with negligible thickness.
The length of the i-th stick is A_i.

Snuke wants to select four different sticks from these sticks and form a rectangle (including a square), using the sticks as its sides.
Find the maximum possible area of the rectangle.

Constraints

4 \leq N \leq 10^5

1 \leq A_i \leq 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible area of the rectangle.
If no rectangle can be formed, print 0.

Sample Input 1

6
3 1 2 4 2 1

Sample Output 1

2

1 \times 2 rectangle can be formed.

Sample Input 2

4
1 2 3 4

Sample Output 2

0

No rectangle can be formed.

Sample Input 3

10
3 3 3 3 4 4 4 5 5 5

Sample Output 3

20