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

main = do
    [n,w] <- map read . words <$> getLine :: IO [Int]
    wv <- map ((\[a,b] -> (a,b)) . map (fst . fromJust . BS.readInt) . BS.words) . BS.lines <$> BS.getContents
    print $ knapsack w wv

knapsack :: Int -> [(Int,Int)] -> Integer
knapsack c wv = memo!(n,c)
  where
    n = length wv
    k = ((0,0),(n,c))
    memo = listArray k [f t | t <- range k] :: Array (Int,Int) Integer
    f :: (Int,Int) -> Integer
    f (i,ci)
      | i == 0 = 0
      | wi > ci = memo!(i-1, ci)
      | otherwise = maximum [vi + memo!(i-1, ci-wi), memo!(i-1, ci)]
      where
        wv' = listArray (1, n) wv :: Array Int (Int, Int)
        wi = fromIntegral $ fst (wv'!i)
        vi = fromIntegral $ snd (wv'!i)

Score : 400 points

Problem Statement

You have N items and a bag of strength W.
The i-th item has a weight of w_i and a value of v_i.

You will select some of the items and put them in the bag.
Here, the total weight of the selected items needs to be at most W.

Your objective is to maximize the total value of the selected items.

Constraints

1 ≤ N ≤ 100

1 ≤ W ≤ 10^9

1 ≤ w_i ≤ 10^9

For each i = 2,3,...,N, w_1 ≤ w_i ≤ w_1 + 3.

1 ≤ v_i ≤ 10^7

W, each w_i and v_i are integers.

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible total value of the selected items.

Sample Input 1

4 6
2 1
3 4
4 10
3 4

Sample Output 1

11

The first and third items should be selected.

Sample Input 2

4 6
2 1
3 7
4 10
3 6

Sample Output 2

13

The second and fourth items should be selected.

Sample Input 3

4 10
1 100
1 100
1 100
1 100

Sample Output 3

400

You can take everything.

Sample Input 4

4 1
10 100
10 100
10 100
10 100

Sample Output 4

0

You can take nothing.


{-# LANGUAGE BangPatterns #-}
import Data.List
import Data.Maybe
import Control.Monad
import Data.Function (fix)
import Data.Array (Array, array, (!))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

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

data Tree a = Tree (Tree a) a (Tree a)

instance Functor Tree where
    fmap f (Tree l m r) = Tree (fmap f l) (f m) (fmap f r)

index :: Tree a -> Int -> a
index (Tree _ m _) 0 = m
index (Tree l _ r) n = case (n - 1) `divMod` 2 of
    (q,0) -> index l q
    (q,1) -> index r q

nats :: Tree Int
nats = go 0 1
    where go !n !s = Tree (go l s') n (go r s')
            where l = n + s
                  r = l + s
                  s' = s * 2

memo :: (Int -> a) -> (Int -> a)
memo f = index cached
    where cached = fmap f nats

memo2 :: (Int -> Int -> a) -> (Int -> Int -> a)
memo2 f = memo (\x -> memo (f x))

memo3 :: (Int -> Int -> Int -> a) -> (Int -> Int -> Int -> a)
memo3 f = memo (\x -> memo2 (f x))

solve :: Int -> [Int] -> Int
solve t = fst . foldl (\(a,b) x -> (a + min t (x+t-b), x+t)) (0,0)

main :: IO ()
main = do
    [_, t] <- getInts
    arr <- getInts
    print $ solve t arr

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

Score : 300 points

Problem Statement

In a public bath, there is a shower which emits water for T seconds when the switch is pushed.

If the switch is pushed when the shower is already emitting water, from that moment it will be emitting water for T seconds.
Note that it does not mean that the shower emits water for T additional seconds.

N people will push the switch while passing by the shower.
The i-th person will push the switch t_i seconds after the first person pushes it.

How long will the shower emit water in total?

Constraints

1 ≤ N ≤ 200,000

1 ≤ T ≤ 10^9

0 = t_1 < t_2 < t_3 < , ..., < t_{N-1} < t_N ≤ 10^9

T and each t_i are integers.

Input

Input is given from Standard Input in the following format:

N T
t_1 t_2 ... t_N

Output

Assume that the shower will emit water for a total of X seconds. Print X.

Sample Input 1

2 4
0 3

Sample Output 1

7

Three seconds after the first person pushes the water, the switch is pushed again and the shower emits water for four more seconds, for a total of seven seconds.

Sample Input 2

2 4
0 5

Sample Output 2

8

One second after the shower stops emission of water triggered by the first person, the switch is pushed again.

Sample Input 3

4 1000000000
0 1000 1000000 1000000000

Sample Output 3

2000000000

Sample Input 4

1 1
0

Sample Output 4

1

Sample Input 5

9 10
0 3 5 7 100 110 200 300 311

Sample Output 5

67

Submitted source-code file size, in bytes.

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

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


import Data.Char
main = do
  s <- getLine
  putStrLn $ (map (toUpper . head) . words) s

Score : 100 points

Problem Statement

You are given three words s_1, s_2 and s_3, each composed of lowercase English letters, with spaces in between.
Print the acronym formed from the uppercased initial letters of the words.

Constraints

s_1, s_2 and s_3 are composed of lowercase English letters.

1 ≤ |s_i| ≤ 10 (1≤i≤3)

Input

Input is given from Standard Input in the following format:

s_1 s_2 s_3

Output

Print the answer.

Sample Input 1

atcoder beginner contest

Sample Output 1

ABC

The initial letters of atcoder, beginner and contest are a, b and c. Uppercase and concatenate them to obtain ABC.

Sample Input 2

resident register number

Sample Output 2

RRN

Sample Input 3

k nearest neighbor

Sample Output 3

KNN

Sample Input 4

async layered coding

Sample Output 4

ALC


import Data.Char

concatHead :: String -> String -> String
concatHead a b =
    a ++ [toUpper $ head b]

main :: IO ()
main = do
    ss <- words <$> getLine
    putStrLn $ foldl concatHead "" ss


import Control.Applicative

comp a b
  |a>b  ="GREATER"
  |a<b  ="LESS"
  |a==b="EQUAL"

main=do
  a<-readLn::IO Int
  b<-readLn::IO Int
  putStr $ comp a b


import Data.Char

main = do
  s <- getLine
  putStrLn . map (toUpper . head) . words $ s


solve :: Integer -> Integer -> String
solve a b
  | a > b = "GREATER"
  | a < b = "LESS"
  | otherwise = "EQUAL"

main :: IO ()
main = do
  a <- readLn
  b <- readLn
  putStrLn $ solve a b

Score : 200 points

Problem Statement

You are given two positive integers A and B. Compare the magnitudes of these numbers.

Constraints

1 ≤ A, B ≤ 10^{100}

Neither A nor B begins with a 0.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print GREATER if A>B, LESS if A<B and EQUAL if A=B.

Sample Input 1

36
24

Sample Output 1

GREATER

Since 36>24, print GREATER.

Sample Input 2

850
3777

Sample Output 2

LESS

Sample Input 3

9720246
22516266

Sample Output 3

LESS

Sample Input 4

123456789012345678901234567890
234567890123456789012345678901

Sample Output 4

LESS


main = do
  getLine
  as <- map read . words <$> getLine :: IO [Int]
  let pns = cycle [1,-1] :: [Int]
  print $ min (solve (zip as pns) 0) (solve (zip as (tail pns)) 0)

solve :: [(Int,Int)] -> Int -> Int
solve [] acc = 0
solve ((a1,b1):xs) acc
  | signum (acc+a1) == b1 = 0 + solve xs (acc+a1)
  | b1 == 1 = (1 - (acc+a1)) + solve xs 1
  | otherwise = abs (-1-(acc+a1)) + solve xs (-1)

Score : 300 points

Problem Statement

You are given an integer sequence of length N. The i-th term in the sequence is a_i.
In one operation, you can select a term and either increment or decrement it by one.

At least how many operations are necessary to satisfy the following conditions?

For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.

For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Constraints

2 ≤ n ≤ 10^5

|a_i| ≤ 10^9

Each 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 necessary count of operations.

Sample Input 1

4
1 -3 1 0

Sample Output 1

4

For example, the given sequence can be transformed into 1, -2, 2, -2 by four operations. The sums of the first one, two, three and four terms are 1, -1, 1 and -1, respectively, which satisfy the conditions.

Sample Input 2

5
3 -6 4 -5 7

Sample Output 2

0

The given sequence already satisfies the conditions.

Sample Input 3

6
-1 4 3 2 -5 4

Sample Output 3

8


import Control.Applicative
import Data.List

main = do
  _ <- getLine
  as <- (map read) . words <$> getLine

  print $ minimum
    [sum $ zipWith (\a b -> abs (a-b)) (f 0 as True) as,
     sum $ zipWith (\a b -> abs (a-b)) (f 0 as False) as]

  where
    f :: Integer -> [Integer] -> Bool -> [Integer]
    f _ [] _ = []
    f ps (x:xs) m =
      if ps * (ps+x) < 0 then
        x : (f (ps+x) xs m)
      else
        if ps > 0 then
          (-ps-1) : (f (-1) xs m)
        else if ps < 0 then
          (-ps+1) : (f 1 xs m)
        else
          if x /= 0 then
            x : (f x xs m)
          else
            if m then
              1 : (f 1 xs m)
            else
              (-1) : (f (-1) xs m)


main :: IO()
main = do
  getLine
  lis <- words <$> getLine
  let numlis = map read lis
  print $ solve numlis 0

solve :: [Integer] -> Integer -> Integer
solve [] x = 0
solve (x:xs) 0 = solve xs x
solve (x:xs) m
  | m > 0 = max 0 (sum+1) + solve xs (min sum (-1))
  | m < 0 = max 0 (1-sum) + solve xs (max sum 1)
  where sum = m+x


solve [] v acc  = acc
solve as v acc
  | v < 0 =
    let w = v + (head as) in
      if w <= 0
        then solve (tail as) 1 (1 - w + acc)
        else solve (tail as) w acc
  | v > 0 =
    let w = v + (head as) in
      if w >= 0
        then solve (tail as) (-1) (1 + w + acc)
        else solve (tail as) w acc

main = do
  n <- read <$> getLine :: IO Int
  l <- getLine
  let as = fmap read (words l) :: [Int]
      v = head as
      oddV = if v <= 0
               then solve (tail as) 1 (1 - v)
               else solve (tail as) v 0
      evenV = if v < 0
                then solve (tail as) v 0
                else solve (tail as) (-1) (1 + v) in
    putStrLn (show (min oddV evenV))


{-# 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           Data.List
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 = solve <$ getInt1 <*> getIntegers >>= print

solve = solve' 0 0 . scanl (+) 0 where
  solve' _ ans [_] = ans
  solve' acc ans (x:x2:xs)
    | x2+acc == 0 = solve' (acc-signum x) (ans+1) (x2+acc-signum x:xs)
    | signum x == signum (x2+acc) = solve' (acc+d) (ans+abs d) (x2+acc+d:xs)
    | otherwise = solve' acc ans (x2+acc:xs)
      where
        d = - signum (x2+acc) * (abs (x2+acc) + 1)

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

getIntegers :: IO [Integer]
getIntegers = readIntegers <$> BS.getLine

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.Bool
main=putStrLn.solve.map read.words=<<getLine
solve[x,y]=bool"Alice""Brown"$abs(x-y)<2

Score : 500 points

Problem Statement

Alice and Brown loves games. Today, they will play the following game.

In this game, there are two piles initially consisting of X and Y stones, respectively.
Alice and Bob alternately perform the following operation, starting from Alice:

Take 2i stones from one of the piles. Then, throw away i of them, and put the remaining i in the other pile. Here, the integer i (1≤i) can be freely chosen as long as there is a sufficient number of stones in the pile.

The player who becomes unable to perform the operation, loses the game.

Given X and Y, determine the winner of the game, assuming that both players play optimally.

Constraints

0 ≤ X, Y ≤ 10^{18}

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the winner: either Alice or Brown.

Sample Input 1

2 1

Sample Output 1

Brown

Alice can do nothing but taking two stones from the pile containing two stones. As a result, the piles consist of zero and two stones, respectively. Then, Brown will take the two stones, and the piles will consist of one and zero stones, respectively. Alice will be unable to perform the operation anymore, which means Brown's victory.

Sample Input 2

5 0

Sample Output 2

Alice

Sample Input 3

0 0

Sample Output 3

Brown

Sample Input 4

4 8

Sample Output 4

Alice


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

main = do
  getLine
  li <- BS.getLine
  let as = unfoldr (BS.readInt . BS.dropWhile isSpace) li
  let ans = compute as
  print ans

compute :: [Int] -> Int
compute (a:as) = ans where (ans,_,_) = foldl step (1,EQ,a) as

-- カウント、上昇中/下降中/不明、前の値
type Acc = (Int,Ordering,Int)
step :: Acc -> Int -> Acc
step (n,o,z) a = case (o,compare z a) of
  (EQ, o') -> (n, o', a)
  (LT, GT) -> (succ n, EQ, a)
  (GT, LT) -> (succ n, EQ, a)
  _        -> (n, o, a)

Score : 300 points

Problem Statement

You are given an array A of length N.
Your task is to divide it into several contiguous subarrays.
Here, all subarrays obtained must be sorted in either non-decreasing or non-increasing order.
At least how many subarrays do you need to divide A into?

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Each 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 subarrays after division of A.

Sample Input 1

6
1 2 3 2 2 1

Sample Output 1

2

One optimal solution is to divide the array into [1,2,3] and [2,2,1].

Sample Input 2

9
1 2 1 2 1 2 1 2 1

Sample Output 2

5

Sample Input 3

7
1 2 3 2 1 999999999 1000000000

Sample Output 3

3


import Control.Monad
import Data.List

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

solve :: [Int] -> Int
solve as = go as' (if length as' /= 1
                   then (head y <= head (head ys))
                   else True)
  where
    as'@(y:ys) = group as
    go :: [[Int]] -> Bool -> Int
    go [] _ = 0
    go [x] _ = 1
    go (x:xs@(z:zs)) b
      | head x <= head z , b = go xs b
      | head x >= head z , not b = go xs b
      | otherwise = if (not.null) zs
                    then 1 + go zs (head z <= head (head zs))
                    else 1 + go xs b


main=do
 [a,b,c]<-map read.words<$>getLine
 putStrLn$if(b-a)==(c-b)then"YES"else"NO"

Score : 100 points

Problem Statement

Three poles stand evenly spaced along a line. Their heights are a, b and c meters, from left to right.
We will call the arrangement of the poles beautiful if the tops of the poles lie on the same line, that is, b-a = c-b.

Determine whether the arrangement of the poles is beautiful.

Constraints

1 \leq a,b,c \leq 100

a, b and c are integers.

Input

Input is given from Standard Input in the following format:

a b c

Output

Print YES if the arrangement of the poles is beautiful; print NO otherwise.

Sample Input 1

2 4 6

Sample Output 1

YES

Since 4-2 = 6-4, this arrangement of poles is beautiful.

Sample Input 2

2 5 6

Sample Output 2

NO

Since 5-2 \neq 6-5, this arrangement of poles is not beautiful.

Sample Input 3

3 2 1

Sample Output 3

YES

Since 1-2 = 2-3, this arrangement of poles is beautiful.


import           Control.Monad
import           Control.Applicative

main :: IO ()
main = do
  o <- getLine
  e <- getLine

  putStrLn $ concatMap (\(a, b) -> a : [b]) $ zip o e

Score : 200 points

Problem Statement

Snuke signed up for a new website which holds programming competitions.
He worried that he might forget his password, and he took notes of it.
Since directly recording his password would cause him trouble if stolen,
he took two notes: one contains the characters at the odd-numbered positions, and the other contains the characters at the even-numbered positions.

You are given two strings O and E. O contains the characters at the odd-numbered positions retaining their relative order, and E contains the characters at the even-numbered positions retaining their relative order.
Restore the original password.

Constraints

O and E consists of lowercase English letters (a - z).

1 \leq |O|,|E| \leq 50

|O| - |E| is either 0 or 1.

Input

Input is given from Standard Input in the following format:

O
E

Output

Print the original password.

Sample Input 1

xyz
abc

Sample Output 1

xaybzc

The original password is xaybzc. Extracting the characters at the odd-numbered positions results in xyz, and extracting the characters at the even-numbered positions results in abc.

Sample Input 2

atcoderbeginnercontest
atcoderregularcontest

Sample Output 2

aattccooddeerrbreeggiunlnaerrccoonntteesstt


import Control.Monad
cs = ['a' .. 'z']

solve :: [String]->Char->(Char,Int)
solve ss c = (c, minimum $ map (length . filter (== c)) ss)

unpack :: [(Char,Int)] -> String
unpack [] = []
unpack ((c,n):cs) = (unpack cs) `mappend` (replicate n c)

main = do
  n <- readLn
  ss <- replicateM n getLine
  let
    ts = (map (solve ss) cs)
    in putStrLn $ reverse $ unpack ts

Score : 300 points

Problem Statement

Snuke loves "paper cutting": he cuts out characters from a newspaper headline and rearranges them to form another string.

He will receive a headline which contains one of the strings S_1,...,S_n tomorrow.
He is excited and already thinking of what string he will create.
Since he does not know the string on the headline yet, he is interested in strings that can be created regardless of which string the headline contains.

Find the longest string that can be created regardless of which string among S_1,...,S_n the headline contains.
If there are multiple such strings, find the lexicographically smallest one among them.

Constraints

1 \leq n \leq 50

1 \leq |S_i| \leq 50 for every i = 1, ..., n.

S_i consists of lowercase English letters (a - z) for every i = 1, ..., n.

Input

Input is given from Standard Input in the following format:

n
S_1
...
S_n

Output

Print the lexicographically smallest string among the longest strings that satisfy the condition.
If the answer is an empty string, print an empty line.

Sample Input 1

3
cbaa
daacc
acacac

Sample Output 1

aac

The strings that can be created from each of cbaa, daacc and acacac, are aa, aac, aca, caa and so forth.
Among them, aac, aca and caa are the longest, and the lexicographically smallest of these three is aac.

Sample Input 2

3
a
aa
b

Sample Output 2

The answer is an empty string.


import Data.List
main = interact $ (++"\n") . sort . foldl1 (\x y -> x \\ (x \\ y)) . tail . lines


wGcd a []=[]
wGcd [] a=[]
wGcd la@(a:as) lb@(b:bs)
  |elem a lb =a:wGcd as lb
  |elem b la =b:wGcd as bs
  |otherwise =wGcd as bs

output n a=do
  if(n==0) then putStr a
              else do
                b<-getLine
                output (n-1) (wGcd a b)

main=do
  n<-readLn
  a<-getLine
  output n a


import Data.Int
modNum = 1000000007

main = do
  nm <- map (read :: String -> Int) . words <$> getLine
  inputX <- map (read :: String -> Int) . words <$> getLine
  inputY <- map (read :: String -> Int) . words <$> getLine
  let n = head nm
      m = last nm
      x = flip mod modNum . sum . zipWith (solve (length inputX)) [1..n] $ inputX
      y = flip mod modNum . sum . zipWith (solve (length inputY)) [1..m] $ inputY
  putStrLn . show $ (flip mod modNum $ x * y)

solve :: Int -> Int -> Int -> Int
solve n k = (flip mod modNum) . ((*) (2 * k - n - 1))

Score : 500 points

Problem Statement

On a two-dimensional plane, there are m lines drawn parallel to the x axis, and n lines drawn parallel to the y axis.
Among the lines parallel to the x axis, the i-th from the bottom is represented by y = y_i.
Similarly, among the lines parallel to the y axis, the i-th from the left is represented by x = x_i.

For every rectangle that is formed by these lines, find its area, and print the total area modulo 10^9+7.

That is, for every quadruple (i,j,k,l) satisfying 1\leq i < j\leq n and 1\leq k < l\leq m, find the area of the rectangle formed by the lines x=x_i, x=x_j, y=y_k and y=y_l, and print the sum of these areas modulo 10^9+7.

Constraints

2 \leq n,m \leq 10^5

-10^9 \leq x_1 < ... < x_n \leq 10^9

-10^9 \leq y_1 < ... < y_m \leq 10^9

x_i and y_i are integers.

Input

Input is given from Standard Input in the following format:

n m
x_1 x_2 ... x_n
y_1 y_2 ... y_m

Output

Print the total area of the rectangles, modulo 10^9+7.

Sample Input 1

3 3
1 3 4
1 3 6

Sample Output 1

60

The following figure illustrates this input:

The total area of the nine rectangles A, B, ..., I shown in the following figure, is 60.

Sample Input 2

6 5
-790013317 -192321079 95834122 418379342 586260100 802780784
-253230108 193944314 363756450 712662868 735867677

Sample Output 2

835067060


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

solve :: Int -> [String] -> String
solve n ss =
  concat $
  zipWith replicate (foldr1 (zipWith min) (map countEach ss)) alphabet

alphabet = ['a'..'z']

countEach s0 = snd $ mapAccumL op (sort s0) alphabet where
  op s c = (newS, length cs) where
    (cs, newS) = span (== c) s

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

tmain :: B.ByteString -> String
tmain cont =
  let remLines0 = map B.words (B.lines cont)
      [bs_n]:remLines1 = remLines0
      n = readBInt bs_n
      ss = map (\[x] -> B.unpack x) remLines1
  in solve n ss

outAnswer :: String -> IO ()
outAnswer = putStrLn

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

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

inp1 = "3\ncbaa\ndaacc\nacacac\n"
inp2 = "3\na\naa\nb\n"
tv1 = tmain $ B.pack inp1
tv2 = tmain $ B.pack inp2
test1 = tv1 == "aac"
test2 = tv2 == ""
alltest = test1 && test2


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

solve :: Int -> Int -> [Int] -> [Int] -> Int
solve n m xs ys = weightX `mMul` weightY
  where
    diff ps = zipWith mSub (tail ps) ps
    dxs = diff xs
    dys = diff ys
    weightX = foldl' mAdd 0 $ zipWith mMul dxs [hight n k | k <- [0..n-2]]
    weightY = foldl' mAdd 0 $ zipWith mMul dys [hight m k | k <- [0..m-2]]

hight n k = mMul (n - 1 - k) (k + 1)

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

mPrime = 10^9 + 7

-- mAdd x y = (x + y) `mod` mPrime
mAdd :: Int -> Int -> Int
mAdd x y = let w = x + y in if w < mPrime then w else w - mPrime

-- mSub x y = (x - y) `mod` mPrime    -- ok even if x < y
mSub :: Int -> Int -> Int
mSub x y = let w = x - y in if w >= 0 then w else w + mPrime

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

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

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

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

tmain :: B.ByteString -> Int
tmain cont =
  let remLines0 = map B.words (B.lines cont)
      [bs_n,bs_m]:remLines1 = remLines0
      n = readBInt bs_n
      m = readBInt bs_m
      line2:remLines2 = remLines1
      xs = map readBInt line2
      line3:remLines3 = remLines2
      ys = map readBInt line3
  in solve n m xs ys

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

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

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

inp1 = "3 3\n1 3 4\n1 3 6\n"
inp2 = "6 5\n-790013317 -192321079 95834122 418379342 586260100 802780784\n-253230108 193944314 363756450 712662868 735867677\n"
inp3 = "4 4\n0 1 2 3\n0 1 2 3\n"
inp4 = "4 3\n0 1 2 3\n0 1 2\n"
tv1 = tmain $ B.pack inp1
tv2 = tmain $ B.pack inp2
tv3 = tmain $ B.pack inp3
tv4 = tmain $ B.pack inp4
test1 = tv1 == 60
test2 = tv2 == 835067060
test3 = tv3 == 100
test4 = tv4 == 40
alltest = test1 && test2 && test3 && test4


import Control.Monad
import Data.List
import qualified Data.ByteString.Char8 as B
main = breadIs >>= main'
    where
        main' [n, m] = replicateM 2 breadIs >>= print . solve n m

solve :: Int -> Int -> [[Int]] -> Int
solve n m [xs, ys] = modval $ calc n xs * calc m ys

calc :: Int -> [Int] -> Int
calc n = foldl' ff 0 . zip [0..]
    where
        ff acc (i, x) = modval $ acc + modval ((2 * i - n + 1) * x)

modval :: Int -> Int
modval = (`mod` mv)

mv :: Int
mv = 7 + 10 ^ 9

breadIs :: IO [Int]
breadIs = unfoldr uff <$> B.getLine
    where
        uff b = check <$> B.readInt b
        check (a, b)
            | B.null b = (a, b)
            | otherwise = (a, B.tail b)


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

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

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

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

readInteger :: IO Integer
readInteger = fst . fromJust . BS.readInteger <$> BS.getLine

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

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

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

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

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

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

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

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

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

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

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

divCeiling x n | b == 0    = a
               | otherwise = a + 1
  where (a, b) = x `divMod` n

main = do
  n  <- readInt
  as <- readInts
  print $ sum $ take n $ drop n $ sort as

Score : 300 points

Problem Statement

There are 3N participants in AtCoder Group Contest.
The strength of the i-th participant is represented by an integer a_i.
They will form N teams, each consisting of three participants.
No participant may belong to multiple teams.

The strength of a team is defined as the second largest strength among its members.
For example, a team of participants of strength 1, 5, 2 has a strength 2, and a team of three participants of strength 3, 2, 3 has a strength 3.

Find the maximum possible sum of the strengths of N teams.

Constraints

1 ≤ N ≤ 10^5

1 ≤ a_i ≤ 10^{9}

a_i are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the answer.

Sample Input 1

2
5 2 8 5 1 5

Sample Output 1

10

The following is one formation of teams that maximizes the sum of the strengths of teams:

Team 1: consists of the first, fourth and fifth participants.

Team 2: consists of the second, third and sixth participants.

Sample Input 2

10
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 2

10000000000

The sum of the strengths can be quite large.


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

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

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

solve :: Int -> [Int] -> Int
solve 0 _        = 0
solve n (a:b:as) = b + solve (n - 1) as


main = do
    [a, b] <- map read . words <$> getLine
    print $ (a + b) `mod` 24

Score : 100 points

Problem Statement

Dolphin loves programming contests. Today, he will take part in a contest in AtCoder.

In this country, 24-hour clock is used. For example, 9:00 p.m. is referred to as "21 o'clock".

The current time is A o'clock, and a contest will begin in exactly B hours.
When will the contest begin? Answer in 24-hour time.

Constraints

0 \leq A,B \leq 23

A and B are integers.

Input

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

A B

Output

Print the hour of the starting time of the contest in 24-hour time.

Sample Input 1

9 12

Sample Output 1

21

In this input, the current time is 9 o'clock, and 12 hours later it will be 21 o'clock in 24-hour time.

Sample Input 2

19 0

Sample Output 2

19

The contest has just started.

Sample Input 3

23 2

Sample Output 3

1

The contest will begin at 1 o'clock the next day.


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

main = do
  [a, b] <- readInt
  print $ ((a + b )`mod` 24)


main = getLine >>= print . flip mod 24 . sum . map read . words


main = do
    (a:b:xs) <- words <$> getLine
    print $ (read a + read b :: Int) `mod` 24


main = print =<< (`mod` 24) . sum . map read . words <$> getLine


import Control.Applicative ((<$>))

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


import           Control.Monad
import           Control.Applicative
import           Data.IORef
import           Data.List.Split
import           Data.Maybe
import           Data.List

main :: IO ()
main = do
  [n, m] <- map read . words <$> getLine
  sts <- replicateM n $ map read . words <$> getLine
  pts <- replicateM m $ map read . words <$> getLine

  forM_ sts $ \(sx:sy:_) -> do
    let ds = map (\(x:y:_) -> abs (sx - x) + abs (sy - y)) pts
    print $ 1 + (head . elemIndices (minimum ds)) ds

Score : 200 points

Problem Statement

There are N students and M checkpoints on the xy-plane.

The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j).

When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance.

The Manhattan distance between two points (x_1,y_1) and (x_2,y_2) is |x_1-x_2|+|y_1-y_2|.

Here, |x| denotes the absolute value of x.

If there are multiple nearest checkpoints for a student, he/she will select the checkpoint with the smallest index.

Which checkpoint will each student go to?

Constraints

1 \leq N,M \leq 50

-10^8 \leq a_i,b_i,c_j,d_j \leq 10^8

All input values are integers.

Input

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

N M
a_1 b_1
:
a_N b_N
c_1 d_1
:
c_M d_M

Output

Print N lines.

The i-th line (1 \leq i \leq N) should contain the index of the checkpoint for the i-th student to go.

Sample Input 1

2 2
2 0
0 0
-1 0
1 0

Sample Output 1

2
1

The Manhattan distance between the first student and each checkpoint is:

For checkpoint 1: |2-(-1)|+|0-0|=3

For checkpoint 2: |2-1|+|0-0|=1

The nearest checkpoint is checkpoint 2. Thus, the first line in the output should contain 2.

The Manhattan distance between the second student and each checkpoint is:

For checkpoint 1: |0-(-1)|+|0-0|=1

For checkpoint 2: |0-1|+|0-0|=1

When there are multiple nearest checkpoints, the student will go to the checkpoint with the smallest index. Thus, the second line in the output should contain 1.

Sample Input 2

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

Sample Output 2

3
1
2

There can be multiple checkpoints at the same coordinates.

Sample Input 3

5 5
-100000000 -100000000
-100000000 100000000
100000000 -100000000
100000000 100000000
0 0
0 0
100000000 100000000
100000000 -100000000
-100000000 100000000
-100000000 -100000000

Sample Output 3

5
4
3
2
1


main :: IO ()
main = do
  n <- readLn :: IO Int
  print $ minimum [maximum $ fmap (length . show) [a, (n `div` a)] | a <- takeWhile ((n >) . (^2)) [1 .. ], (n `mod` a) == 0]

Score : 300 points

Problem Statement

You are given an integer N.

For two positive integers A and B, we will define F(A,B) as the larger of the following: the number of digits in the decimal notation of A, and the number of digits in the decimal notation of B.

For example, F(3,11) = 2 since 3 has one digit and 11 has two digits.

Find the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Constraints

1 \leq N \leq 10^{10}

N is an integer.

Input

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

N

Output

Print the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Sample Input 1

10000

Sample Output 1

3

F(A,B) has a minimum value of 3 at (A,B)=(100,100).

Sample Input 2

1000003

Sample Output 2

7

There are two pairs (A,B) that satisfy the condition: (1,1000003) and (1000003,1). For these pairs, F(1,1000003)=F(1000003,1)=7.

Sample Input 3

9876543210

Sample Output 3

6


main = do
    n <- readLn :: IO Integer
    print.minimum.(map (\x -> length (show (n`div`x))))
            .(filter $ (==0).(mod n)) $ [1..(ceiling .sqrt. fromIntegral $ n)]


import Control.Monad
import qualified Data.ByteString.Char8 as C
import Data.List
import Data.Ord

main = C.interact $ put . sol . get

get = fmap (unfoldr (C.readInt . C.dropWhile (==' '))) . C.lines

put = C.pack . unlines

sol ([n,a,b]:vs:[]) = [show ave,show cnt]
  where
  (as,bs) = splitAt a $ sortBy (flip compare) vs
  v = last as
  x = length $ filter (==v) as
  y = length $ filter (==v) vs
  cnt = if x==length as then 2^y-1 else binom y x
  ave = (fromIntegral $ sum as)/fromIntegral a

binom = loop 1 1
  where
  loop fn fk _ 0 = fn `div` fk
  loop _  _  0 _ = 0
  loop fn fk n k = loop (fn*n) (fk*k) (n-1) (k-1)

Score : 400 points

Problem Statement

You are given N items.

The value of the i-th item (1 \leq i \leq N) is v_i.

Your have to select at least A and at most B of these items.

Under this condition, find the maximum possible arithmetic mean of the values of selected items.

Additionally, find the number of ways to select items so that the mean of the values of selected items is maximized.

Constraints

1 \leq N \leq 50

1 \leq A,B \leq N

1 \leq v_i \leq 10^{15}

Each v_i is an integer.

Input

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

N A B
v_1
v_2
...
v_N

Output

Print two lines.

The first line should contain the maximum possible arithmetic mean of the values of selected items. The output should be considered correct if the absolute or relative error is at most 10^{-6}.

The second line should contain the number of ways to select items so that the mean of the values of selected items is maximized.

Sample Input 1

5 2 2
1 2 3 4 5

Sample Output 1

4.500000
1

The mean of the values of selected items will be maximized when selecting the fourth and fifth items. Hence, the first line of the output should contain 4.5.

There is no other way to select items so that the mean of the values will be 4.5, and thus the second line of the output should contain 1.

Sample Input 2

4 2 3
10 20 10 10

Sample Output 2

15.000000
3

There can be multiple ways to select items so that the mean of the values will be maximized.

Sample Input 3

5 1 5
1000000000000000 999999999999999 999999999999998 999999999999997 999999999999996

Sample Output 3

1000000000000000.000000
1


import Data.Bool

main = do
 (a:_:b:_) <- getLine
 putStrLn $ bool "D" "H" (a==b)

Score : 100 points

Problem Statement

Two deer, AtCoDeer and TopCoDeer, are playing a game called Honest or Dishonest.
In this game, an honest player always tells the truth, and an dishonest player always tell lies.
You are given two characters a and b as the input. Each of them is either H or D, and carries the following information:

If a=H, AtCoDeer is honest; if a=D, AtCoDeer is dishonest.
If b=H, AtCoDeer is saying that TopCoDeer is honest; if b=D, AtCoDeer is saying that TopCoDeer is dishonest.

Given this information, determine whether TopCoDeer is honest.

Constraints

a=H or a=D.

b=H or b=D.

Input

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

a b

Output

If TopCoDeer is honest, print H. If he is dishonest, print D.

Sample Input 1

H H

Sample Output 1

H

In this input, AtCoDeer is honest. Hence, as he says, TopCoDeer is honest.

Sample Input 2

D H

Sample Output 2

D

In this input, AtCoDeer is dishonest. Hence, contrary to what he says, TopCoDeer is dishonest.

Sample Input 3

D D

Sample Output 3

H


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

f :: Int -> [Int]
f x = unfoldr g (0, x)
  where
    g (i, 0) = Nothing
    g (i, r)
        | i + 1 == r  = Just (i + 1, (i + 1, 0))
        | i + 2 <= r' = Just (i + 1, (i + 1, r'))
        | otherwise   = Just (0,     (i + 1, r))
      where
        r' = r - (i + 1)

main :: IO ()
main = do
    x <- readLn :: IO Int
    print $ length (f x)

Score : 200 points

Problem Statement

There is a kangaroo at coordinate 0 on an infinite number line that runs from left to right, at time 0.
During the period between time i-1 and time i, the kangaroo can either stay at his position, or perform a jump of length exactly i to the left or to the right.
That is, if his coordinate at time i-1 is x, he can be at coordinate x-i, x or x+i at time i.
The kangaroo's nest is at coordinate X, and he wants to travel to coordinate X as fast as possible.
Find the earliest possible time to reach coordinate X.

Constraints

X is an integer.

1≤X≤10^9

Input

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

X

Output

Print the earliest possible time for the kangaroo to reach coordinate X.

Sample Input 1

6

Sample Output 1

3

The kangaroo can reach his nest at time 3 by jumping to the right three times, which is the earliest possible time.

Sample Input 2

2

Sample Output 2

2

He can reach his nest at time 2 by staying at his position during the first second, and jumping to the right at the next second.

Sample Input 3

11

Sample Output 3

5


import Control.Monad
import Data.List

-- [a,b) -> a .. f aがTrueとなる最大のa, f bはFalse
-- aとbは評価しないので、範囲が0..(n-1)のとき、(a,b)=(-1,n)で呼んで良い
bsearch f (a,b)
    | a+1 == b = a
    | f m  = bsearch f (m,b)
    | True = bsearch f (a,m)
    where m = (a + (b-a)`div`2)

f x a = a*(a+1) < x

main=do
    x<-readLn :: IO Int
    print $ (+) 1 $ bsearch (f (x*2)) (-1,x)


main = do
  x <- readLn
  putStr . show $ f x

f x = minimum [i | i <- [0..], i*(i-1) <= 2*(abs x)]


sol :: Double->Integer
sol s = let a = fromIntegral (round ( (-1.0+sqrt(1+8.0*( s)))/2.0-0.4999 ) ) in
           round (s + a - (a**2+a) / 2)
main = getLine >>= print.sol.read


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

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

--------------------------------------------------------------------------
solve [] _ _ _ capacity
    | capacity > 0 = 1
    | otherwise = 0
solve (x:xs) c k limit capacity
    | isRange x && capacity < c = solve xs c k limit (capacity+1)
    | capacity == c = 1 + solve (x:xs) c k x 0
    | otherwise = 1 + solve (x:xs) c k x 0
    where
        isRange a = (limit<=a) && (a<=limit+k)

main = do
    [n,c,k] <- sLineToIntL
    xs <- sort <$> mLinesToIntL n
    print $ solve xs c k (head xs) 0
--------------------------------------------------------------------------

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

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

str :: IO String
str = getLine

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

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

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

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

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

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

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

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

sLineToDoubleL :: IO [Double]
sLineToDoubleL = fromSLineL bsToDouble

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Score : 300 points

Problem Statement

Every day, N passengers arrive at Takahashi Airport.
The i-th passenger arrives at time T_i.

Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers.
Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport.
Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane.
For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).

When setting the departure times for buses under this condition, find the minimum required number of buses.
Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.

Constraints

2 \leq N \leq 100000

1 \leq C \leq 10^9

1 \leq K \leq 10^9

1 \leq T_i \leq 10^9

C, K and T_i are integers.

Input

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

N C K
T_1
T_2
:
T_N

Output

Print the minimum required number of buses.

Sample Input 1

5 3 5
1
2
3
6
12

Sample Output 1

3

For example, the following three buses are enough:

A bus departing at time 4.5, that carries the passengers arriving at time 2 and 3.

A bus departing at time 6, that carries the passengers arriving at time 1 and 6.

A bus departing at time 12, that carries the passenger arriving at time 12.

Sample Input 2

6 3 3
7
6
2
8
10
6

Sample Output 2

3


main = do
  li <- getLine
  let n = read li
  let ans = compute n
  print ans

compute :: Int -> Int
compute n = n * 800 - (n `div` 15) * 200

Score : 100 points

Problem Statement

Snuke has a favorite restaurant.

The price of any meal served at the restaurant is 800 yen (the currency of Japan), and each time a customer orders 15 meals, the restaurant pays 200 yen back to the customer.

So far, Snuke has ordered N meals at the restaurant.
Let the amount of money Snuke has paid to the restaurant be x yen, and let the amount of money the restaurant has paid back to Snuke be y yen.
Find x-y.

Constraints

1 ≤ N ≤ 100

Input

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

N

Output

Print the answer.

Sample Input 1

20

Sample Output 1

15800

So far, Snuke has paid 16000 yen, and the restaurant has paid back 200 yen. Thus, the answer is 15800.

Sample Input 2

60

Sample Output 2

47200

Snuke has paid 48000 yen for 60 meals, and the restaurant has paid back 800 yen.


main :: IO ()
main = do
  n <- readLn
  print $ n * 800 - (n `div` 15) * 200


solver ::Integer -> Integer
solver 0 = 1
solver x = mod (x*(solver (x-1))) 1000000007

main::IO()
main=do
  dc<-getLine
  let d = read dc::Integer
  print (solver d)

Score : 200 points

Problem Statement

Snuke loves working out. He is now exercising N times.

Before he starts exercising, his power is 1. After he exercises for the i-th time, his power gets multiplied by i.

Find Snuke's power after he exercises N times. Since the answer can be extremely large, print the answer modulo 10^{9}+7.

Constraints

1 ≤ N ≤ 10^{5}

Input

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

N

Output

Print the answer modulo 10^{9}+7.

Sample Input 1

3

Sample Output 1

6

After Snuke exercises for the first time, his power gets multiplied by 1 and becomes 1.

After Snuke exercises for the second time, his power gets multiplied by 2 and becomes 2.

After Snuke exercises for the third time, his power gets multiplied by 3 and becomes 6.

Sample Input 2

10

Sample Output 2

3628800

Sample Input 3

100000

Sample Output 3

457992974

Print the answer modulo 10^{9}+7.


{-# LANGUAGE BangPatterns #-}

module Main
  ( main
  )
where

import           Control.Applicative
import           Control.Monad
import           Data.Bits
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import           Data.List
import           Data.Maybe
import qualified Data.Vector                   as V

parse = fst . fromJust
parseInt = parse . BS.readInt
parseInteger = parse . BS.readInteger
readInt = parseInt <$> BS.getLine
readInteger = parseInteger <$> BS.getLine
readIntList = map parseInt . BS.words <$> BS.getLine
readIntegerList = map parseInteger . BS.words <$> BS.getLine

res = 1000000000 + 7

main = do
  [n, m] <- readIntegerList
  print $ (max n (m `div` 2)) + (max (m - 2 * n) 0) `div` 4

Score : 300 points

Problem Statement

Snuke loves puzzles.

Today, he is working on a puzzle using S- and c-shaped pieces.
In this puzzle, you can combine two c-shaped pieces into one S-shaped piece, as shown in the figure below:

Snuke decided to create as many Scc groups as possible by putting together one S-shaped piece and two c-shaped pieces.

Find the maximum number of Scc groups that can be created when Snuke has N S-shaped pieces and M c-shaped pieces.

Constraints

1 ≤ N,M ≤ 10^{12}

Input

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

N M

Output

Print the answer.

Sample Input 1

1 6

Sample Output 1

2

Two Scc groups can be created as follows:

Combine two c-shaped pieces into one S-shaped piece

Create two Scc groups, each from one S-shaped piece and two c-shaped pieces

Sample Input 2

12345 678901

Sample Output 2

175897


main = interact $ (++"\n") . show . (\(s:c:_) -> if s >= div c 2 then div c 2 else ((c - s * 2) `div` 4) + s) . map (read :: String -> Int) . words


import Data.Array.Unboxed
import Data.Bool
import qualified Data.ByteString.Char8  as C
import Data.List
import Data.Maybe

main = sol <$> getn <*> gets >>= put

getn = fst . fromJust . C.readInt <$> C.getLine

gets = C.filter ((||) <$> ('o' ==) <*> ('x' ==)) <$> C.getLine

put = putStrLn . (flip bool "-1" <*> null)

sol n s = maybe "-1" init $ find ((==) <$> head <*> last) [ss,sw,ws,ww]
  where
  a = listArray (0,n) $ (=='o') <$> C.last s:C.unpack s :: UArray Int Bool
  ss = 'S':unfoldr step ('S','S',1)
  sw = 'W':unfoldr step ('S','W',1)
  ws = 'S':unfoldr step ('W','S',1)
  ww = 'W':unfoldr step ('W','W',1)
  step ('S','S',i) = if i<=n
    then Just (nxt, ('S',nxt,i+1))
    else Nothing
    where
    nxt = bool 'W' 'S' (a!i)
  step ('S','W',i) = if i<=n
    then Just (nxt, ('W',nxt,i+1))
    else Nothing
    where
    nxt = bool 'S' 'W' (a!i)
  step ('W','S',i) = if i<=n
    then Just (nxt, ('S',nxt,i+1))
    else Nothing
    where
    nxt = bool 'S' 'W' (a!i)
  step ('W','W',i) = if i<=n
    then Just (nxt, ('W',nxt,i+1))
    else Nothing
    where
    nxt = bool 'W' 'S' (a!i)

Score : 500 points

Problem Statement

Snuke, who loves animals, built a zoo.

There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle.
The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.

There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.

Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is o, the animal said that the two neighboring animals are of the same species, and if s_i is x, the animal said that the two neighboring animals are of different species.

More formally, a sheep answered o if the two neighboring animals are both sheep or both wolves, and answered x otherwise.
Similarly, a wolf answered x if the two neighboring animals are both sheep or both wolves, and answered o otherwise.

Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print -1.

Constraints

3 ≤ N ≤ 10^{5}

s is a string of length N consisting of o and x.

Input

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

N
s

Output

If there does not exist an valid assignment that is consistent with s, print -1.
Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.

t is a string of length N consisting of S and W.

If t_i is S, it indicates that the animal numbered i is a sheep. If t_i is W, it indicates that the animal numbered i is a wolf.

Sample Input 1

6
ooxoox

Sample Output 1

SSSWWS

For example, if the animals numbered 1, 2, 3, 4, 5 and 6 are respectively a sheep, sheep, sheep, wolf, wolf, and sheep, it is consistent with their responses. Besides, there is another valid assignment of species: a wolf, sheep, wolf, sheep, wolf and wolf.

Let us remind you: if the neiboring animals are of the same species, a sheep answers o and a wolf answers x. If the neiboring animals are of different species, a sheep answers x and a wolf answers o.

Sample Input 2

3
oox

Sample Output 2

-1

Print -1 if there is no valid assignment of species.

Sample Input 3

10
oxooxoxoox

Sample Output 3

SSWWSSSWWS


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

type Animal = Char -- 'S' or 'W'
type OX     = Char -- 'o' or 'x'

next :: (Animal, Animal) -> OX -> (Animal, Animal)
next ( a, 'S') 'o' = ('S', a)
next ( a, 'W') 'x' = ('W', a)
next ('S', b )  _  = (b, 'W')
next ('W', b )  _  = (b, 'S')

compute s = if null answers then "-1" else head answers
  where
    answers =
      [ map fst (tail seq)
      | i <- [('S','S'),('S','W'),('W','S'),('W','W')]
      , let seq = scanl next i s
      , head seq == last seq
      ]


{-# LANGUAGE BangPatterns #-}
import           Control.Exception           (assert)
import           Control.Monad
import           Control.Monad.Primitive
import qualified Control.Monad.ST            as ST
import qualified Data.Array.IO               as IO
import qualified Data.Array.ST               as ST
import qualified Data.Array.Unboxed          as A
import           Data.Bits
import qualified Data.ByteString.Char8       as BS
import           Data.Char
import           Data.Foldable
import           Data.List
import           Data.Maybe
import qualified Data.Sequence               as Seq
import qualified Data.Set                    as Set
import qualified Data.Vector.Unboxed         as V
import qualified Data.Vector.Unboxed.Mutable as VM
import           Debug.Trace

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine
getIntVec n = V.unfoldrN n (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine

readInteger = fst . fromJust . BS.readInteger
readIntegerList = map readInteger . BS.words
getInteger = readInteger <$> BS.getLine
getIntegerList = readIntegerList <$> BS.getLine

inf :: Int
inf = 10^18

main = do
  [n, m] <- getIntList

  let nScc1 = min (2 * n) m `div` 2
      m' = m - nScc1 * 2
      nScc2 = m' `div` 4
      ans = nScc1 + nScc2

  print ans


main = do
  [n,m] <- map read . words <$> getLine
  let m' = m - n*2
  if m' < 0
    then print $ n + m'`div`2
    else print $ n + m'`div`4


main::IO()
main = do
  n <- (read::String->Int)  <$> getLine
  ns <- map read . words <$> getLine
  mapM_ (putStrLn . show) $ solve 0 ns []

solve ::  Int -> [Int] -> [Int] -> [Int]
solve m ns ans = do
  let car:cdr = ns
  case ns of
    [] -> ans
    _ -> case car > m of
      True -> solve car cdr $ ans++[sum $ map ((max 0) . (subtract m). (min car)) ns]
      False -> solve m cdr $ ans++[0]

Score : 700 points

Problem Statement

Snuke loves constructing integer sequences.

There are N piles of stones, numbered 1 through N.
The pile numbered i consists of a_i stones.

Snuke will construct an integer sequence s of length Σa_i, as follows:

Among the piles with the largest number of stones remaining, let x be the index of the pile with the smallest index. Append x to the end of s.

Select a pile with one or more stones remaining, and remove a stone from that pile.

If there is a pile with one or more stones remaining, go back to step 1. Otherwise, terminate the process.

We are interested in the lexicographically smallest sequence that can be constructed. For each of the integers 1,2,3,...,N, how many times does it occur in the lexicographically smallest sequence?

Constraints

1 ≤ N ≤ 10^{5}

1 ≤ a_i ≤ 10^{9}

Input

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

N
a_1 a_2 ... a_{N}

Output

Print N lines. The i-th line should contain the number of the occurrences of the integer i in the lexicographically smallest sequence that can be constructed.

Sample Input 1

2
1 2

Sample Output 1

2
1

The lexicographically smallest sequence is constructed as follows:

Since the pile with the largest number of stones remaining is pile 2, append 2 to the end of s. Then, remove a stone from pile 2.

Since the piles with the largest number of stones remaining are pile 1 and 2, append 1 to the end of s (we take the smallest index). Then, remove a stone from pile 2.

Since the pile with the largest number of stones remaining is pile 1, append 1 to the end of s. Then, remove a stone from pile 1.

The resulting sequence is (2,1,1). In this sequence, 1 occurs twice, and 2 occurs once.

Sample Input 2

10
1 2 1 3 2 4 2 5 8 1

Sample Output 2

10
7
0
4
0
3
0
2
3
0


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

card x = if x==1 then x+13 else x
poker n m
  |n>m  = "Alice"
  |n==m = "Draw"
  |n<m  = "Bob"

Score : 100 points

Problem Statement

Alice and Bob are playing One Card Poker.

One Card Poker is a two-player game using playing cards.

Each card in this game shows an integer between 1 and 13, inclusive.

The strength of a card is determined by the number written on it, as follows:

Weak 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 < 10 < 11 < 12 < 13 < 1 Strong

One Card Poker is played as follows:

Each player picks one card from the deck. The chosen card becomes the player's hand.

The players reveal their hands to each other. The player with the stronger card wins the game.

If their cards are equally strong, the game is drawn.

You are watching Alice and Bob playing the game, and can see their hands.

The number written on Alice's card is A, and the number written on Bob's card is B.

Write a program to determine the outcome of the game.

Constraints

1≦A≦13

1≦B≦13

A and B are integers.

Input

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

A B

Output

Print Alice if Alice will win. Print Bob if Bob will win. Print Draw if the game will be drawn.

Sample Input 1

8 6

Sample Output 1

Alice

8 is written on Alice's card, and 6 is written on Bob's card.
Alice has the stronger card, and thus the output should be Alice.

Sample Input 2

1 1

Sample Output 2

Draw

Since their cards have the same number, the game will be drawn.

Sample Input 3

13 1

Sample Output 3

Bob


main=interact$f.map r.words;f[a,b]|a<b="Bob"|a>b="Alice"|0<1="Draw";r"1"=99;r s=read s


import Data.List
import Data.Maybe

solve :: Int -> Int -> String
solve a b
  | a > b = "Alice"
  | a < b = "Bob"
  | otherwise = "Draw"

main :: IO ()
main = do
  [a, b] <- map read . words <$> getLine
  let seq = [2..13] ++ [1]
  putStrLn $ solve (fromJust $ elemIndex a seq) (fromJust $ elemIndex b seq)


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

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

main = do
  [a,b] <- getInts
  let [a',b'] = [f a, f b]
  putStrLn $ case (compare a' b') of
    LT -> "Bob"
    GT -> "Alice"
    EQ -> "Draw"
  where
    f 1 = 14
    f x = x


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

main :: IO ()
main = do
  [a, b] <- readInts
  putStrLn $ solve (a, b)

solve :: (Int, Int) -> String
solve (a, b) =
  if (a - b) == 0 then "Draw"
    else if a == 1 || a > b then "Alice"
    else "Bob"

-- 以下ライブラリ

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

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

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

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

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

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

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

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

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

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

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


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

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

solve :: [Int] -> String
solve [a, b]
  | a == b = "Draw"
  | a == 1 = "Alice"
  | b == 1 = "Bob"
  | a > b = "Alice"
  | otherwise = "Bob"

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


import Data.List
import Data.Maybe
import Control.Monad

main = do
  [n,m] <- map read . words <$> getLine :: IO [Int]
  xs <- replicateM n (map read . words <$> getLine) :: IO [[Int]]
  let ps = paths n (xs ++ map reverse xs)
  print $ trav m 1 ps [1..n]

paths :: Int -> [[Int]] -> [(Int,[Int])]
paths 0 xs = []
paths n xs =
  let
    dests = last $ transpose $ filter (\[a,_] -> a==n) xs
  in
    (n, dests) : (paths (n-1) xs)

trav :: Int -> Int -> [(Int,[Int])] ->  [Int] -> Int
trav m current paths dests
  | null dests = 1
  | isNothing $ find (==current) dests = 0
  | otherwise =
    let
      ds = snd $ head $ filter (\(a,_) -> a==current) paths
    in
      sum $ [x | d<-ds, let x = trav m d paths (delete current dests)]

Score : 300 points

Problem Statement

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

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

How many different paths start from vertex 1 and visit all the vertices exactly once?

Here, the endpoints of a path are considered visited.

For example, let us assume that the following undirected graph shown in Figure 1 is given.

Figure 1: an example of an undirected graph

The following path shown in Figure 2 satisfies the condition.

Figure 2: an example of a path that satisfies the condition

However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices.

Figure 3: an example of a path that does not satisfy the condition

Neither the following path shown in Figure 4, because it does not start from vertex 1.

Figure 4: another example of a path that does not satisfy the condition

Constraints

2≦N≦8

0≦M≦N(N-1)/2

1≦a_i<b_i≦N

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

Input

The 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

Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once.

Sample Input 1

3 3
1 2
1 3
2 3

Sample Output 1

2

The given graph is shown in the following figure:

The following two paths satisfy the condition:

Sample Input 2

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

Sample Output 2

1

This test case is the same as the one described in the problem statement.


import           Control.Monad
import           Data.List
import qualified Data.Map      as M

main :: IO ()
main = do
  [n, m] <- getInts
  ns <- replicateM m $ toTuple <$> getInts
  let d = make $ concat ns
  print $ solve n d

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

toTuple [n, m] = [(n, m), (m, n)]

make xs = M.fromList $
          map (foldr (\(a, b) (c, d) -> (a, b:d)) (1, [])) $
          groupBy (\a b -> fst a == fst b) $ sort xs

solve n d = go 1 []
  where
    go i xs
      | length xs == (n - 1) = 1
      | otherwise = let ns = filter (not . (`elem` xs)) $ d M.! i
                    in sum $ map (\n -> go n (i:xs)) ns


import Data.Ratio
import qualified Data.Map as M
main=do{([_,m,n]:s)<-map(map read.words).lines<$>getContents;print$M.findWithDefault(-1)(m%n)$M.mapKeysWith min(uncurry(%))$M.deleteMin.foldl(\h[a,b,c]->M.unionWith min h$M.mapKeys(\(k,l)->(k+a,l+b))$M.map(+c)h)(M.singleton(0,0)0)$s}

Score : 400 points

Problem Statement

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

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

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

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

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

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

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

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

Constraints

1≦N≦40

1≦a_i,b_i≦10

1≦c_i≦100

1≦M_a,M_b≦10

gcd(M_a,M_b)=1

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

Input

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

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

Output

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

Sample Input 1

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

Sample Output 1

3

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

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

The total price of these packages is 3 yen.

Sample Input 2

1 1 10
10 10 10

Sample Output 2

-1

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


import Data.Int (Int64)

judge :: Integral a => a -> [a] -> Bool
judge 1 _ = True
judge n xs = all f ys
    where
        k = sum xs `div` (n * (n + 1) `div` 2)
        ds = diff $ last xs : xs
        ys = fmap (k -) ds
        f x = x >= 0 && mod x n == 0

diff :: Num a => [a] -> [a]
diff xs = zipWith (-) (tail xs) (init xs)

main :: IO ()
main = do
    n <- readLn :: IO Int64
    xs <- fmap read . words <$> getLine :: IO [Int64]
    putStrLn $ if judge n xs then "YES" else "NO"

Score : 500 points

Problem Statement

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

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

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

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

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9

Input

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

N
A_1 A_2 … A_N

Output

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

Sample Input 1

5
4 5 1 2 3

Sample Output 1

YES

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

Sample Input 2

5
6 9 12 10 8

Sample Output 2

YES

Sample Input 3

4
1 2 3 1

Sample Output 3

NO


import Data.Graph.Inductive.Graph
import Data.Graph.Inductive.PatriciaTree
import Control.Monad
import Data.Maybe
import Data.Vector.Unboxed (Vector)
import qualified Data.Vector.Unboxed as V

main = do
  n <- readLn
  as <- map read.words <$> getLine
  edges <- replicateM (n-1) $ (\[a,b]->(a,b)).map read.words <$> getLine
  let
    avec = V.fromList as
    tree = mkUGraph [1..n] edges :: Gr () ()
  putStr $ unwords $ map show $ solve n tree avec

inf = 1000000001
solve :: Int -> Gr () () -> Vector Int -> [Int]
solve n tree avec = filter inner [1..n]
  where
  inner node = go 0 node == inf
  go visited node
    | lose = a
    | otherwise = inf
    where
    a = V.unsafeIndex avec (node-1)
    lose = foldr f True childs
    f child acc
      | child == visited = acc
      | otherwise = acc && a <= go node child
    childs = neighbors tree node

Score : 1600 points

Problem Statement

There is a tree with N vertices, numbered 1 through N.
The i-th of the N-1 edges connects vertices a_i and b_i.

Currently, there are A_i stones placed on vertex i.
Takahashi and Aoki will play a game using this tree.

First, Takahashi will select a vertex and place a piece on it.
Then, starting from Takahashi, they will alternately perform the following operation:

Remove one stone from the vertex currently occupied by the piece.

Then, move the piece to a vertex that is adjacent to the currently occupied vertex.

The player who is left with no stone on the vertex occupied by the piece and thus cannot perform the operation, loses the game.
Find all the vertices v such that Takahashi can place the piece on v at the beginning and win the game.

Constraints

2 ≦ N ≦ 3000

1 ≦ a_i,b_i ≦ N

0 ≦ A_i ≦ 10^9

The given graph is a tree.

Input

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

N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}

Output

Print the indices of the vertices v such that Takahashi can place the piece on v at the beginning and win the game, in a line, in ascending order.

Sample Input 1

3
1 2 3
1 2
2 3

Sample Output 1

2

The following is one possible progress of the game when Takahashi places the piece on vertex 2:

Takahashi moves the piece to vertex 1. The number of the stones on each vertex is now: (1,1,3).

Aoki moves the piece to vertex 2. The number of the stones on each vertex is now: (0,1,3).

Takahashi moves the piece to vertex 1. The number of the stones on each vertex is now: (0,0,3).

Aoki cannot take a stone from the vertex, and thus Takahashi wins.

Sample Input 2

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

Sample Output 2

1 2

Sample Input 3

3
1 1 1
1 2
2 3

Sample Output 3

Note that the correct output may be an empty line.


{-# LANGUAGE BangPatterns #-}

module Main
  ( main
  )
where

import           Control.Applicative
import           Control.Monad
import           Data.Bits
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import           Data.List
import           Data.Maybe
import qualified Data.Vector                   as V
import qualified Data.Vector.Mutable           as MV
import           Control.Monad.ST

parse = fst . fromJust
parseInt = parse . BS.readInt
parseInteger = parse . BS.readInteger
readInt = parseInt <$> BS.getLine
readInteger = parseInteger <$> BS.getLine
readIntList = map parseInt . BS.words <$> BS.getLine
readIntegerList = map parseInteger . BS.words <$> BS.getLine

main = do
  x <- readInteger
  let p = x `div` 11
      r = if x `mod` 11 <= 6 then 1 else 2
  print $ 2 * p + r

Score : 300 points

Problem Statement

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

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

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

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

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

Constraints

1 ≦ x ≦ 10^{15}

x is an integer.

Input

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

x

Output

Print the answer.

Sample Input 1

7

Sample Output 1

2

Sample Input 2

149696127901

Sample Output 2

27217477801


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

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


main = getLine >>= print . compute . read

compute :: Integer -> Integer
compute x
  | q == 0 = p * 2
  | q <= 5 = p * 2 + 1
  | True   = p * 2 + 2
  where
    (p,q) = divMod x 11


main = do
    x <- readLn
    let (d,m) = x `divMod` 11
        ans = d * 2 + if m <= 6 then 1 else 2
    print ans


import Data.List( sortBy, sort, group)
main = do
    getLine
    as_ <- return . map (read::String->Int) . words =<< getLine
    let
	gs = group . sort $ as_
	counts = map length gs
	countSorted = sortBy (flip compare) counts
	proc []			= 0
	proc [_]		= 1
	proc list@(1:_)		= length list
	proc (n1:tl@(n2:ns))
	  | 2<n1		= if n1`mod`2==0
				    then proc (2:tl)
				    else 1 + proc ((n2-1):ns)
	  | 2==n1		= if n2==1
				    then proc tl
				    else 1 + proc ((n2-1):ns)
	  | otherwise		= 1 + proc ns
    print $ proc countSorted

Score : 400 points

Problem Statement

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

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

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

Constraints

3 ≦ N ≦ 10^{5}

N is odd.

1 ≦ A_i ≦ 10^{5}

A_i is an integer.

Input

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

N
A_1 A_2 A_3 ... A_{N}

Output

Print the answer.

Sample Input 1

5
1 2 1 3 7

Sample Output 1

3

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

Sample Input 2

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

Sample Output 2

7


import Data.List

main :: IO ()
main =
    getLine >>=
        putStrLn.show.maximum.(\[a,b,c,d] -> [a*b,c*d]).(map read).words

Score : 100 points

Problem Statement

There are two rectangles.
The lengths of the vertical sides of the first rectangle are A, and the lengths of the horizontal sides of the first rectangle are B.
The lengths of the vertical sides of the second rectangle are C, and the lengths of the horizontal sides of the second rectangle are D.

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Constraints

All input values are integers.

1≤A≤10^4

1≤B≤10^4

1≤C≤10^4

1≤D≤10^4

Input

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

A B C D

Output

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Sample Input 1

3 5 2 7

Sample Output 1

15

The first rectangle has an area of 3×5=15, and the second rectangle has an area of 2×7=14.
Thus, the output should be 15, the larger area.

Sample Input 2

100 600 200 300

Sample Output 2

60000


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

main :: IO ()
main = do
    [a, b, c, d] <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine :: IO [Int]
    print $ max (a * b) (c * d)


{-# LANGUAGE BangPatterns #-}

import qualified Data.List as L

import Debug.Trace

main :: IO ()
main = do
    n <- readLn
    print
        . L.foldl' (*%) 1
        . map (succ.length)
        . L.group
        . L.sort
        $ concatMap primeFactors [1..n]

(*%) :: Int -> Int -> Int
x *% y = x * y `rem` 1000000007

smallPrimes :: (Integral i) => [i]
smallPrimes = 2 : [ n | n<-[3,5..46337], all ((>0).rem n) $ takeWhile (\x->x*x<=n) smallPrimes]
{-# SPECIALIZE smallPrimes :: [Int] #-}

primeFactors :: (Integral i) => i -> [i]
primeFactors n | n < 2 = []
primeFactors n = go n smallPrimes
  where
    go !n pps@(p:ps)
        | n < p * p = [n]
        | r > 0     = go n ps
        | otherwise = p : go q pps
      where
        (q, r) = quotRem n p
    go n [] = [n]
{-# SPECIALIZE primeFactors :: Int -> [Int] #-}

Score : 300 points

Problem Statement

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

Constraints

1≤N≤10^3

Input

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

N

Output

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

Sample Input 1

3

Sample Output 1

4

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

Sample Input 2

6

Sample Output 2

30

Sample Input 3

1000

Sample Output 3

972926972


import Data.List

main = do
    n <- readLn
    let ps = takeWhile (<=n) primes
        fs = map (succ . (f n)) ps
    print $ foldl' (\a b -> (a * b) `mod` (10^9+7)) 1 fs

primes = 2 : 3 : [x | i <- [1..], j <- [-1, 1], let x = 6 * i + j, isPrime x]
    where isPrime n = null [i | i <- takeWhile (\x -> x * x <= n) primes, rem n i == 0]

f n p = sum . map (n `div`) . takeWhile (<= n) $ map (p^) [1..]


main = do
 s <- getLine
 let t = [if c == ',' then ' ' else c | c <- s]
 putStrLn s

Score : 100 points

Problem Statement

As a New Year's gift, Dolphin received a string s of length 19.

The string s has the following format: [five lowercase English letters],[seven lowercase English letters],[five lowercase English letters].

Dolphin wants to convert the comma-separated string s into a space-separated string.

Write a program to perform the conversion for him.

Constraints

The length of s is 19.

The sixth and fourteenth characters in s are ,.

The other characters in s are lowercase English letters.

Input

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

s

Output

Print the string after the conversion.

Sample Input 1

happy,newyear,enjoy

Sample Output 1

happy newyear enjoy

Replace all the commas in happy,newyear,enjoy with spaces to obtain happy newyear enjoy.

Sample Input 2

haiku,atcoder,tasks

Sample Output 2

haiku atcoder tasks

Sample Input 3

abcde,fghihgf,edcba

Sample Output 3

abcde fghihgf edcba


main = do
  [sx,sy,tx,ty] <- map read . words <$> getLine :: IO [Int]
  let hori = tx-sx
  let vert = ty-sy
  let there1 = up vert ++ right hori
  let back1 = down vert ++ left hori
  let there2 = "L" ++ up vert ++ "UR" ++ right hori ++ "D"
  let back2 = "R" ++ down vert ++ "DL" ++ left hori ++ "U"
  putStrLn $ there1 ++ back1 ++ there2 ++ back2
    where
      up = flip replicate 'U'
      down = flip replicate 'D'
      right = flip replicate 'R'
      left = flip replicate 'L'

Score : 300 points

Problem Statement

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

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

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

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

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

Under this condition, find a shortest path for him.

Constraints

-1000 ≤ sx < tx ≤ 1000

-1000 ≤ sy < ty ≤ 1000

sx,sy,tx and ty are integers.

Input

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

sx sy tx ty

Output

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

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

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

U: Up

D: Down

L: Left

R: Right

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

Sample Input 1

0 0 1 2

Sample Output 1

UURDDLLUUURRDRDDDLLU

One possible shortest path is:

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

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

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

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

Sample Input 2

-2 -2 1 1

Sample Output 2

UURRURRDDDLLDLLULUUURRURRDDDLLDL


import Data.List
import qualified Data.IntSet as S

main=do
    [x,y]<-map read.words<$>getLine
    print $ sol 0 S.empty (S.singleton x) y
sol::Int->S.IntSet->S.IntSet->Int->Int
sol c m q y
    | S.member y q = c
    | otherwise = sol (c+1) (S.union m $ S.fromList nl) (S.fromList nl) y
    where
        nl = filter (`S.notMember` m) $ concatMap (\x->[-x, x+1]) $ S.toList q

Score : 300 points

Problem Statement

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

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

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

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

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

Constraints

x and y are integers.

|x|, |y| ≤ 10^9

x and y are different.

Input

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

x y

Output

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

Sample Input 1

10 20

Sample Output 1

10

Press button A ten times.

Sample Input 2

10 -10

Sample Output 2

1

Press button B once.

Sample Input 3

-10 -20

Sample Output 3

12

Press the buttons as follows:

Press button B once.

Press button A ten times.

Press button B once.


import Control.Applicative

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

Score : 100 points

Problem Statement

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

Constraints

1≦A,B≦10^9

op is either + or -.

Input

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

A op B

Output

Evaluate the formula and print the result.

Sample Input 1

1 + 2

Sample Output 1

3

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

Sample Input 2

5 - 7

Sample Output 2

-2


import Control.Applicative
import Control.Monad

main = do
  n <- (read::String->Int) <$> getLine
  ts <- (map (read::String->Int)) . words <$> getLine
  m <- (read::String->Int) <$> getLine
  pxs <- (map ((map (read::String->Int)) . words)) . lines <$> getContents

  forM_ pxs $ \(p:x:[]) ->
    print (sum ts - (ts!!(p-1)) + x)

Score : 200 points

Problem Statement

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

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

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

Constraints

All input values are integers.

1≦N≦100

1≦T_i≦10^5

1≦M≦100

1≦P_i≦N

1≦X_i≦10^5

Input

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

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

Output

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

Sample Input 1

3
2 1 4
2
1 1
2 3

Sample Output 1

6
9

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

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

Sample Input 2

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

Sample Output 2

19
25
30


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

main :: IO ()
main = do
  _ <- getLine
  ts <- UV.fromList . fmap (read :: String -> Int) . words <$> getLine
  m <- readLn :: IO Int
  Monad.replicateM_ m $ do
    [p,x] <- map (read :: String -> Int) . words <$> getLine
    print . UV.sum $ ts UV.// [(p-1,x)]


import Data.List
import qualified Data.ByteString.Char8 as BS
main = do
  BS.getLine
  as <- map (read . BS.unpack) . BS.words <$> BS.getLine :: IO [Int]
  print $ if check as then solve (length as `div` 2) else 0

check :: [Int] -> Bool
check xs
  | even $ length xs =
      all (even . length) (group $ sort xs)
  | otherwise =
      (length (filter (==0) xs) == 1) && (all (even . length) (group $ sort $ delete 0 xs))

solve :: Int -> Int
solve 1 = 2 `mod` (10^9+7)
solve n = (2 * solve (n-1)) `mod` (10^9+7)

Score : 300 points

Problem Statement

There are N people, conveniently numbered 1 through N.
They were standing in a row yesterday, but now they are unsure of the order in which they were standing.
However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the number of the people who were standing to the right of that person.
According to their reports, the difference above for person i is A_i.

Based on these reports, find the number of the possible orders in which they were standing.
Since it can be extremely large, print the answer modulo 10^9+7.
Note that the reports may be incorrect and thus there may be no consistent order.
In such a case, print 0.

Constraints

1≦N≦10^5

0≦A_i≦N-1

Input

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

N
A_1 A_2 ... A_N

Output

Print the number of the possible orders in which they were standing, modulo 10^9+7.

Sample Input 1

5
2 4 4 0 2

Sample Output 1

4

There are four possible orders, as follows:

2,1,4,5,3

2,5,4,1,3

3,1,4,5,2

3,5,4,1,2

Sample Input 2

7
6 4 0 2 4 0 2

Sample Output 2

0

Any order would be inconsistent with the reports, thus the answer is 0.

Sample Input 3

8
7 5 1 1 7 3 5 3

Sample Output 3

16


import Data.List
main = do
  getLine
  as <- map read . words <$> getLine :: IO [Int]
  print $ if check as then solve as else 0

check :: [Int] -> Bool
check xs
  | even $ length xs =
      all (even . length) (group $ sort xs)
  | otherwise =
      (length (filter (==0) xs) == 1) && (all (even . length) (group $ sort $ delete 0 xs))

solve :: [Int] -> Int
solve xs = 2 ^ (length xs `div` 2) `mod` (10^9+7)


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

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

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

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

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

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

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

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

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

countIf f = length . filter f

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

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

--
--
--

main = do
    num <- getI
    humans <- getIs
    let counted = evalState (cnt humans) M.empty
        checks = if even num then [1,3..(num - 1)] else [0,2..(num - 1)]
        able = all (valid counted) checks
    putStrLn . show $ bool 0 (foldr (\x y -> mod (x * y) mmm) 1 $ take (div num 2) [2,2..]) able
    where
        valid mp 0 = M.lookup 0 mp == Just 1
        valid mp n = M.lookup n mp == Just 2

cnt [] = get
cnt (x:xs) = do
    nowMap <- get
    put $ M.alter mapIncr x nowMap
    cnt xs