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

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

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

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

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

main = do
	n <- readInt
	k <- readInt
	as <- map ( \a -> [a] ) <$> readInts
	print . ( * 2 ) . sum . map minimum . map ( [ id, ( k - ) ] <*> ) $ as


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

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

Submitted source-code file size, in bytes.

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

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


main = do
  n <- getLine
  putStrLn $ eval n

eval s = if any (== '9') s 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


main :: IO ()
main = getLine >>= putStrLn . solve

solve :: String -> String
solve (x : xs)
    | x == '9' = "Yes"
    | otherwise = solve xs
solve _ = "No"


import Control.Monad
import Data.List

main = do
    n <- readLn
    nums <- replicateM n getLine
    print $ length $ filter odd $ map length $ group . sort $ nums

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 Data.List
main=do
    ctx<-getContents
    print $ length $ dup $ sort [read x::Int|x<-tail (lines ctx)]
dup :: [Int]->[Int]
dup []=[]
dup (x:y:xs)=if x==y then dup (xs) else x:dup (y:xs)
dup (x:[]) = [x]


import qualified Data.IntSet as S

main = do
  getLine
  ns <- map read . words <$> getContents
  print (we ns)

we = S.size . foldl (\s n -> if S.member n s then S.delete n s else S.insert n s) S.empty


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^5 + 1) :: IO Memo
  foldM memoize edge input
  let index = [(i, j, k) | i <- [1..n], j <- [1..n], k <- [1..n], i /= j]
  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 (i, j, k) = 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)
  return =<< (+d) <$> readMemo memo (t:ts)

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


{-# LANGUAGE BangPatterns          #-}

import Control.Monad
import Control.Applicative
import Data.List as List
import Data.Set as Set

solve:: Int -> Int -> Int
solve x t
    | x >= t = x - t
    | otherwise = 0

main :: IO()
main = do
    [x, t] <- List.map read . words <$> getLine :: IO [Int]
    let s = solve x t
    print s

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


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

main = do
  (a : b : _) <- map (read :: String -> Int) . words <$> getLine
  print $ case a - b of
    n | n > 0     -> n
      | otherwise -> 0


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

extract (n1 : n2 : ns) = n1 : extract ns
extract _              = []

main = extract <$> getLine >>= putStrLn

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 Data.List
main = putStrLn . map snd . filter (odd . fst) . zip [1..] =<< getLine


{-# OPTIONS_GHC -O #-}

import Control.Monad
import Data.List
import Data.Ord
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.IntMap as M

readIntLL :: IO [[Int]]
readIntLL = map(unfoldr(B.readInt.B.dropWhile(==' '))).B.lines<$>B.getContents

rsort :: Ord a => [a] -> [a]
rsort = sortBy$flip compare

main=do
    n:as <- readIntLL
    print $ maximum $ map snd $ M.toList
        $ foldl' (\m k -> M.insertWith (+) (k-1) 1 $ M.insertWith (+) (k+1) 1 $ M.insertWith (+) k 1 m) M.empty
        $ head as

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


module Main where

import Data.List

main :: IO()
main = do
  _ <- getLine
  inputs <- map read . words <$> getLine
  print $ solve inputs

solve :: [Integer] -> Integer
solve = maximum . posibilities . allLists

allLists :: [Integer] -> [[Integer]]
allLists inputs = map (zipWith (+) inputs) adds where
  adds :: [[Integer]]
  adds = sub (length inputs) where
    sub 0 = [[]]
    sub n = concatMap (\l -> [1 : l, 0 : l, -1 : l]) $ sub (n - 1)

posibilities :: [[Integer]] -> [Integer]
posibilities = map (fromIntegral . maximum . map length . group . sort)


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

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

readInts :: B.ByteString -> [Int]
readInts = map readInt . B.words

main = do
  getLine
  as <- readInts <$> B.getLine
  print (together as)

together as = succ $ maximum $ (0:) $ map (length . takeWhile (<=2) . scanl1 (+)) $ collectBy (\x y -> x<2&&y<2) ds
  where
    sas = sort as
    ds = zipWith (-) (tail sas) sas

collectBy _ [] = []
collectBy op [x] = [[x]]
collectBy op (x1:x2:xs)
  | op x1 x2 = let (g:gs) = collectBy op (x2:xs) in (x1:g) : gs
  | otherwise = collectBy op (x2:xs)


import Data.List

chunksOf :: Int -> [a] -> [[a]]
chunksOf n = takeWhile (not . null) . unfoldr (return . splitAt n)

main = do
  getLine
  ps <- map read . words <$> getLine
  print (der ps)

der = sum . map (\[x,y] -> y-x) . chunksOf 2 . map fst . filter (uncurry (==)) . zip [1..]

Score : 400 points

Problem Statement

You are given a permutation p_1,p_2,...,p_N consisting of 1,2,..,N.
You can perform the following operation any number of times (possibly zero):

Operation: Swap two adjacent elements in the permutation.

You want to have p_i ≠ i for all 1≤i≤N.
Find the minimum required number of operations to achieve this.

Constraints

2≤N≤10^5

p_1,p_2,..,p_N is a permutation of 1,2,..,N.

Input

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

N
p_1 p_2 .. p_N

Output

Print the minimum required number of operations

Sample Input 1

5
1 4 3 5 2

Sample Output 1

2

Swap 1 and 4, then swap 1 and 3. p is now 4,3,1,5,2 and satisfies the condition.
This is the minimum possible number, so the answer is 2.

Sample Input 2

2
1 2

Sample Output 2

1

Swapping 1 and 2 satisfies the condition.

Sample Input 3

2
2 1

Sample Output 3

0

The condition is already satisfied initially.

Sample Input 4

9
1 2 4 9 5 8 7 3 6

Sample Output 4

3


{-# LANGUAGE ScopedTypeVariables #-}
-- extension section
{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE CPP               #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections     #-}
-- not supported extension
--{-# LANGUAGE Strict, StrictData #-}

module Main where

-- @@@@@@@@@@@@@@@@@--
-- import section   --
-- @@@@@@@@@@@@@@@@@--
--    import A.B.C( function name )  ...
-- or import A.B.C

--
import           Prelude hiding(
  getLine,
  getContents,
  lines,
  words
  )

-- standard library
import           Control.Monad.ST
import           Control.Applicative
import           Data.Char
import           Data.Ratio

-- bytestring
import qualified Data.ByteString.Char8       as B
import qualified Data.ByteString.Unsafe      as B

-- containers
import           Data.Set

-- deepseq

-- regex-posix

-- text
import           Data.Text.Lazy.IO as TIO
import           Data.Text.Lazy as T
import           Data.Text.Lazy.Read as TR

-- import Data.Text.IO as TIO
-- import Data.Text as T
-- import Data.Text.Read as TR

-- unordered-containers

-- vectors
import qualified Data.Vector as V
import           Data.Vector.Unboxed as UV
import           Data.Vector.Unboxed.Mutable as MV

-- mtl

-- @@@@@@@@@@@@@@@@@--
-- main section     --
-- @@@@@@@@@@@@@@@@@--

main :: IO ()
main = do
  input <- getInput
  Prelude.putStr . show . getAnswer $ input

-- main :: IO()
-- main = do
--   answer <- getInputandanser
--   putStr . show $ answer

-- @@@@@@@@@@@@@@@@@@@@@--
-- I/O DataType section --
-- @@@@@@@@@@@@@@@@@@@@@--
data Input = I (Int, UV.Vector (Int, Int) )
  deriving(Show)

type Answer = Int

-- @@@@@@@@@@@@@@@@@--
-- answerSection    --
-- @@@@@@@@@@@@@@@@@--
getInput :: IO Input
getInput = do
  n <- (UV.!0) <$> intVectorFromLine 1
  input <- generatePairVectorFromLine n
  return $ I (n , input)

getAnswer :: Input -> Answer
getAnswer (I (n, v)) | n == 1 = 0
                     | otherwise =  ( ( 2^n )- ( 1 + n + res  ) )
  where res =  go 0 1 0 Data.Set.empty
        go !i1 !i2 !accum' !lset
          | i1 == n-2 && i2 == n-1 = (  (accum'+ dScore))
          | i2 == n-1 = go (i1+1) (i1+2) (  (accum'+ dScore))  ( ins l )
          | otherwise = go i1 (i2+1) (   (accum'+ dScore))  (ins l)
          where l = lineFromPoint n1 n2
                dScore | l `member` lset = 0
                       | otherwise = 2^k - k - 1
                (k:: Int) = case l of
                  L (True,_,_,_,_) -> (1+). UV.length .UV.filter  ( == True) $ UV.map ( (l==) . (lineFromPoint n1)) ( v :: UV.Vector (Int,Int) )
                  L (False,_,_,_,_) -> UV.length .UV.filter  ( == True) $ UV.map ( (l==) . (lineFromPoint n1)) ( v :: UV.Vector (Int,Int) )
                n1 = v UV.! i1
                n2 = v UV.! i2
                ins = flip insert lset

-- getAnswer :: Input -> Answer
-- getAnswer (I (n, v)) | n == 1 = 0
--                      | otherwise = m' ( (m' 2^n + 998244353)- (m' $ 1 + n + res  ) )
--   where res =  go 0 1 0 Data.Set.empty
--         go !i1 !i2 !accum' !lset
--           | i1 == n-2 && i2 == n-1 = ( m' (accum'+ dScore))
--           | i2 == n-1 = go (i1+1) (i1+2) ( m' (accum'+ dScore))  ( ins l )
--           | otherwise = go i1 (i2+1) (  m' (accum'+ dScore))  (ins l)
--           where l = lineFromPoint n1 n2
--                 dScore | l `member` lset = 0
--                        | otherwise = 2^k - k - 1
--                 (k:: Int) = case l of
--                   L (True,_,_,_,_) -> (1+). UV.length .UV.filter  ( == True) $ UV.map ( (l==) . (lineFromPoint n1)) ( v :: UV.Vector (Int,Int) )
--                   L (False,_,_,_,_) -> UV.length .UV.filter  ( == True) $ UV.map ( (l==) . (lineFromPoint n1)) ( v :: UV.Vector (Int,Int) )
--                 n1 = v UV.! i1
--                 n2 = v UV.! i2
--                 ins = flip insert lset

getInputAndAnser :: IO Answer
getInputAndAnser = undefined

-- @@@@@@@@@@@@@@@@@@@@@@@@@@--
-- question unique section    --
-- @@@@@@@@@@@@@@@@@@@@@@@@@@--

newtype Line = L (Bool, Int,Int,Int,Int)
  deriving(Show)

instance Eq Line where
  (==) (L (False,x,_,_,_)) (L (False,x',_,_,_)) = x == x'
  (==) (L (True,a,a',b,b')) (L (True,aa,aa',bb,bb')) = Prelude.and [ a==aa,a'==aa',b==bb,b'==bb']
  (==) _ _ = False

instance Ord Line where
  compare (L (False,_,_,_,_)) (L (True,_,_,_,_)) = GT
  compare (L (True,_,_,_,_)) (L (False,_,_,_,_)) = LT
  compare (L (False,x,_,_,_)) (L (False,x',_,_,_)) = compare x x'
  compare l l' = compare ab ab'
    where coefficient (L ( True, x,y,z,a) ) = (x,y,z,a)
          ab = coefficient l
          ab' = coefficient l'

lineFromPoint :: (Int,Int) -> (Int,Int) -> Line
lineFromPoint (x0,y0) (x1,y1)
  | x0 /= x1 =
    L ( True , divA, divA' , divB, divB')
  | otherwise = L (False,x0,minBound,minBound,minBound)
  where a = y1-y0
        a' = x1-x0
        b = (x1-x0)*y0 - (y1-y0)*x0
        b' = x1-x0
        factorA = gcd a a'
        factorB = gcd b b'
        (divA, divA') | a >= 0 && a' >= 0 = (a `div` factorA ,a `div` factorA)
                      | a < 0 && a' >= 0 = (a `div` factorA ,a `div` factorA)
                      | a >= 0 && a' < 0 = (-1 * a `div` factorA ,-1 * a `div` factorA)
                      | a <  0 && a' < 0 = (-1 * a `div` factorA ,-1 * a `div` factorA)
        (divB, divB') | b >= 0 && b' >= 0 = (b `div` factorB ,b `div` factorB)
                      | b < 0 && b' >= 0 = (b `div` factorB ,b `div` factorB)
                      | b >= 0 && b' < 0 = (-1 * b `div` factorB ,-1 * b `div` factorB)
                      | b <  0 && b' < 0 = (-1 * b `div` factorB ,-1 * b `div` factorB)

m' :: Int -> Int
m' i = i `mod`998244353

-- @@@@@@@@@@@@@@@@@--
-- util section     --
-- @@@@@@@@@@@@@@@@@--

-- standard Input Function
gLine :: IO Text
gLine = getLine

gContents :: IO Text
gContents = getContents

-- intVectorFromline 5  ("1 2 3 4 5") -> vector <1,2,3,4,5>
intVectorFromLine ::Int -> IO ( Vector Int )
intVectorFromLine n = UV.unfoldrN n (B.readInt.B.dropWhile isSpace) <$> B.getLine

pairFromLine :: IO (Int,Int)
pairFromLine = do
  v <- intVectorFromLine 2
  return ( v ! 0, v ! 1)

generatePairVectorFromLine :: Int -> IO ( Vector (Int, Int) )
generatePairVectorFromLine n = generateM n (const pairFromLine)

Score : 700 points

Problem Statement

You are given N points (x_i,y_i) located on a two-dimensional plane.
Consider a subset S of the N points that forms a convex polygon.
Here, we say a set of points S forms a convex polygon when there exists a convex polygon with a positive area that has the same set of vertices as S. All the interior angles of the polygon must be strictly less than 180°.

For example, in the figure above, {A,C,E} and {B,D,E} form convex polygons; {A,C,D,E}, {A,B,C,E}, {A,B,C}, {D,E} and {} do not.

For a given set S, let n be the number of the points among the N points that are inside the convex hull of S (including the boundary and vertices). Then, we will define the score of S as 2^{n-|S|}.

Compute the scores of all possible sets S that form convex polygons, and find the sum of all those scores.

However, since the sum can be extremely large, print the sum modulo 998244353.

Constraints

1≤N≤200

0≤x_i,y_i<10^4 (1≤i≤N)

If i≠j, x_i≠x_j or y_i≠y_j.

x_i and y_i are integers.

Input

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

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the sum of all the scores modulo 998244353.

Sample Input 1

4
0 0
0 1
1 0
1 1

Sample Output 1

5

We have five possible sets as S, four sets that form triangles and one set that forms a square. Each of them has a score of 2^0=1, so the answer is 5.

Sample Input 2

5
0 0
0 1
0 2
0 3
1 1

Sample Output 2

11

We have three "triangles" with a score of 1 each, two "triangles" with a score of 2 each, and one "triangle" with a score of 4. Thus, the answer is 11.

Sample Input 3

1
3141 2718

Sample Output 3

0

There are no possible set as S, so the answer is 0.


{-# LANGUAGE ScopedTypeVariables #-}
-- extension section
{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE CPP               #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections     #-}
-- not supported extension
--{-# LANGUAGE Strict, StrictData #-}

module Main where

-- @@@@@@@@@@@@@@@@@--
-- import section   --
-- @@@@@@@@@@@@@@@@@--
--    import A.B.C( function name )  ...
-- or import A.B.C

--
import           Prelude hiding(
  getLine,
  getContents,
  lines,
  words
  )

-- standard library
import           Control.Monad.ST
import           Control.Applicative
import           Data.Char
import           Data.Ratio

-- bytestring
import qualified Data.ByteString.Char8       as B
import qualified Data.ByteString.Unsafe      as B

-- containers
import           Data.Set

-- deepseq

-- regex-posix

-- text
import           Data.Text.Lazy.IO as TIO
import           Data.Text.Lazy as T
import           Data.Text.Lazy.Read as TR

-- import Data.Text.IO as TIO
-- import Data.Text as T
-- import Data.Text.Read as TR

-- unordered-containers

-- vectors
import qualified Data.Vector as V
import           Data.Vector.Unboxed as UV
import           Data.Vector.Unboxed.Mutable as MV

-- mtl

-- @@@@@@@@@@@@@@@@@--
-- main section     --
-- @@@@@@@@@@@@@@@@@--

main :: IO ()
main = do
  input <- getInput
  Prelude.putStr . show . getAnswer $ input

-- main :: IO()
-- main = do
--   answer <- getInputandanser
--   putStr . show $ answer

-- @@@@@@@@@@@@@@@@@@@@@--
-- I/O DataType section --
-- @@@@@@@@@@@@@@@@@@@@@--
data Input = I (Int, UV.Vector (Int, Int) )
  deriving(Show)

type Answer = Int

-- @@@@@@@@@@@@@@@@@--
-- answerSection    --
-- @@@@@@@@@@@@@@@@@--
getInput :: IO Input
getInput = do
  n <- (UV.!0) <$> intVectorFromLine 1
  input <- generatePairVectorFromLine n
  return $ I (n , input)

getAnswer :: Input -> Answer
getAnswer (I (n, v)) | n == 1 = 0
                     | otherwise = m' ( (m' 2^n + 998244353)- (m' $ 1 + n + res  ) )
  where res =  go 0 1 0 Data.Set.empty
        go !i1 !i2 !accum' !lset
          | i1 == n-2 && i2 == n-1 = ( m' (accum'+ dScore))
          | i2 == n-1 = go (i1+1) (i1+2) ( m' (accum'+ dScore))  ( ins l )
          | otherwise = go i1 (i2+1) (  m' (accum'+ dScore))  (ins l)
          where l = lineFromPoint n1 n2
                dScore | l `member` lset = 0
                       | otherwise = 2^k - k - 1
                (k:: Int) = case l of
                  L (True,_,_,_,_) -> (1+). UV.length .UV.filter  ( == True) $ UV.map ( (l==) . (lineFromPoint n1)) ( v :: UV.Vector (Int,Int) )
                  L (False,_,_,_,_) -> UV.length .UV.filter  ( == True) $ UV.map ( (l==) . (lineFromPoint n1)) ( v :: UV.Vector (Int,Int) )
                n1 = v UV.! i1
                n2 = v UV.! i2
                ins = flip insert lset

getInputAndAnser :: IO Answer
getInputAndAnser = undefined

-- @@@@@@@@@@@@@@@@@@@@@@@@@@--
-- question unique section    --
-- @@@@@@@@@@@@@@@@@@@@@@@@@@--

newtype Line = L (Bool, Int,Int,Int,Int)
  deriving(Show,Ord)

instance Eq Line where
  (==) (L (False,x,_,_,_)) (L (False,x',_,_,_)) = x == x'
  (==) (L (True,a,a',b,b')) (L (True,aa,aa',bb,bb')) = Prelude.and [ a==aa,a'==aa',b==bb,b'==bb']
  (==) _ _ = False

lineFromPoint :: (Int,Int) -> (Int,Int) -> Line
lineFromPoint (x0,y0) (x1,y1)
  | x0 /= x1 =
    L ( True , divA, divA' , divB, divB')
  | otherwise = L (False,x0,minBound,minBound,minBound)
  where a = y1-y0
        a' = x1-x0
        b = (x1-x0)*y0 - (y1-y0)*x0
        b' = x1-x0
        factorA = gcd a a'
        factorB = gcd b b'
        (divA, divA') | a >= 0 && a' >= 0 = (a `div` factorA ,a `div` factorA)
                      | a < 0 && a' >= 0 = (a `div` factorA ,a `div` factorA)
                      | a >= 0 && a' < 0 = (-1 * a `div` factorA ,-1 * a `div` factorA)
                      | a <  0 && a' < 0 = (-1 * a `div` factorA ,-1 * a `div` factorA)
        (divB, divB') | b >= 0 && b' >= 0 = (b `div` factorB ,b `div` factorB)
                      | b < 0 && b' >= 0 = (b `div` factorB ,b `div` factorB)
                      | b >= 0 && b' < 0 = (-1 * b `div` factorB ,-1 * b `div` factorB)
                      | b <  0 && b' < 0 = (-1 * b `div` factorB ,-1 * b `div` factorB)

m' :: Int -> Int
m' i = i `mod`998244353

-- @@@@@@@@@@@@@@@@@--
-- util section     --
-- @@@@@@@@@@@@@@@@@--

-- standard Input Function
gLine :: IO Text
gLine = getLine

gContents :: IO Text
gContents = getContents

-- intVectorFromline 5  ("1 2 3 4 5") -> vector <1,2,3,4,5>
intVectorFromLine ::Int -> IO ( Vector Int )
intVectorFromLine n = UV.unfoldrN n (B.readInt.B.dropWhile isSpace) <$> B.getLine

pairFromLine :: IO (Int,Int)
pairFromLine = do
  v <- intVectorFromLine 2
  return ( v ! 0, v ! 1)

generatePairVectorFromLine :: Int -> IO ( Vector (Int, Int) )
generatePairVectorFromLine n = generateM n (const pairFromLine)


main = getContents >>= print.f.map read.words
f[q,h,s,d,n]
    | even n = div n 2 * y
    | otherwise = min (n * x) $ x + div n 2 * y
  where
    x = minimum xs
    y = minimum ys
    xs = [4*q, 2*h, s]
    ys = [8*q, 4*h, 2*s, d]

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
import Data.Ord

takePairs []  = []
takePairs [_] = []
takePairs (a:b:xs)
  | a == b = a : takePairs xs
  | otherwise = takePairs (b:xs)

main :: IO ()
main = do
    n <- readLn :: IO Int
    a <- map read . words <$> getLine :: IO [Int]
    let a' = takePairs . concat
           . filter ((2<=) . length) . group . sortOn Down $ a
    print $ if length a' < 2
               then 0 else product $ take 2 a'

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


import Data.List

f :: Integral a => [a] -> a -> a
f [] _ = 0
f [_] _ = 0
f (x:y:xs) cur
  | x == y && cur == 0 = f xs x
  | x == y && cur /= 0 = x * cur
  | otherwise = f (y:xs) cur

main = do
  getLine
  nums <- reverse . sort . map read . words <$> getLine :: IO [Integer]
  print $ f nums 0


import qualified Data.Map as M

main = do
  getLine
  as <- map read . words <$> getLine
  print . h . M.toDescList $ f M.empty as

f m [] = M.filter (> 0) $ M.map g m
f m (a:as) = M.insertWith (const succ) a 1 (f m as)

g a
  | a >= 4 = 2
  | a >= 2 = 1
  | otherwise = 0

h ((k, v):(k', _):_)
  | v == 2 = k * k
  | otherwise = k * k'
h _ = 0


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

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 CPP #-}
#define MOD (1000000007 :: Integer)
import Prelude hiding (mod)

mod :: Integer -> Integer -> Integer
mod x y
  | x >= y    = mod (x - y) y
  | otherwise = x

calc' :: String -> Integer
calc' [x] = 3
calc' [x,y] = 6
calc' (x:y:xs)
  | x == y  = 6 * calc (x:y:xs)
  | x /= y  = 3 * calc (x:y:xs)

calc :: String -> Integer
calc [x,y]
  | x == y = 1
  | x /= y = 2
calc [x,y,z]
  | x == y    = 1
  | y == z    = 2
  | otherwise = 4
calc (x:y:z:w:xs)
  | x == y && z == w  = (3 * calc(z:w:xs)) `mod` MOD
  | x == y && z /= w  = calc(z:w:xs) `mod` MOD
  | x /= y            = (2 * calc(y:z:w:xs)) `mod` MOD

main :: IO ()
main = do
  getLine
  str <- getLine
  getLine
  putStrLn . show . calc' $ str


import Control.Applicative
import Control.Monad.State.Lazy
import qualified Data.Map.Lazy as M
import Data.Monoid
import Data.List

data Subsequence = Subsequence
    { str :: String
    , indicies :: [Int] } deriving Show

emptySubseq :: Subsequence
emptySubseq = Subsequence "" []

allStrings :: [String] -> [String]
allStrings alphabet =  alphabet <> ((++) <$> allStrings alphabet <*> alphabet)

dict = allStrings $ map (: []) ['a'..'z']

{-
insertAndReturnSeqIdx :: Int -> [Int] -> Int -> ([Int], Int)
insertAndReturnSeqIdx i [] a = ([i], a)
insertAndReturnSeqIdx i ix a
    | i < head ix = (i : ix, a)
    | not $ null ix = let
        (res, newA) = insertAndReturnSeqIdx i (tail ix) (a + 1) in
        (head ix : res, newA)
    | null ix = ([i], a)

-- recurrence relation between subsequences
-- TODO: Tabulation
reccur :: V.Vector Char -> Subsequence -> Int -> Subsequence
reccur input prevSeq idx = Subsequence newStr newIndicies
      where (newIndicies, seqIdx) =
                insertAndReturnSeqIdx idx (indicies prevSeq) 0
            (front, end) = splitAt seqIdx $ str prevSeq
            newStr = front ++ ((input V.! idx) : end)

isSubseq Subsequence sx =
-}

{-
search :: V.Vector Char -> String -> Either String Int
search input target = do
    let limit = length target
    let inputLen = V.length input
    map
-}

betterIsSubsequenceOf :: String -> String -> State (M.Map String Bool) Bool
betterIsSubsequenceOf part all = do
    hm <- get
    let res = M.lookup part hm
    case res of
        Nothing -> do
            let newMap = M.insert part res
            return $ isSubsequenceOf part all
        Just s -> return s

search :: String -> [String] -> State (M.Map String Bool) String
search input dict = do
    isSubsequence <- betterIsSubsequenceOf (head dict) input
    if isSubsequence then
        search input (tail dict)
    else
        return $ head dict

{-
solve :: V.Vector Char -> Int
solve input =
-}

main = do
    --input <- V.fromList <$> getLine
    input <- getLine
    let res = evalState (search input dict) M.empty
    putStrLn res

Score : 600 points

Problem Statement

A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters.
For example, arc, artistic and (an empty string) are all subsequences of artistic; abc and ci are not.

You are given a string A consisting of lowercase English letters.
Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A.
If there are more than one such string, find the lexicographically smallest one among them.

Constraints

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

A consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

A

Output

Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.

Sample Input 1

atcoderregularcontest

Sample Output 1

b

The string atcoderregularcontest contains a as a subsequence, but not b.

Sample Input 2

abcdefghijklmnopqrstuvwxyz

Sample Output 2

aa

Sample Input 3

frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn

Sample Output 3

aca


main :: IO()
main = do
  [a,b,c,d] <- map read . words <$> getLine
  print (max ((min b d)-(max a c)) 0 )

Score : 200 points

Problem Statement

Alice and Bob are controlling a robot. They each have one switch that controls the robot.

Alice started holding down her button A second after the start-up of the robot, and released her button B second after the start-up.

Bob started holding down his button C second after the start-up, and released his button D second after the start-up.

For how many seconds both Alice and Bob were holding down their buttons?

Constraints

0≤A<B≤100

0≤C<D≤100

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the length of the duration (in seconds) in which both Alice and Bob were holding down their buttons.

Sample Input 1

0 75 25 100

Sample Output 1

50

Alice started holding down her button 0 second after the start-up of the robot, and released her button 75 second after the start-up.

Bob started holding down his button 25 second after the start-up, and released his button 100 second after the start-up.

Therefore, the time when both of them were holding down their buttons, is the 50 seconds from 25 seconds after the start-up to 75 seconds after the start-up.

Sample Input 2

0 33 66 99

Sample Output 2

0

Alice and Bob were not holding their buttons at the same time, so the answer is zero seconds.

Sample Input 3

10 90 20 80

Sample Output 3

60


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

main = do
  [a, b, c, d] <- map (read::String -> Int) . words <$> getLine
  print $ if b <= c || a >= d then 0 else (min b d) - (max a c)


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

solve (a:b:c:d:_) = max ((min b d) - (max a c)) 0


main=tail.map read.lines<$>getContents>>=print.(foldl lcm 1)

Score : 300 points

Problem Statement

We have N clocks. The hand of the i-th clock (1≤i≤N) rotates through 360° in exactly T_i seconds.

Initially, the hand of every clock stands still, pointing directly upward.

Now, Dolphin starts all the clocks simultaneously.

In how many seconds will the hand of every clock point directly upward again?

Constraints

1≤N≤100

1≤T_i≤10^{18}

All input values are integers.

The correct answer is at most 10^{18} seconds.

Input

Input is given from Standard Input in the following format:

N
T_1
:
T_N

Output

Print the number of seconds after which the hand of every clock point directly upward again.

Sample Input 1

2
2
3

Sample Output 1

6

We have two clocks. The time when the hand of each clock points upward is as follows:

Clock 1: 2, 4, 6, ... seconds after the beginning

Clock 2: 3, 6, 9, ... seconds after the beginning

Therefore, it takes 6 seconds until the hands of both clocks point directly upward.

Sample Input 2

5
2
5
10
1000000000000000000
1000000000000000000

Sample Output 2

1000000000000000000


import Data.Bits
import Data.List
import Data.Foldable(foldlM)
import Data.Maybe(fromJust)
import Control.Monad
import Data.Array as A ((!),accumArray)
import Data.Graph
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as VM
import Control.Monad.ST
import Data.Maybe (fromMaybe)
import qualified Data.ByteString.Char8 as BS

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

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

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

getLineB :: (Read a) => IO [a] --直接入力
getLineB = map (read.BS.unpack) . BS.words <$> BS.getLine

build :: Int -> Int -> [(Int,(Int,Int))] -> V.Vector Int
build s n ls = runST $ do
  vec <- VM.replicate (n+1) maxBound
  VM.write vec s 0
  sub vec s 0
  V.freeze vec
  where
    graph = A.accumArray (flip (:)) [] (1,n) ls
    sub vec s par = do
      forM_ (graph A.! s) $ \(vw,v) -> do
        d  <- VM.read vec v
        sd <- VM.read vec s
        if d > sd + vw && v /= par then VM.write vec v (sd+vw)
          else return ()
      --V.freeze vec >>= \vec -> traceShowM (graph A.! s, vec)
      forM_ (graph A.! s) $ \(_,v) -> if v == par then return () else sub vec v s

solve :: Int -> V.Vector Int -> IO ()
solve q vec = do
  replicateM_ q $ do
    [x,y] <- getIntList
    print $ (vec V.! x) + (vec V.! y)

main :: IO ()
main = do
  n <- readLn :: IO Int
  as <- fmap concat $ replicateM (n-1) $ do
    [a,b,c] <- getIntList
    return [(a,(c,b)),(b,(c,a))]
  [q,k] <- getIntList
  solve q $ build k n as

Score : 400 points

Problem Statement

You are given a tree with N vertices.

Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.

The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.

You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):

find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.

Constraints

3≤N≤10^5

1≤a_i,b_i≤N (1≤i≤N-1)

1≤c_i≤10^9 (1≤i≤N-1)

The given graph is a tree.

1≤Q≤10^5

1≤K≤N

1≤x_j,y_j≤N (1≤j≤Q)

x_j≠y_j (1≤j≤Q)

x_j≠K,y_j≠K (1≤j≤Q)

Input

Input is given from Standard Input in the following format:

N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}

Output

Print the responses to the queries in Q lines.

In the j-th line j(1≤j≤Q), print the response to the j-th query.

Sample Input 1

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

Sample Output 1

3
2
4

The shortest paths for the three queries are as follows:

Query 1: Vertex 2 → Vertex 1 → Vertex 2 → Vertex 4 : Length 1+1+1=3

Query 2: Vertex 2 → Vertex 1 → Vertex 3 : Length 1+1=2

Query 3: Vertex 4 → Vertex 2 → Vertex 1 → Vertex 3 → Vertex 5 : Length 1+1+1+1=4

Sample Input 2

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

Sample Output 2

5
14
22

The path for each query must pass Vertex K=2.

Sample Input 3

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

Sample Output 3

17000000000


import Data.Maybe
import qualified Data.ByteString.Char8 as B
import qualified Data.Vector as V
import qualified Data.IntMap as IM
main=mapM_(mapM_ print.solve).analyze.map(map(fst.fromJust.B.readInt).B.words).B.lines=<<B.getContents
analyze([n]:cs)=(n,abcs,q,k,xys):analyze rs where
  (abcs,[q,k]:qs)=splitAt(n-1)cs
  (xys,rs)=splitAt q qs
analyze []=[]
solve(n,abcs,q,k,xys)=map(\[x,y]->d IM.! x+d IM.! y)xys where
  g=V.accum(flip(:))(V.replicate(n+1)[])$concatMap(\[a,b,c]->[(a,(b,c)),(b,(a,c))])abcs
  d=f(IM.empty)k(-1)0
  f m t s c=foldr(\(i,d)m->if i==s then m else f m i t(c+d))(IM.insert t c m)$g V.! t where


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

Score : 100 points

Problem Statement

In K-city, there are n streets running east-west, and m streets running north-south. Each street running east-west and each street running north-south cross each other. We will call the smallest area that is surrounded by four streets a block. How many blocks there are in K-city?

Constraints

2 ≤ n, m ≤ 100

Input

Input is given from Standard Input in the following format:

n m

Output

Print the number of blocks in K-city.

Sample Input 1

3 4

Sample Output 1

6

There are six blocks, as shown below:

Sample Input 2

2 2

Sample Output 2

1

There are one block, as shown below:


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


module Main where
    import Data.List
    import Control.Monad

    main = do
        {-
        n <- getLine
        lines<-getLines (read n ::Int)
        -}
        inputs<-getInputs
        print ( foldr (*) 1 (map pred inputs))

    read' s = read s ::Integer

    getInputs = do
        line <- getLine
        let inputs = map read' (words line)
        return inputs

    getLines n = do
        lines <- (replicateM n getLine)
        return lines

    getGCD::Integer->Integer->Integer
    getGCD m n
        | m < n = (getGCD n m)
        | n == 0 = m
        | otherwise = getGCD (mod m n) n

    getLCM::Integer->Integer->Integer
    getLCM m n = div (m * n) (getGCD m n)


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

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

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

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

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

main = do
	[ h, w ] <- readInts
	print $ ( h - 1 ) * ( w - 1 )


i18n :: [Char] -> [Char]
i18n s = [head s] ++ show ((length s) - 2) ++ [last s]

main = do
  s <- getLine
  let s' = i18n s
  putStrLn s'

Score : 200 points

Problem Statement

The word internationalization is sometimes abbreviated to i18n.
This comes from the fact that there are 18 letters between the first i and the last n.

You are given a string s of length at least 3 consisting of lowercase English letters.
Abbreviate s in the same way.

Constraints

3 ≤ |s| ≤ 100 (|s| denotes the length of s.)

s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

Print the abbreviation of s.

Sample Input 1

internationalization

Sample Output 1

i18n

Sample Input 2

smiles

Sample Output 2

s4s

Sample Input 3

xyz

Sample Output 3

x1z


main :: IO ()
f xs = [head xs] ++ show (length xs - 2) ++ [last xs]
main = getLine >>= putStrLn . f


module Main where

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

main :: IO ()
main = do
    ss <- getLine
    let ans = [head ss] ++ (show $ length ss - 2) ++ [last ss]
    putStrLn ans


main = putStrLn . (\s -> (head s) : (show $ length s - 2) ++ [last s]) =<< getLine


import Control.Applicative
main = do
    n <- getLine
    a <- map read . words <$> getLine
    putStrLn $ solve a
solve :: [Int] -> String
solve list = if judge tuple then "Yes" else "No"
    where tuple = count list

powerTwo :: Int -> Int -> Int
powerTwo n x = if r==0 then powerTwo (n+1) q else n
    where (q,r) = divMod x 2

count :: [Int] -> (Int,Int,Int)
count = foldl f (0,0,0)
    where f (x,y,z) n = case powerTwo 0 n of 0 -> (x+1,y,z)
                                             1 -> (x,y+1,z)
                                             _ -> (x,y,z+1)
judge :: (Int,Int,Int) -> Bool
judge (x,y,z) = if y>=1
                then x<=z
                else x<=z+1

Score : 400 points

Problem Statement

We have a sequence of length N, a = (a_1, a_2, ..., a_N).
Each a_i is a positive integer.

Snuke's objective is to permute the element in a so that the following condition is satisfied:

For each 1 ≤ i ≤ N - 1, the product of a_i and a_{i + 1} is a multiple of 4.

Determine whether Snuke can achieve his objective.

Constraints

2 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

If Snuke can achieve his objective, print Yes; otherwise, print No.

Sample Input 1

3
1 10 100

Sample Output 1

Yes

One solution is (1, 100, 10).

Sample Input 2

4
1 2 3 4

Sample Output 2

No

It is impossible to permute a so that the condition is satisfied.

Sample Input 3

3
1 4 1

Sample Output 3

Yes

The condition is already satisfied initially.

Sample Input 4

2
1 1

Sample Output 4

No

Sample Input 5

6
2 7 1 8 2 8

Sample Output 5

Yes


{-# OPTIONS_GHC -O #-}

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

readIntL :: IO [Int]
readIntL = unfoldr(B.readInt.B.dropWhile(==' '))<$>B.getContents

f (a,b,c) n
    | odd n = (a+1,b,c)
    | n `mod` 4 == 0 = (a,b,c+1)
    | True = (a,1,c)

main=do
    n <- readLn
    (a,b,c) <- foldl' f (0,0,0).take n <$> readIntL
    putStrLn $ if a+b <= c+1 then "Yes" else "No"


main :: IO ()
main = do
  n <- readLn :: IO Int
  as <- (map read . words) <$> getLine :: IO [Int]
  let mul4 = length $ filter (\a -> a `mod` 4 == 0) as
      mul2 = length $ filter (\a -> a `mod` 2 == 0 && a `mod` 4 /= 0) as
  putStrLn $ if n - 3 * mul4 - mul2 > 0 then "No" else "Yes"


-- Try AtCoder
-- author: Leonardone @ NEETSDKASU

main = putStrLn . solve . map read . tail . words =<< getContents

solve xs = if ans then "Yes" else "No" where
    (o, q, e) = foldl f (0, 0, 0) xs
    f (o, q, e) x | odd x        = (o + 1, q, e)
                  | mod x 4 == 0 = (o, q + 1, e)
                  | otherwise    = (o, q, e + 1)
    ans = (o == 0)
       || (q > 0 && e == 0 && q >= o - 1)
       || (q > 0 && e > 0 && q >= o)


main :: IO ()
main = do
  n <- getLine
  putStrLn $ "ABC" ++ n

Score : 100 points

Problem Statement

This contest, AtCoder Beginner Contest, is abbreviated as ABC.

When we refer to a specific round of ABC, a three-digit number is appended after ABC. For example, ABC680 is the 680th round of ABC.

What is the abbreviation for the N-th round of ABC? Write a program to output the answer.

Constraints

100 ≤ N ≤ 999

Input

Input is given from Standard Input in the following format:

N

Output

Print the abbreviation for the N-th round of ABC.

Sample Input 1

100

Sample Output 1

ABC100

The 100th round of ABC is ABC100.

Sample Input 2

425

Sample Output 2

ABC425

Sample Input 3

999

Sample Output 3

ABC999


import Data.List
import Data.Function
import Data.Bool

main = do
    [n,m] <- map read . words <$> getLine
    es <- tuplify . map read . words <$> getContents
    let fs = map snd $ filter ((==1) . fst) es
        ss = map fst $ filter ((==n) . snd) es
        cs = sort $ (fs ++ ss)
    putStrLn $ bool "IMPOSSIBLE" "POSSIBLE" . or $ zipWith (==) cs (drop 1 cs)

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

Score : 300 points

Problem Statement

In Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands.
For convenience, we will call them Island 1, Island 2, ..., Island N.

There are M kinds of regular boat services between these islands.
Each service connects two islands. The i-th service connects Island a_i and Island b_i.

Cat Snuke is on Island 1 now, and wants to go to Island N.
However, it turned out that there is no boat service from Island 1 to Island N, so he wants to know whether it is possible to go to Island N by using two boat services.

Help him.

Constraints

3 ≤ N ≤ 200 000

1 ≤ M ≤ 200 000

1 ≤ a_i < b_i ≤ N

(a_i, b_i) \neq (1, N)

If i \neq j, (a_i, b_i) \neq (a_j, b_j).

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

If it is possible to go to Island N by using two boat services, print POSSIBLE; otherwise, print IMPOSSIBLE.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

POSSIBLE

Sample Input 2

4 3
1 2
2 3
3 4

Sample Output 2

IMPOSSIBLE

You have to use three boat services to get to Island 4.

Sample Input 3

100000 1
1 99999

Sample Output 3

IMPOSSIBLE

Sample Input 4

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

Sample Output 4

POSSIBLE

You can get to Island 5 by using two boat services: Island 1 -> Island 4 -> Island 5.


import Control.Monad
import qualified Data.List as L

main = do
  [n, m] <- map read . words <$> getLine
  es <- map (map read . words) <$> replicateM m getLine
  putStr $ solve n es

solve n es
  | null $ L.intersect as bs = "IMPOSSIBLE"
  | otherwise = "POSSIBLE"
    where
    as = [ b | [a, b] <- es, a == 1]
    bs = [ a | [a, b] <- es, b == n]


main=map read.words<$>getLine>>=putStrLn.(\x->if(mod(product (x++[sum x]))3)==0 then"Possible"else"Impossible")

Score : 100 points

Problem Statement

Snuke is giving cookies to his three goats.

He has two cookie tins. One contains A cookies, and the other contains B cookies. He can thus give A cookies, B cookies or A+B cookies to his goats (he cannot open the tins).

Your task is to determine whether Snuke can give cookies to his three goats so that each of them can have the same number of cookies.

Constraints

1 \leq A,B \leq 100

Both A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If it is possible to give cookies so that each of the three goats can have the same number of cookies, print Possible; otherwise, print Impossible.

Sample Input 1

4 5

Sample Output 1

Possible

If Snuke gives nine cookies, each of the three goats can have three cookies.

Sample Input 2

1 1

Sample Output 2

Impossible

Since there are only two cookies, the three goats cannot have the same number of cookies no matter what Snuke gives to them.


import Data.List
import Data.Array

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

solve :: Int -> Int -> String
solve a b = if (mod a 3) == 0 || (mod b 3) == 0 || (mod (a+b) 3) == 0
            then "Possible"
            else "Impossible"


main = interact $ show . sol . map read . words

sol :: [Int] -> Int
sol (_:as) = f maxBound (sum as) as

f s _ [_]     = s
f s t (a:as)  = f s' t' as
  where
  s' = min s t'
  t' = t-2*a

Score : 300 points

Problem Statement

Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.

They will share these cards.
First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards.
Here, both Snuke and Raccoon have to take at least one card.

Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively.
They would like to minimize |x-y|.
Find the minimum possible value of |x-y|.

Constraints

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

-10^{9} \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 answer.

Sample Input 1

6
1 2 3 4 5 6

Sample Output 1

1

If Snuke takes four cards from the top, and Raccoon takes the remaining two cards, x=10, y=11, and thus |x-y|=1. This is the minimum possible value.

Sample Input 2

2
10 -10

Sample Output 2

20

Snuke can only take one card from the top, and Raccoon can only take the remaining one card. In this case, x=10, y=-10, and thus |x-y|=20.


import qualified Data.Vector.Unboxed as VU
import Data.ByteString.Char8 as B
import Data.Char
import Control.Monad

solve vec a b i
    | i == 1 = diff
    | otherwise = min diff (solve vec (a-v) (b+v) (i-1))
    where
        v = vec VU.! i
        diff = abs $ (a-v) - (b+v)

main = do
    n <- readLn :: IO Int
    xs <- VU.unfoldrN n (B.readInt . B.dropWhile isSpace) <$> B.getLine
    print $ solve xs (VU.sum xs) 0 (n-1)


import qualified Data.ByteString.Char8 as BS
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import Data.Char (isSpace)

main :: IO ()
main = do
  n <- readLn :: IO Int
  vec <- VU.unfoldrN n (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine :: IO (VU.Vector Int)
  let scan =  VU.init $ VU.tail $ VU.scanl (+) 0 vec
  print $ solve (VU.sum vec) scan

solve :: Int -> VU.Vector Int -> Int
solve s xs
  | VU.length xs == 1 = abs (s - 2*(VU.last xs))
  | otherwise = min (abs (s-2*(VU.head xs))) (solve s $ VU.tail xs)


import qualified Data.ByteString.Char8 as B
import Data.Maybe
main = print.solve.map(fst.fromJust.B.readInt).B.words=<<B.getContents
solve (_:as) = minimum.map(\x->abs$x+x-s).scanl1(+)$init as where s=sum as


import Data.Sequence

--戦略：両端からとっていく。値が小さい方を優先的にとらせる。
--シーケンスが空になったときの差を計算すればいい。

solver::Seq Int->(Int,Int)->Int
solver sq (x,y) =  if sq == empty then abs (x-y) else if x <= y then let a :< rest = viewl sq in solver rest (a+x,y)
                                                                else let rest :> b = viewr sq in solver rest (x,b+y)

main::IO()
main=do
  _<-getLine
  datc<-getLine
  let dat = map read (words datc)
  print (solver (fromList dat) (0,0))


import Control.Applicative
import Control.Monad
import Data.Array.IO

main = do
  [n,p] <- map read . words <$> getLine :: IO [Int]
  as <- map ((`mod` 2) . read) . words <$> getLine :: IO [Int]

  dp <- newArray ((0,0),(n,2)) 0 :: IO (IOArray (Int,Int) Integer)

  writeArray dp (0,0) 1
  forM_ (zip [1..n] as) $ \(i,a) -> do
    if even a then do
      writeArray dp (i,0) =<< (*2) <$> readArray dp (i-1,0)
      writeArray dp (i,1) =<< (*2) <$> readArray dp (i-1,1)
      else do
      writeArray dp (i,0) =<< (+) <$> readArray dp (i-1,0) <*> readArray dp (i-1,1)
      writeArray dp (i,1) =<< (+) <$> readArray dp (i-1,0) <*> readArray dp (i-1,1)

  print =<< readArray dp (n,p)

Score : 200 points

Problem Statement

There are N bags of biscuits. The i-th bag contains A_i biscuits.

Takaki will select some of these bags and eat all of the biscuits inside.
Here, it is also possible to select all or none of the bags.

He would like to select bags so that the total number of biscuits inside is congruent to P modulo 2.
How many such ways to select bags there are?

Constraints

1 \leq N \leq 50

P = 0 or 1

1 \leq A_i \leq 100

Input

Input is given from Standard Input in the following format:

N P
A_1 A_2 ... A_N

Output

Print the number of ways to select bags so that the total number of biscuits inside is congruent to P modulo 2.

Sample Input 1

2 0
1 3

Sample Output 1

2

There are two ways to select bags so that the total number of biscuits inside is congruent to 0 modulo 2:

Select neither bag. The total number of biscuits is 0.

Select both bags. The total number of biscuits is 4.

Sample Input 2

1 1
50

Sample Output 2

0

Sample Input 3

3 0
1 1 1

Sample Output 3

4

Two bags are distinguished even if they contain the same number of biscuits.

Sample Input 4

45 1
17 55 85 55 74 20 90 67 40 70 39 89 91 50 16 24 14 43 24 66 25 9 89 71 41 16 53 13 61 15 85 72 62 67 42 26 36 66 4 87 59 91 4 25 26

Sample Output 4

17592186044416


import Control.Applicative
import Data.Int

main = do
  [n,a,b,c,d] <- map read . words <$> getLine :: IO [Int64]

  putStrLn $ if (or [a + c*i - d*(n-1-i) <= b && b <= a + d*i - c*(n-1-i) | i <- [0..n-1]]) then "YES" else "NO"

Score : 400 points

Problem Statement

There are N squares in a row.
The leftmost square contains the integer A, and the rightmost contains the integer B. The other squares are empty.

Aohashi would like to fill the empty squares with integers so that the following condition is satisfied:

For any two adjacent squares, the (absolute) difference of the two integers in those squares is between C and D (inclusive).

As long as the condition is satisfied, it is allowed to use arbitrarily large or small integers to fill the squares.
Determine whether it is possible to fill the squares under the condition.

Constraints

3 \leq N \leq 500000

0 \leq A \leq 10^9

0 \leq B \leq 10^9

0 \leq C \leq D \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B C D

Output

Print YES if it is possible to fill the squares under the condition; print NO otherwise.

Sample Input 1

5 1 5 2 4

Sample Output 1

YES

For example, fill the squares with the following integers: 1, -1, 3, 7, 5, from left to right.

Sample Input 2

4 7 6 4 5

Sample Output 2

NO

Sample Input 3

48792 105960835 681218449 90629745 90632170

Sample Output 3

NO

Sample Input 4

491995 412925347 825318103 59999126 59999339

Sample Output 4

YES


import Data.Bool

main = do
 [n,a,b,c,d] <- map read . words <$> getLine :: IO [Integer]
 putStrLn $ bool "NO" "YES" $ moderate n a b c d

moderate n a b c d
 | odd n = r >= abs (a-b)
 | otherwise = min c d <= abs (a-b) || r + max c d <= abs (a-b)
 where
  r = div (abs (a-b)) 2 * diff
  diff = d - c


main :: IO()
main = do
    str <- getLine
    print $ getsolve (init str)

getsolve :: String -> Int
getsolve str
	| len == 0								= 0
    | mod len 2 == 1						= getsolve (init str)
    | (take hlen str) == (drop hlen str)	= len
    | otherwise								= getsolve (init str)
    where len = length str
          hlen = div len 2

Score : 200 points

Problem Statement

We will call a string that can be obtained by concatenating two equal strings an even string.
For example, xyzxyz and aaaaaa are even, while ababab and xyzxy are not.

You are given an even string S consisting of lowercase English letters.
Find the length of the longest even string that can be obtained by deleting one or more characters from the end of S.
It is guaranteed that such a non-empty string exists for a given input.

Constraints

2 \leq |S| \leq 200

S is an even string consisting of lowercase English letters.

There exists a non-empty even string that can be obtained by deleting one or more characters from the end of S.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest even string that can be obtained.

Sample Input 1

abaababaab

Sample Output 1

6

abaababaab itself is even, but we need to delete at least one character.

abaababaa is not even.

abaababa is not even.

abaabab is not even.

abaaba is even. Thus, we should print its length, 6.

Sample Input 2

xxxx

Sample Output 2

2

xxx is not even.

xx is even.

Sample Input 3

abcabcabcabc

Sample Output 3

6

The longest even string that can be obtained is abcabc, whose length is 6.

Sample Input 4

akasakaakasakasakaakas

Sample Output 4

14

The longest even string that can be obtained is akasakaakasaka, whose length is 14.


isEvenString :: String -> Bool
isEvenString s
  | odd $ length s = False
  | takeHalf s ++ takeHalf s == s = True
  | otherwise = False

takeHalf :: String -> String
takeHalf s = take n s
  where n = (length s) `div` 2

solve :: String -> Int
solve s
  | isEvenString s' = length s - 1
  | otherwise = solve $ init s'
    where s' = init s

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


main = do
  n <- readLn
  a <- (map read . words) <$> getLine
  putStrLn $ solve n a

solve:: Int -> [Int] -> String
solve n a = arStr $ solve' n a

solve':: Int -> [Int] -> [Int]
solve' n a
  | odd n = addL [] a
  | otherwise = addR [] a

addR:: [Int] -> [Int] -> [Int]
addR s [] = s
addR s (a:as) = addL (s ++ [a]) as

addL:: [Int] -> [Int] -> [Int]
addL s [] = s
addL s (a:as) = addR (a:s) as

arStr:: [Int] -> String
arStr a = unwords $ map show a

Score : 300 points

Problem Statement

You are given an integer sequence of length n, a_1, ..., a_n.
Let us consider performing the following n operations on an empty sequence b.

The i-th operation is as follows:

Append a_i to the end of b.

Reverse the order of the elements in b.

Find the sequence b obtained after these n operations.

Constraints

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

0 \leq a_i \leq 10^9

n and a_i are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print n integers in a line with spaces in between.
The i-th integer should be b_i.

Sample Input 1

4
1 2 3 4

Sample Output 1

4 2 1 3

After step 1 of the first operation, b becomes: 1.

After step 2 of the first operation, b becomes: 1.

After step 1 of the second operation, b becomes: 1, 2.

After step 2 of the second operation, b becomes: 2, 1.

After step 1 of the third operation, b becomes: 2, 1, 3.

After step 2 of the third operation, b becomes: 3, 1, 2.

After step 1 of the fourth operation, b becomes: 3, 1, 2, 4.

After step 2 of the fourth operation, b becomes: 4, 2, 1, 3.

Thus, the answer is 4 2 1 3.

Sample Input 2

3
1 2 3

Sample Output 2

3 1 2

As shown above in Sample Output 1, b becomes 3, 1, 2 after step 2 of the third operation. Thus, the answer is 3 1 2.

Sample Input 3

1
1000000000

Sample Output 3

1000000000

Sample Input 4

6
0 6 7 6 7 0

Sample Output 4

0 6 6 0 7 7


import qualified Data.ByteString.Char8 as B
import Data.Maybe(fromJust)
main=B.putStrLn.B.unwords.solve.reverse.tail.B.words=<<B.getContents
solve[]=[]
solve(x:xs)=x:(reverse.solve$xs)


deal :: [Int] -> [Int] -> [Int] -> ([Int], [Int])
deal [] xs ys = (xs, ys)
deal [x] xs ys = (x:xs, ys)
deal (x:y:zs) xs ys = deal zs (x:xs) (y:ys)

main = do
  _ <- getLine
  as <- map read . words <$> getLine
  let (ts, hs) = deal as [] []
  print (hs ++ reverse ts)


import Control.Arrow
import Data.Maybe
import qualified Data.ByteString.Char8 as B
main=putStrLn.unwords.map show.solve.map (fst.fromJust.B.readInt).B.words=<<B.getContents
solve (n:as)
  |odd n=reverse a1s++a2s
  |otherwise=reverse a2s++a1s
  where (a1s,a2s)=(f odd&&&f even)as
f g=map snd.filter (g.fst).zip [1..]


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

q = 10^9+7

main = do
 n <- readLn
 as <- map (fst. fromJust .  B.readInteger) . B.words <$> B.getLine
 mapM_ (print . (`mod` q) . ss n as) [1..n+1]

ss n as k = comb (n+1) k - comb (n-(j-i)) (k-1)
 where
  [(i,_),(j,_)] = sort . head . filter ((==2) . length) . groupBy (\(_,x) (_,y) -> x==y) . sortOn snd . zip [0..] $ as

fact n = go 1 n
 where
  go acc 0 = acc
  go acc x = go (mod (acc*x) q) (x-1)

comb n r
 | n < r = 0
 | otherwise = fact n * pow (fact r) (q-2) * pow (fact (n-r)) (q-2)

pow x n
 | n == 0 = 1
 | odd n = mod (x * pow x (n-1)) q
 | otherwise = mod ((pow x (div n 2))^2) q

Score : 600 points

Problem Statement

You are given an integer sequence of length n+1, a_1,a_2,...,a_{n+1}, which consists of the n integers 1,...,n.
It is known that each of the n integers 1,...,n appears at least once in this sequence.

For each integer k=1,...,n+1, find the number of the different subsequences (not necessarily contiguous) of the given sequence with length k, modulo 10^9+7.

Notes

If the contents of two subsequences are the same, they are not separately counted even if they originate from different positions in the original sequence.

A subsequence of a sequence a with length k is a sequence obtained by selecting k of the elements of a and arranging them without changing their relative order. For example, the sequences 1,3,5 and 1,2,3 are subsequences of 1,2,3,4,5, while 3,1,2 and 1,10,100 are not.

Constraints

1 \leq n \leq 10^5

1 \leq a_i \leq n

Each of the integers 1,...,n appears in the sequence.

n and a_i are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_{n+1}

Output

Print n+1 lines.
The k-th line should contain the number of the different subsequences of the given sequence with length k, modulo 10^9+7.

Sample Input 1

3
1 2 1 3

Sample Output 1

3
5
4
1

There are three subsequences with length 1: 1 and 2 and 3.

There are five subsequences with length 2: 1,1 and 1,2 and 1,3 and 2,1 and 2,3.

There are four subsequences with length 3: 1,1,3 and 1,2,1 and 1,2,3 and 2,1,3.

There is one subsequence with length 4: 1,2,1,3.

Sample Input 2

1
1 1

Sample Output 2

1
1

There is one subsequence with length 1: 1.

There is one subsequence with length 2: 1,1.

Sample Input 3

32
29 19 7 10 26 32 27 4 11 20 2 8 16 23 5 14 6 12 17 22 18 30 28 24 15 1 25 3 13 21 19 31 9

Sample Output 3

32
525
5453
40919
237336
1107568
4272048
13884156
38567100
92561040
193536720
354817320
573166440
818809200
37158313
166803103
166803103
37158313
818809200
573166440
354817320
193536720
92561040
38567100
13884156
4272048
1107568
237336
40920
5456
528
33
1

Be sure to print the numbers modulo 10^9+7.


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

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

getIntArray :: IO [Integer]
getIntArray = ((map (\a -> read a :: Integer)) . words) <$> getLine

getStrArray :: Integer -> IO [String]
getStrArray 0 = return [] :: IO [String]
getStrArray n = (:) <$> getLine <*> (getStrArray (n - 1))

canEat :: [Integer] -> String
canEat [x, a, b]
    | b - a < 0 = "delicious"
    | b - a < x = "safe"
    | otherwise = "dangerous"

main = do
    putStrLn =<< (canEat <$> getIntArray)

Score : 100 points

Problem Statement

Takahashi has a strong stomach. He never gets a stomachache from eating something whose "best-by" date is at most X days earlier.
He gets a stomachache if the "best-by" date of the food is X+1 or more days earlier, though.

Other than that, he finds the food delicious if he eats it not later than the "best-by" date. Otherwise, he does not find it delicious.

Takahashi bought some food A days before the "best-by" date, and ate it B days after he bought it.

Write a program that outputs delicious if he found it delicious, safe if he did not found it delicious but did not get a stomachache either, and dangerous if he got a stomachache.

Constraints

1 ≤ X,A,B ≤ 10^9

Input

Input is given from Standard Input in the following format:

X A B

Output

Print delicious if Takahashi found the food delicious; print safe if he neither found it delicious nor got a stomachache; print dangerous if he got a stomachache.

Sample Input 1

4 3 6

Sample Output 1

safe

He ate the food three days after the "best-by" date. It was not delicious or harmful for him.

Sample Input 2

6 5 1

Sample Output 2

delicious

He ate the food by the "best-by" date. It was delicious for him.

Sample Input 3

3 7 12

Sample Output 3

dangerous

He ate the food five days after the "best-by" date. It was harmful for him.


main :: IO ()
main = do
    [x, a, b] <- map read . words <$> getLine
    putStrLn $
        if b - a <= 0          then "delicious"
        else if b - a <= x + 1 then "safe"
        else                        "dangerous"


import Control.Monad

main :: IO ()
main = do
  n <- read <$> getLine
  as <- replicateM n (read <$> getLine)

  print $ f n as 0 1

f :: Int -> [Int] -> Int -> Int -> Int
f n xs m i
  | i == 2 = m
  | n == m = -1
  | otherwise = f n xs (m+1) (xs!!(i-1))

Score : 200 points

Problem Statement

Takahashi wants to gain muscle, and decides to work out at AtCoder Gym.

The exercise machine at the gym has N buttons, and exactly one of the buttons is lighten up.
These buttons are numbered 1 through N.
When Button i is lighten up and you press it, the light is turned off, and then Button a_i will be lighten up. It is possible that i=a_i.
When Button i is not lighten up, nothing will happen by pressing it.

Initially, Button 1 is lighten up. Takahashi wants to quit pressing buttons when Button 2 is lighten up.

Determine whether this is possible. If the answer is positive, find the minimum number of times he needs to press buttons.

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i ≤ N

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

Output

Print -1 if it is impossible to lighten up Button 2.
Otherwise, print the minimum number of times we need to press buttons in order to lighten up Button 2.

Sample Input 1

3
3
1
2

Sample Output 1

2

Press Button 1, then Button 3.

Sample Input 2

4
3
4
1
2

Sample Output 2

-1

Pressing Button 1 lightens up Button 3, and vice versa, so Button 2 will never be lighten up.

Sample Input 3

5
3
3
4
2
4

Sample Output 3

3


import Control.Monad

main :: IO ()
main = do
  n <- readLn :: IO Int
  as <- replicateM n readLn :: IO [Int]
  print $ solve n (map (\l -> l - 1) as)

solve :: Int -> [Int] -> Int
solve n as = go 0 0
  where
    go m c
      | c == 1 = m
      | m > n = -1
      | otherwise =
          let next = as !! c in
            go (m+1) next


import Prelude
import Control.Monad
import Control.Applicative

takahashi ::[Int]-> [Int]-> Int -> Int
takahashi as his now |now==2 = length his
                     |elem now his = -1
                     |otherwise = as `seq` his `seq` now `seq` takahashi as (now:his) $as!!(now-1)

takahashi2 :: [Int]->[Int]->Int->Int
takahashi2 as his now
  |(not$elem 2 as) = -1
  |otherwise = (takahashi as his now)

main :: IO ()
main = do
	n <- readLn
	l <- replicateM n readLn
        putStrLn $ show $ takahashi2 l [] 1


{-# LANGUAGE MultiWayIf #-}

import Data.List
import Control.Applicative

main :: IO ()
main = do
  [n,m] <- map read . words <$> getLine :: IO [Int]
  let mi = min n m
      di = abs (n-m)
      fa = prod [mi .. 1]
  print
   $ if di >= 2 then 0
     else fa `mult` fa
           `mult` if di == 1 then mi+1 else 2

modulus :: Int
modulus = 10^9 + 7

mult :: Int -> Int -> Int
mult x y = (x * y) `mod` modulus

prod :: [Int] -> Int
prod = foldl' mult 1

Score : 300 points

Problem Statement

Snuke has N dogs and M monkeys. He wants them to line up in a row.

As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.

How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that).
Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Constraints

1 ≤ N,M ≤ 10^5

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of possible arrangements, modulo 10^9+7.

Sample Input 1

2 2

Sample Output 1

8

We will denote the dogs by A and B, and the monkeys by C and D. There are eight possible arrangements: ACBD, ADBC, BCAD, BDAC, CADB, CBDA, DACB and DBCA.

Sample Input 2

3 2

Sample Output 2

12

Sample Input 3

1 8

Sample Output 3

0

Sample Input 4

100000 100000

Sample Output 4

530123477


import Data.List
import Data.Maybe
import Data.IntMap.Strict ((!))
import qualified Data.IntMap.Strict as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

_nub = S.toList . S.fromList
readInt = fst . fromJust . B.readInt
untilFix f x = if f x == x then x else untilFix f (f x)

kruskal n edge = makepath uft 0 edge
 where
  uft = M.fromDistinctAscList (zip [1..n] [1..])
  makepath _ acc [] = acc
  makepath forest acc (((a,b),d):abd)
   | rep1 /= rep2 = makepath _forest (d+acc) abd
   | otherwise = makepath forest acc abd
   where
    v1 = min a b
    v2 = max a b
    rep1 = untilFix (forest!) v1
    rep2 = untilFix (forest!) v2
    _forest = M.insert v2 rep1 (M.insert rep2 rep1 forest)

main = do
 getLine
 xys <- map (map readInt . B.words) . B.lines <$> B.getContents
 let xyis = zip (_nub xys) [1..]
 let _n = length xyis
 let xysx = sortOn (head.fst) xyis
 let xysy = sortOn (last.fst) xyis
 print (built _n xysx xysy)

built n xysx xysy = kruskal n edge
 where
  edge = sortOn snd (edgex ++ edgey)
  edgex = zipWith mkedgex xysx (tail xysx)
  edgey = zipWith mkedgey xysy (tail xysy)
  mkedgex ([xi,yi],i) ([xj,yj],j) = ((i,j), xj-xi)
  mkedgey ([xi,yi],i) ([xj,yj],j) = ((i,j), yj-yi)

Score : 500 points

Problem Statement

There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.

You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.

Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?

Constraints

2 ≤ N ≤ 10^5

0 ≤ x_i,y_i ≤ 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.

Sample Input 1

3
1 5
3 9
7 8

Sample Output 1

3

Build a road between Towns 1 and 2, and another between Towns 2 and 3. The total cost is 2+1=3 yen.

Sample Input 2

6
8 3
4 9
12 19
18 1
13 5
7 6

Sample Output 2

8


import Data.List
divisor :: Int
divisor = 1000000007
solve :: Int -> Int -> Int
solve n m =
    case abs (n-m) of
         0 -> 2 *: (factMod n) *: (factMod m)
         1 -> (factMod n) *: (factMod m)
         _ -> 0

(*:) :: Int -> Int -> Int
(*:) x y = (x*y) `mod` divisor

factMod :: Int -> Int
factMod n = foldl1' (*:) [n, n-1..1]

main = do
    [n,m] <- map read . words <$> getLine
    print $ solve n m


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# LANGUAGE OverloadedStrings #-}
-- {-# LANGUAGE FlexibleContexts #-}
-- {-# LANGUAGE MultiWayIf #-}
-- {-# LANGUAGE BangPatterns #-}
-- {-# LANGUAGE ViewPatterns #-}
-- {-# LANGUAGE TupleSections #-}

import           System.IO hiding (char8)
import           Control.Applicative
import           Control.Monad
import           Control.Monad.ST
import           Data.List hiding (find)
import           Data.Tuple
import           Data.Int
import           Data.Char
import           Data.Function (on, (&))
import           Data.Ord (comparing)
import           Data.Monoid (mappend)
import           Data.Array
-- import           Data.Array.Unboxed
-- import           Data.Array.IArray
import           Data.Array.ST
import           Data.Array.MArray
-- import           Data.Array.Unsafe
-- import           Data.Array.Base(unsafeRead, unsafeWrite)
-- import           Data.Array.IO
import           Data.Ix
import           Data.Maybe
-- import           Data.Monoid hiding ((<>))
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BL
import           Data.ByteString.Builder
-- import           Data.Graph
-- import           Data.Vector.Unboxed ((//), (++), (!), (!?))
-- import qualified Data.Vector.Unboxed as U
-- import           Data.IntSet (IntSet)
-- import qualified Data.IntSet as IntSet
-- import           Data.IntMap.Strict (IntMap)
-- import qualified Data.IntMap.Strict as IntMap
import           Data.Sequence ((|>), (<|), (><),ViewR(..), ViewL(..), Seq)
import qualified Data.Sequence              as Seq
-- import           Data.Foldable (toList, minimumBy)
-- import           Debug.Trace

main = do
  n <- readInt1 <$> BS.getLine
  xys <- map readInt2 <$> replicateM n BS.getLine
  print . solve n $ unzip xys

-- solve :: Int -> ([Int], [Int]) -> Int
solve n (xs,ys) = sum $ kruskal n edges
  where
    edges = sortOn snd $ mkEdges xs ++ mkEdges ys
    mkEdges :: [Int] -> [Edge]
    mkEdges ns = zip [1..] ns
        & sortOn snd
        & \ms -> zipWith ((,) **** flip (-)) ms $ tail ms

(****) :: (a -> b -> c) -> (a' -> b' -> c') -> (a, a') -> (b, b') -> (c, c')
(****) f g (a, a') (b, b') = (f a b, g a' b')
infixr 3 ****

type Edge = ((Node, Node), Cost)
type Node = Int
type Cost = Int
kruskal :: Int -> [Edge] -> [Cost]
kruskal n es = runST $ do
  uf <- newUnionFind n
  k' uf es []
  where
    k' :: UnionFind s -> [Edge] -> [Cost] -> ST s [Cost]
    k' _ [] es' = return es'
    k' uf (((x,y),c):es) es' = do
      united <- find uf x y
      if united
        then k' uf es es'
        else unite uf x y >> k' uf es (c:es')

-- libs
-- http://jng.imagine27.com/index.php/2012-08-22-144618_purely-functional-data-structures-algorithms-union-find-haskell.html

-- Code from http://kwangyulseo.com/2014/01/30/implementing-union-find-algorithms-in-haskell/
data UnionFind s = UnionFind {
    ids:: STUArray s Int Int
  , szs:: STUArray s Int Int
  }

newUnionFind :: Int -> ST s (UnionFind s)
newUnionFind n = liftM2 UnionFind (newListArray (1, n) [1..n]) (newArray (1, n) 1)

find :: UnionFind s -> Int -> Int -> ST s Bool
find uf p q = liftM2 (==) (root uf p) (root uf q)

root :: UnionFind s -> Int -> ST s Int
root uf i = do
    ix <- readArray (ids uf) i
    if ix /= i
        then do
            gpid <- readArray (ids uf) ix
            writeArray (ids uf) i gpid
            root uf ix
        else return i

unite :: UnionFind s -> Int -> Int -> ST s ()
unite uf p q = do
    i <- root uf p
    j <- root uf q
    szi <- readArray (szs uf) i
    szj <- readArray (szs uf) j
    if szi < szj
        then do
            writeArray (ids uf) i j
            writeArray (szs uf) j (szi + szj)
        else do
            writeArray (ids uf) j i
            writeArray (szs uf) i (szj + szi)

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

getInt1 :: IO Int
getInt1 = readInt1 <$> BS.getLine

getInt2 :: IO (Int, Int)
getInt2 = readInt2 <$> BS.getLine

getInt3 :: IO (Int, Int, Int)
getInt3 = readInt3 <$> BS.getLine

getInts :: IO [Int]
getInts = readInts <$> BS.getLine

getIntN :: Int -> IO [Int]
getIntN n = map readInt1 <$> replicateM n BS.getLine

format :: Show a => Maybe a -> IO ()
format Nothing = putStrLn "NO"
format (Just a) = putStrLn "YES" >> print a

-- [1,2,3] -> 1 2 3
putInts :: [Int] -> IO ()
-- putInts [] = return ()
-- putInts xs = BL.putStrLn . toLazyByteString . foldl1 mappend . intersperse (char8 ' ') $ map intDec xs
putInts = putStrLn . unwords . map show

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

readInt2 :: BS.ByteString -> (Int,Int)
readInt2 = toTuple . readInts

readInt3 :: BS.ByteString -> (Int,Int,Int)
readInt3 = toTriple . readInts

readInts :: BS.ByteString -> [Int]
readInts =  map readInt1 . BS.words

readInt641 :: BS.ByteString -> Int64
readInt641 = fromIntegral . fst . fromJust . BS.readInteger

readInt642 :: BS.ByteString -> (Int64,Int64)
readInt642 = toTuple . readInt64s

readInt643 :: BS.ByteString -> (Int64,Int64,Int64)
readInt643 = toTriple . readInt64s

readInt64s :: BS.ByteString -> [Int64]
readInt64s =  map readInt641 . BS.words

readInteger1 :: BS.ByteString -> Integer
readInteger1 = fst . fromJust . BS.readInteger

readInteger2 :: BS.ByteString -> (Integer,Integer)
readInteger2 = toTuple . readIntegers

readInteger3 :: BS.ByteString -> (Integer,Integer,Integer)
readInteger3 = toTriple . readIntegers

readIntegers :: BS.ByteString -> [Integer]
readIntegers =  map readInteger1 . BS.words

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

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

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

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

-- if not applying, use "id"

applyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')
applyTuple f g (x, y) = (f x, g y)

applyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')
applyTriple f g h (x, y, z) = (f x, g y, h z)

-- @since 4.8.0.0
sortOn' :: Ord b => (a -> b) -> [a] -> [a]
sortOn' f =
  map snd . sortBy (comparing fst) . map (\x -> let y = f x in y `seq` (y, x))


import Data.List
main=interact$(\b->if b then "Yes" else "No").f.map read.words
f(n:a)=case length m of
  1 -> 0<x && x<=n`div`2 || x==n-1
  2 -> x+1==y && 0<x && x<n-1 && 2*x+1-n<i && i<=x
  _ -> False
  where
    (i,x)=g$m!!0
    (j,y)=g$m!!1
    m=group.sort$a
g a=(length a, head a)

Score : 700 points

Problem Statement

There are N cats.
We number them from 1 through N.

Each of the cats wears a hat.
Cat i says: "there are exactly a_i different colors among the N - 1 hats worn by the cats except me."

Determine whether there exists a sequence of colors of the hats that is consistent with the remarks of the cats.

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i ≤ N-1

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print Yes if there exists a sequence of colors of the hats that is consistent with the remarks of the cats; print No otherwise.

Sample Input 1

3
1 2 2

Sample Output 1

Yes

For example, if cat 1, 2 and 3 wears red, blue and blue hats, respectively, it is consistent with the remarks of the cats.

Sample Input 2

3
1 1 2

Sample Output 2

No

From the remark of cat 1, we can see that cat 2 and 3 wear hats of the same color.
Also, from the remark of cat 2, we can see that cat 1 and 3 wear hats of the same color.
Therefore, cat 1 and 2 wear hats of the same color, which contradicts the remark of cat 3.

Sample Input 3

5
4 3 4 3 4

Sample Output 3

No

Sample Input 4

3
2 2 2

Sample Output 4

Yes

Sample Input 5

4
2 2 2 2

Sample Output 5

Yes

Sample Input 6

5
3 3 3 3 3

Sample Output 6

No


import Data.Bool
import Data.List

main = do
 n <- readLn
 as <- map read . words <$> getLine
 putStrLn $ bool "No" "Yes" (hats n as)

hats n as
 | all (==1) as = True
 | all (==(n-1)) as = True
 | length gs == 1 && n `mod` head (head gs) /= head (head gs) - 1 = True
 | length gs == 2 && head (head gs) == 1 && head (head gs) + length (head gs) == head (head (tail gs)) = True
 | otherwise = False
 where gs = sortOn length $ group (sort as)


main = do
  [a,b,c] <- map read . words <$> getLine
  putStrLn (if (a * 100 + b * 10 + c) `mod` 4 == 0 then "YES" else "NO")

Score : 100 points

Problem Statement

AtCoDeer has three cards, one red, one green and one blue.

An integer between 1 and 9 (inclusive) is written on each card: r on the red card, g on the green card and b on the blue card.

We will arrange the cards in the order red, green and blue from left to right, and read them as a three-digit integer.

Is this integer a multiple of 4?

Constraints

1 ≤ r, g, b ≤ 9

Input

Input is given from Standard Input in the following format:

r g b

Output

If the three-digit integer is a multiple of 4, print YES (case-sensitive); otherwise, print NO.

Sample Input 1

4 3 2

Sample Output 1

YES

432 is a multiple of 4, and thus YES should be printed.

Sample Input 2

2 3 4

Sample Output 2

NO

234 is not a multiple of 4, and thus NO should be printed.


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

data Rgb = Rgb {red :: Int, green :: Int, blue :: Int}

toYesNo :: Bool -> String
toYesNo True = "YES"
toYesNo _ = "NO"

toNum :: Rgb -> Int
toNum rgb = (red rgb) * 100 + (green rgb) * 10 + (blue rgb)

solve :: Rgb -> String
solve = toYesNo . ((==) 0) . (flip mod 4) . toNum

main :: IO ()
main = do
    [r, g, b] <- map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine
    let rgb = Rgb {red=r, green=g, blue=b}
    putStrLn $ solve rgb


{-# LANGUAGE OverloadedStrings #-}

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

main :: IO ()
main = do
    [r, g, b] <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
    B.putStrLn $ if (r * 100 + g * 10 + b) `mod` 4 == 0 then "YES" else "NO"


main = do
  [_, g, b] <- map read . words <$> getLine
  putStrLn $ solve g b

solve:: Int -> Int -> String
solve g b
  | mod gb 4 == 0 = "YES"
  | otherwise = "NO"
  where
    gb = g * 10 + b


main = do
  [r, g, b] <- map read . words <$> getLine
  putStrLn $ f $ r + g + b

f x
  | mod x 4 == 0 = "YES"
  | otherwise = "NO"


module Main where
import Data.List
solve :: [Int] -> (Int,Int)
solve a =
    let list = [b `div` 400 | b <- a,b < 2800]
        ans = nub list
        list' = [b | b<-a,b>=2800]
    in (max 1 (length ans + length list'),max 1 (length ans + min (length list') 1))

main = do
    n <- getLine
    a <- (map read . words) <$> getLine
    let ans = solve a
    print $ snd ans
    print $ fst ans

Score : 300 points

Problem Statement

In AtCoder, a person who has participated in a contest receives a color, which corresponds to the person's rating as follows:

Rating 1-399 : gray

Rating 400-799 : brown

Rating 800-1199 : green

Rating 1200-1599 : cyan

Rating 1600-1999 : blue

Rating 2000-2399 : yellow

Rating 2400-2799 : orange

Rating 2800-3199 : red

Other than the above, a person whose rating is 3200 or higher can freely pick his/her color, which can be one of the eight colors above or not.

Currently, there are N users who have participated in a contest in AtCoder, and the i-th user has a rating of a_i.

Find the minimum and maximum possible numbers of different colors of the users.

Constraints

1 ≤ N ≤ 100

1 ≤ a_i ≤ 4800

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 minimum possible number of different colors of the users, and the maximum possible number of different colors, with a space in between.

Sample Input 1

4
2100 2500 2700 2700

Sample Output 1

2 2

The user with rating 2100 is "yellow", and the others are "orange". There are two different colors.

Sample Input 2

5
1100 1900 2800 3200 3200

Sample Output 2

3 5

The user with rating 1100 is "green", the user with rating 1900 is blue and the user with rating 2800 is "red".

If the fourth user picks "red", and the fifth user picks "blue", there are three different colors. This is one possible scenario for the minimum number of colors.

If the fourth user picks "purple", and the fifth user picks "black", there are five different colors. This is one possible scenario for the maximum number of colors.

Sample Input 3

20
800 810 820 830 840 850 860 870 880 890 900 910 920 930 940 950 960 970 980 990

Sample Output 3

1 1

All the users are "green", and thus there is one color.


import Data.List
main=do
 n<-getLine;a<-map read.words<$>getLine
 putStrLn$unwords(h(g [f x|x<-a]))
  where f x | x<400  ='a'
            | x<800  ='t'
            | x<1200 ='l'
            | x<1600 ='w'
            | x<2000 ='s'
            | x<2400 ='g'
            | x<2800 ='o'
            | x<3200 ='c'
            |otherwise = 'f'
        g s =[(length(nub (filter(/='f')s))),(length(filter(=='f')s))]
        h l = if l!!0==0 then "1":[show (l!!1)] else [show(l!!0),show(sum l)]


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

solve :: [Int] -> (Int, Int)
solve xs = let (a,b) = partition (< 3200) xs
               a' = length . nub $ map (`div` 400) a
            in (max 1 a', a'+ length b)

main :: IO ()
main = do
    _ <- getLine
    a <- map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine
    let (mn,mx) = solve a
    print mn
    print mx


import Data.List
main = do
  n <- read <$> getLine
  as <- map read . words <$> getLine
  let xs = filter (>=8) $ map (`div`400) as
      y = length $ group $ sort xs
  putStrLn $ unwords $ map show [y`max`1, y+n-length xs]


import Data.List (sort)

main :: IO ()
main = do
    getLine
    a <- map read . words <$> getLine
    let ans = solve a
    putStr $ show (fst ans) ++ " " ++ show (snd ans)

solve :: [Int] -> (Int, Int)
solve a = (coll, max 1 (coll + cntp)) where
    hai  = filter (\x ->    1 <= x && x <=  399) a
    cha  = filter (\x ->  400 <= x && x <=  799) a
    mid  = filter (\x ->  800 <= x && x <= 1199) a
    miz  = filter (\x -> 1200 <= x && x <= 1599) a
    ao   = filter (\x -> 1600 <= x && x <= 1999) a
    ki   = filter (\x -> 2000 <= x && x <= 2399) a
    dai  = filter (\x -> 2400 <= x && x <= 2799) a
    aka  = filter (\x -> 2800 <= x && x <= 3199) a
    col  = [hai, cha, mid, miz, ao, ki, dai, aka]
    coll = length $ filter (\x -> not $ null x) col
    pro  = filter (\x -> 3200 <= x) a
    cntp = length pro


import Data.List

main = do
 getLine
 as <- getLine
 putStrLn (ins as)

ins as = replicate nbr '(' ++ as ++ replicate nbl ')'
 where
  nbr = let (br,bl) = partition (==')') $ reverse $ dropWhile (=='(') $ reverse as
         in length br - length bl
  nbl = let (bl,br) = partition (=='(') $ dropWhile (==')') as
         in length bl - length br

Score : 400 points

Problem Statement

You are given a string S of length N consisting of ( and ). Your task is to insert some number of ( and ) into S to obtain a correct bracket sequence.

Here, a correct bracket sequence is defined as follows:

() is a correct bracket sequence.

If X is a correct bracket sequence, the concatenation of (, X and ) in this order is also a correct bracket sequence.

If X and Y are correct bracket sequences, the concatenation of X and Y in this order is also a correct bracket sequence.

Every correct bracket sequence can be derived from the rules above.

Find the shortest correct bracket sequence that can be obtained. If there is more than one such sequence, find the lexicographically smallest one.

Constraints

The length of S is N.

1 ≤ N ≤ 100

S consists of ( and ).

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the lexicographically smallest string among the shortest correct bracket sequences that can be obtained by inserting some number of ( and ) into S.

Sample Input 1

3
())

Sample Output 1

(())

Sample Input 2

6
)))())

Sample Output 2

(((()))())

Sample Input 3

8
))))((((

Sample Output 3

(((())))(((())))


main = getLine >>= putStrLn . solve . map read . words

solve :: [Int] -> String
solve [x, y] =
	if x + y >= 10 then "error" else show (x + y)

Score : 100 points

Problem Statement

You are given two integers A and B as the input. Output the value of A + B.

However, if A + B is 10 or greater, output error instead.

Constraints

A and B are integers.

1 ≤ A, B ≤ 9

Input

Input is given from Standard Input in the following format:

A B

Output

If A + B is 10 or greater, print the string error (case-sensitive); otherwise, print the value of A + B.

Sample Input 1

6 3

Sample Output 1

9

Sample Input 2

6 4

Sample Output 2

error


solve [a, b] = if a + b >= 10 then "error" else show (a + b)

main = interact $ solve . map read . words


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

solve xs = loop t o
    where
        t = filter (\v -> v `rem` 10 == 0) xs
        o = filter (\v -> v `rem` 10 /= 0) xs
        loop t o
            | null o = 0
            | (sum o `rem` 10) == 0 = loop t (delete (minimum o) o)
            | otherwise = sum o + sum t

main = do
    n <- readLn :: IO Int
    xs <- replicateM n (fst . fromJust . B.readInt <$> B.getLine)
    print $ solve xs

Score : 300 points

Problem Statement

You are taking a computer-based examination. The examination consists of N questions, and the score allocated to the i-th question is s_i. Your answer to each question will be judged as either "correct" or "incorrect", and your grade will be the sum of the points allocated to questions that are answered correctly. When you finish answering the questions, your answers will be immediately judged and your grade will be displayed... if everything goes well.

However, the examination system is actually flawed, and if your grade is a multiple of 10, the system displays 0 as your grade. Otherwise, your grade is displayed correctly. In this situation, what is the maximum value that can be displayed as your grade?

Constraints

All input values are integers.

1 ≤ N ≤ 100

1 ≤ s_i ≤ 100

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the maximum value that can be displayed as your grade.

Sample Input 1

3
5
10
15

Sample Output 1

25

Your grade will be 25 if the 10-point and 15-point questions are answered correctly and the 5-point question is not, and this grade will be displayed correctly. Your grade will become 30 if the 5-point question is also answered correctly, but this grade will be incorrectly displayed as 0.

Sample Input 2

3
10
10
15

Sample Output 2

35

Your grade will be 35 if all the questions are answered correctly, and this grade will be displayed correctly.

Sample Input 3

3
10
20
30

Sample Output 3

0

Regardless of whether each question is answered correctly or not, your grade will be a multiple of 10 and displayed as 0.