{-# LANGUAGE BangPatterns #-}

import Control.Monad
import Data.Char
import qualified Data.ByteString.Char8 as C
import Data.List
import qualified Data.Vector.Unboxed as U

main = sol <$> (get <$> C.getLine) <*> (get <$> C.getContents) >>= print

sub [n,a,b] = sol [n,a,b] <$> replicateM n readLn

get = unfoldr (C.readInt . C.dropWhile isSpace)

sol [n,a,b] hs = bs (h `div` s) (h `dc` a) p
  where
  v = U.fromListN n hs
  h = U.foldl1' (+) v
  s = a + n*b
  p x = (x>=) . U.foldl1' (+) $ U.map (flip dc (a-b) . max 0 . subtract (x*b)) v

bs !l !r p
  | l+1>=r    = r
  | p m       = bs l m p
  | otherwise = bs m r p
  where m = (l+r) `div` 2

dc p q = (p+q-1) `div` q

Score : 400 points

Problem Statement

You are going out for a walk, when you suddenly encounter N monsters. Each monster has a parameter called health, and the health of the i-th monster is h_i at the moment of encounter. A monster will vanish immediately when its health drops to 0 or below.

Fortunately, you are a skilled magician, capable of causing explosions that damage monsters. In one explosion, you can damage monsters as follows:

Select an alive monster, and cause an explosion centered at that monster. The health of the monster at the center of the explosion will decrease by A, and the health of each of the other monsters will decrease by B. Here, A and B are predetermined parameters, and A > B holds.

At least how many explosions do you need to cause in order to vanish all the monsters?

Constraints

All input values are integers.

1 ≤ N ≤ 10^5

1 ≤ B < A ≤ 10^9

1 ≤ h_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N A B
h_1
h_2
:
h_N

Output

Print the minimum number of explosions that needs to be caused in order to vanish all the monsters.

Sample Input 1

4 5 3
8
7
4
2

Sample Output 1

2

You can vanish all the monsters in two explosion, as follows:

First, cause an explosion centered at the monster with 8 health. The healths of the four monsters become 3, 4, 1 and -1, respectively, and the last monster vanishes.

Second, cause an explosion centered at the monster with 4 health remaining. The healths of the three remaining monsters become 0, -1 and -2, respectively, and all the monsters are now vanished.

Sample Input 2

2 10 4
20
20

Sample Output 2

4

You need to cause two explosions centered at each monster, for a total of four.

Sample Input 3

5 2 1
900000000
900000000
1000000000
1000000000
1000000000

Sample Output 3

800000000


import Control.Monad

main = join (sub <$> get) >>= print

sub [n,a,b] = sol [n,a,b] <$> replicateM n readLn

get = fmap read . words <$> getLine

sol [n,a,b] hs = c + if sum hs'>c then 1 else 0
  where
  s = a + (n-1)*b
  h = sum hs
  c = ceil h s
  hs'= fmap (flip ceil (a-b)) . filter (>0) $ fmap (subtract (c*b)) hs

ceil p q = (p+q-1) `div` q

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

Submitted source-code file size, in bytes.

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

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


{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE MultiWayIf #-}

import Control.Monad
import Control.Monad.ST
import Control.Monad.State
import Control.Applicative
import Data.List
import Data.Array
import Data.Array.IO
import Data.Maybe
import Data.Bits
import Data.Ord
import Data.Ratio
import Data.Int
import Data.Char
import qualified Data.ByteString.Char8 as BS
import qualified Data.Set as Set
import Data.Tuple
import Data.Function
import Text.Printf
import Debug.Trace
import Numeric

modifyArray arr i f = readArray arr i >>= \x -> writeArray arr i (f x)

listToTuple2 [a,b] = (a,b)
listToTuple3 [a,b,c] = (a,b,c)
listToTuple4 [a,b,c,d] = (a,b,c,d)
listToTuple5 [a,b,c,d,e] = (a,b,c,d,e)

getWords = getLine >>= return . words

readIntBS = fst . fromJust . BS.readInt

for = flip map

main :: IO ()
main = do
  (n,a,b) <- listToTuple3 . map read . words <$> getLine :: IO (Int64,Int64,Int64)
  hs <- map (fromIntegral . readIntBS) . BS.lines <$> BS.getContents :: IO [Int64]

  print $ solve hs a b 0 (ceiling $ (maximum hs) % b)

  where
    solve hs a b l r = if l+1>=r then r
      else if aux mid hs then solve hs a b l mid
      else solve hs a b mid r
      where
        mid = (l+r)`div`2
        aux x hs = (sum $ map (\h -> max 0 $ ceiling $ (h-x*b) % (a-b)) hs) <= x


module Main where

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

sharp xs = '#' : xs ++ ['#']

main :: IO ()
main = do
    [h, w] <- fmap read . words <$> getLine :: IO [Int]
    ass <- replicateM h getLine

    putStrLn $ replicate (w + 2) '#'
    mapM_ (putStrLn . sharp) ass
    putStrLn $ replicate (w + 2) '#'

Score : 200 points

Problem Statement

You are given a image with a height of H pixels and a width of W pixels.
Each pixel is represented by a lowercase English letter.
The pixel at the i-th row from the top and j-th column from the left is a_{ij}.

Put a box around this image and output the result. The box should consist of # and have a thickness of 1.

Constraints

1 ≤ H, W ≤ 100

a_{ij} is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

H W
a_{11} ... a_{1W}
:
a_{H1} ... a_{HW}

Output

Print the image surrounded by a box that consists of # and has a thickness of 1.

Sample Input 1

2 3
abc
arc

Sample Output 1

#####
#abc#
#arc#
#####

Sample Input 2

1 1
z

Sample Output 2

###
#z#
###


f h w = (x*w-(h-x)`div`2*w) `min` (x*w-w`div`2*(h-x))
  where x = (h+2)`div`3
g h w = ((h-x+1)`div`2*w-x*w) `min` ((w+1)`div`2*(h-x)-x*w)
  where x = h`div`3
main = do
  [h,w] <- map read . words <$> getLine :: IO [Int]
  print $ f h w `min` f w h `min` g h w `min` g w h

Score : 400 points

Problem Statement

There is a bar of chocolate with a height of H blocks and a width of W blocks.
Snuke is dividing this bar into exactly three pieces.
He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle.

Snuke is trying to divide the bar as evenly as possible.
More specifically, he is trying to minimize S_{max} - S_{min}, where S_{max} is the area (the number of blocks contained) of the largest piece, and S_{min} is the area of the smallest piece.
Find the minimum possible value of S_{max} - S_{min}.

Constraints

2 ≤ H, W ≤ 10^5

Input

Input is given from Standard Input in the following format:

H W

Output

Print the minimum possible value of S_{max} - S_{min}.

Sample Input 1

3 5

Sample Output 1

0

In the division below, S_{max} - S_{min} = 5 - 5 = 0.

Sample Input 2

4 5

Sample Output 2

2

In the division below, S_{max} - S_{min} = 8 - 6 = 2.

Sample Input 3

5 5

Sample Output 3

4

In the division below, S_{max} - S_{min} = 10 - 6 = 4.

Sample Input 4

100000 2

Sample Output 4

1

Sample Input 5

100000 100000

Sample Output 5

50000


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Data.List
import Data.Char
import qualified Data.Map.Strict as M

fun :: M.Map Int Int -> Int
fun !m = sum [ k*l | (k,l) <- M.toList m ]

push :: M.Map Int Int -> Int -> M.Map Int Int
push !m !k = M.insertWith (+) k 1 m

popMin :: M.Map Int Int -> (Int,M.Map Int Int)
popMin !m = let (k,i) = M.findMin m in if i == 1 then (k,M.delete k m) else (k,M.update (\x -> Just $ x-1) k m)

popMax :: M.Map Int Int -> (Int,M.Map Int Int)
popMax !m = let (k,i) = M.findMax m in if i == 1 then (k,M.delete k m) else (k,M.update (\x -> Just $ x-1) k m)

main :: IO ()
main = do
    n <- readLn
    xs <- unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
    let (as,oo) = splitAt n xs
        (bs,cs) = splitAt n oo
        bb = V.fromList bs
    let u :: V.Vector (M.Map Int Int,Int)
        u = V.create $ do
            u <- VM.new (n+1)
            VM.write u 0 $! (M.fromListWith (+) [(a,1) | a <- as],sum as)
            forM_ [1..n] $ \i-> do
                (m,s) <- VM.read u (i-1)
                let (k,m') = popMin $! push m (bb V.! (i-1))
                VM.write u i $! (m',s-k+(bb V.! (i-1)))
            return u
        v :: V.Vector (M.Map Int Int,Int)
        v = V.create $ do
            v <- VM.new (n+1)
            VM.write v n $! (M.fromListWith (+) [(c,1) | c <- cs],sum cs)
            forM_ [n-1,n-2..0] $ \i -> do
                (m,s) <- VM.read v (i+1)
                let (k,m') = popMax $! push m (bb V.! i)
                VM.write v i $! (m',s-k+(bb V.! i))
            return v
    print $ maximum [ (snd $ (V.!) u i) - (snd $ (V.!) v i) | i <- [0..n] ]

Score : 500 points

Problem Statement

Let N be a positive integer.

There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}).
Snuke is constructing a new sequence of length 2N, a', by removing exactly N elements from a without changing the order of the remaining elements.
Here, the score of a' is defined as follows: (the sum of the elements in the first half of a') - (the sum of the elements in the second half of a').

Find the maximum possible score of a'.

Constraints

1 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Partial Score

In the test set worth 300 points, N ≤ 1000.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the maximum possible score of a'.

Sample Input 1

2
3 1 4 1 5 9

Sample Output 1

1

When a_2 and a_6 are removed, a' will be (3, 4, 1, 5), which has a score of (3 + 4) - (1 + 5) = 1.

Sample Input 2

1
1 2 3

Sample Output 2

-1

For example, when a_1 are removed, a' will be (2, 3), which has a score of 2 - 3 = -1.

Sample Input 3

3
8 2 2 7 4 6 5 3 8

Sample Output 3

5

For example, when a_2, a_3 and a_9 are removed, a' will be (8, 7, 4, 6, 5, 3), which has a score of (8 + 7 + 4) - (6 + 5 + 3) = 5.


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

solve :: Int -> Int -> Int -> String
solve a b c
    | c >= a && c <= b = "Yes"
    | otherwise = "No"

main :: IO()
main = do
    [a, b, c] <- map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine
    putStrLn $ solve a b c

Score : 100 points

Problem Statement

You are given three integers A, B and C.
Determine whether C is not less than A and not greater than B.

Constraints

-100≤A,B,C≤100

A, B and C are all integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

If the condition is satisfied, print Yes; otherwise, print No.

Sample Input 1

1 3 2

Sample Output 1

Yes

C=2 is not less than A=1 and not greater than B=3, and thus the output should be Yes.

Sample Input 2

6 5 4

Sample Output 2

No

C=4 is less than A=6, and thus the output should be No.

Sample Input 3

2 2 2

Sample Output 3

Yes


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

main :: IO ()
main = do
    [a, b, c] <- fmap read . words <$> getLine :: IO [Int]
    if and [a <= c, c <= b]
        then putStrLn "Yes"
        else putStrLn "No"


main :: IO ()
main = do
  [a,b,c] <- fmap (map read . words) getLine :: IO [Int]

  putStrLn $ if a <= c && c <= b
    then "Yes"
    else "No"


import Data.List
f a r = if null a then r else f (tail a) ((take ((head.head)a) r)++[(r!!((head.head)a))+1]++(((take (((last.head)a)-((head.head))a-1)).(drop ((head.head)a+1))) r)++[(r!!((last.head)a))+1]++(drop ((last.head)a+1) r))
main=do
 [n,m]<-map read.words<$>getLine ::IO[Int]
 a<-map (map (+(-1)).sort.(map read)).map words.lines<$>getContents
 putStr$unlines$map show$f a (replicate n 0)

Score : 200 points

Problem Statement

There are N cities and M roads.
The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally.
There may be more than one road that connects the same pair of two cities.
For each city, how many roads are connected to the city?

Constraints

2≤N,M≤50

1≤a_i,b_i≤N

a_i ≠ b_i

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print the answer in N lines.
In the i-th line (1≤i≤N), print the number of roads connected to city i.

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

City 1 is connected to the 1-st and 3-rd roads.

City 2 is connected to the 1-st and 2-nd roads.

City 3 is connected to the 2-nd road.

City 4 is connected to the 3-rd road.

Sample Input 2

2 5
1 2
2 1
1 2
2 1
1 2

Sample Output 2

5
5

Sample Input 3

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

Sample Output 3

3
3
2
2
2
1
1
2


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

main :: IO ()
main = do
    [n, m] <- fmap read . words <$> getLine :: IO [Int]
    as <- fmap concat . replicateM m $ do
        fmap read . words <$> getLine :: IO [Int]
    forM_ [1 .. n] $ \i -> do
        print $ length (filter (== i) as)


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

main=do
    [n,m]<-map read.words<$>getLine::IO[Int]
    abs<-replicateM m $ map read.words<$>getLine::IO[[Int]]
    mapM_ (print.snd) $ M.toAscList $ foldl (\m [a,b] -> M.insertWith(+)a 1 $ M.insertWith(+)b 1 m) (M.fromList $ zip [1..n] $ repeat 0) abs


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE BangPatterns #-}
module Main where

import           Data.List
import           Control.Monad
import           Debug.Trace
import qualified Data.ByteString.Char8         as BC
import           Data.Maybe                     ( fromJust, fromMaybe )
import qualified Data.Set                      as S
import qualified Data.IntMap.Strict            as IM
import qualified Data.IntMap.Lazy            as IML
import qualified Data.Map.Strict               as M
import           Data.Char
import qualified Data.Array.IArray as A
import qualified Data.Array.Unboxed as UA
import Data.Bits
import Control.Monad.State.Strict
import qualified Data.Array.ST as STA
import qualified Data.Array.IO as IOA
import qualified Data.Array.MArray as MA
import Control.Monad.ST
import System.IO (stdin)
import Control.Arrow
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as UV
import qualified Data.Vector.Generic as GV
import Data.Ix
import Data.Ord (Down(Down))
-- import Control.Lens

debug = False

ts :: Show a => a -> a
ts a = if debug then traceShowId a else a

readTuple2 :: IO (Int, Int)
readTuple2 = do
    [a, b] <- readInts
    return (a, b)

readTuple3 :: IO (Int, Int, Int)
readTuple3 = do
    [a, b, c] <- readInts
    return (a, b, c)

readTuple4 :: IO (Int, Int, Int, Int)
readTuple4 = do
    [a, b, c, d] <- readInts
    return (a, b, c, d)

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

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

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

modN = 1000000007

pow :: Num a => a -> Int -> a
pow base 0 = 1
pow base 1 = base
pow base time
    | odd time = let
        a = pow base (div time 2)
        in
        a * a * base
    | otherwise = let
        a = pow base (div time 2)
        in
        a * a

inv :: ModNum -> ModNum
inv a = pow a $ modN - 2

newtype ModNum = ModNum {getInt :: Int} deriving (Show, Eq, Ord)
instance Num ModNum where
    (+) (ModNum a) (ModNum b) = ModNum $ mod (a + b) modN
    (-) (ModNum a) (ModNum b)
            | a < b = (ModNum $ a + modN) - ModNum b
            | otherwise = ModNum $ mod (a - b) modN
    (*) (ModNum a) (ModNum b) = ModNum $ mod (a * b) modN
    abs (ModNum a)
            | a < 0 = abs . ModNum $ a + modN
            | otherwise = ModNum a
    signum (ModNum a) = ModNum $ signum a
    fromInteger i = abs . ModNum . fromIntegral $ mod i (fromIntegral modN)

mDiv :: ModNum -> ModNum -> ModNum
mDiv a b = a * inv b

solve :: [(Int, Int)] -> Int -> Int
solve ((a, b):xs) k
      | k <= b = a
      | otherwise = solve xs (k - b)

main :: IO ()
main = do
  (n, k) <- readTuple2
  ab <- sortOn fst <$> replicateM n readTuple2
  print $ solve ab k

Score : 300 points

Problem Statement

There is an empty array.
The following N operations will be performed to insert integers into the array.
In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array.
Find the K-th smallest integer in the array after the N operations.
For example, the 4-th smallest integer in the array \{1,2,2,3,3,3\} is 3.

Constraints

1≤N≤10^5

1≤a_i,b_i≤10^5

1≤K≤b_1…+…b_n

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
a_1 b_1
:
a_N b_N

Output

Print the K-th smallest integer in the array after the N operations.

Sample Input 1

3 4
1 1
2 2
3 3

Sample Output 1

3

The resulting array is the same as the one in the problem statement.

Sample Input 2

10 500000
1 100000
1 100000
1 100000
1 100000
1 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000

Sample Output 2

1


import Control.Monad
import Data.List
main = do
 [n,k] <- map read . words <$> getLine
 asbs<-replicateM n (map read . words <$> getLine)
 let as = map head asbs
 let bs = map last asbs
 print ((sort $ f as bs) !! (k-1))

f [] [] = []
f (x:xs) (y:ys) = (replicate y x) ++ (f xs ys)


import           Control.Exception           (assert)
import           Control.Monad
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

type Edge = (Int, Int, Int)
eFrm  (frm, _, _)  = frm
eTo   (_, to, _)   = to
eCost (_, _, cost) = cost

shortestPath :: Int -> V.Vector (Int, Int, Int) -> Int
  -> IO (Maybe (V.Vector Int))
shortestPath s edges numV = do
  let numE = V.length edges
      inf = 10^18 :: Int

  d <- VM.new numV
  VM.set d inf
  VM.write d s 0

  let loop :: Int -> IO Bool
      loop i | i > numV = return True -- cyclic
             | otherwise = do update <- loop2 0 False
                              if update
                                then loop (i+1)
                                else return False

      loop2 :: Int -> Bool -> IO Bool
      loop2 j upd | j == V.length edges = return upd
                  | otherwise = do
                      let e = edges V.! j
                      d_frm <- VM.read d (eFrm e)
                      d_to  <- VM.read d (eTo e)
                      let ucond = d_frm /= inf && d_to > d_frm + eCost e
                          upd' = upd || ucond
                      when ucond $ VM.write d (eTo e) (d_frm + eCost e)
                      loop2 (j+1) upd'

  cyc <- loop 0
  res <- V.freeze d

  if cyc
    then return Nothing
    else return (Just res)

main = do
  [n, m] <- getIntList
  edges <- V.replicateM m $ do
    [a, b, c] <- getIntList
    return (a-1, b-1, (-c))

  maybe_costs <- shortestPath 0 edges n

  case maybe_costs of
    Nothing    -> putStrLn "inf"
    Just costs -> print ((-1) * (costs V.! (n-1)))

Score : 400 points

Problem Statement

There is a directed graph with N vertices and M edges.
The i-th edge (1≤i≤M) points from vertex a_i to vertex b_i, and has a weight c_i.
We will play the following single-player game using this graph and a piece.

Initially, the piece is placed at vertex 1, and the score of the player is set to 0.
The player can move the piece as follows:

When the piece is placed at vertex a_i, move the piece along the i-th edge to vertex b_i. After this move, the score of the player is increased by c_i.

The player can end the game only when the piece is placed at vertex N.
The given graph guarantees that it is possible to traverse from vertex 1 to vertex N.

When the player acts optimally to maximize the score at the end of the game, what will the score be?
If it is possible to increase the score indefinitely, print inf.

Constraints

2≤N≤1000

1≤M≤min(N(N-1),2000)

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

a_i≠b_i (1≤i≤M)

a_i≠a_j or b_i≠b_j (1≤i<j≤M)

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

c_i is an integer.

In the given graph, there exists a path from vertex 1 to vertex N.

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible score at the end of the game, if it is finite. If it is possible to increase the score indefinitely, print inf.

Sample Input 1

3 3
1 2 4
2 3 3
1 3 5

Sample Output 1

7

There are two ways to move the piece to vertex N=3:

vertex 1 → vertex 2 → vertex 3 : score 4+3=7

vertex 1 → vertex 3 : score 5

Thus, the maximum possible score at the end of the game is 7.

Sample Input 2

2 2
1 2 1
2 1 1

Sample Output 2

inf

It is possible to increase the score indefinitely by alternating between vertex 1 and 2.

Sample Input 3

6 5
1 2 -1000000000
2 3 -1000000000
3 4 -1000000000
4 5 -1000000000
5 6 -1000000000

Sample Output 3

-5000000000


import qualified Data.IntMap as M
import Data.Maybe (fromJust)
import Control.Monad
import Data.Array.IO
import Data.List

infinite = maxBound :: Int

main = do
  [n, m] <- map read . words <$> getLine :: IO [Int]
  input <- (\[x, y, z] -> zip3 x y $ map negate z) . transpose . map (map read . words) . lines <$> getContents :: IO [(Int, Int, Int)]
  weight <- newArray (0, n) infinite :: IO (IOUArray Int Int)
  let graph = foldl makeGraph M.empty input
      index = [(i, v) | i <- [1..n], v <- [1..n]]
  writeArray weight 0 0
  writeArray weight 1 0
  foldM (bellmanFord graph n) weight index
  inf <- readArray weight 0
  ans <- readArray weight n
  print =<< getElems weight
  if inf == -1 then putStrLn "inf"
               else print $ negate ans

type Weight = Int
type Vertex = (Int, Weight)
--key:頂点番号, value:隣接点集合
type Graph = M.IntMap Neighbor
--key:ある点の隣接点の頂点番号, value:辺の重さ
type Neighbor = M.IntMap Weight
type Memo = IOUArray Int Int

--隣接リスト
makeGraph :: Graph -> (Int, Int, Int) -> Graph
makeGraph graph (x, y, z) =
  let nX = M.lookup x graph
  in if nX == Nothing
       then M.insert x (addNeighbor (y, z) M.empty) graph
       else M.insert x (addNeighbor (y, z) $ fromJust nX) graph

addNeighbor :: (Int, Int) -> Neighbor -> Neighbor
addNeighbor (i, weight) ne = M.insert i weight ne

bellmanFord :: Graph -> Int -> Memo -> (Int, Int) -> IO Memo
bellmanFord graph n weight (i, v) = do
  b <- readArray weight 0
  case b of
    0 -> do
      let neMaybe = M.lookup v graph
      case neMaybe of
        Nothing -> do
          return weight
        _ -> do
          let neighbors = M.toList $ fromJust neMaybe
          foldM bf' weight neighbors
          return weight
    _ -> do
      return weight
    where bf' weight (e, w) = do
            updatable <- readArray weight 0
            case updatable of
              0 -> do
                distE <- readArray weight e
                distV <- readArray weight v
                let isUpdate = distE > distV + w
                    dist = if isUpdate then distV + w
                                       else distE
                    isClosed = if isUpdate && i == n
                                 then (-1) else 0
                writeArray weight e dist
                writeArray weight 0 isClosed
                return weight
              _ -> do
                return weight


import Data.IntMap.Strict ((!))
import qualified Data.IntMap.Strict as M
import Control.Monad

apply n f x = foldr ($) x (replicate n f)

main = do
 [n,_] <- map read . words <$> getLine
 abcs <- map (map read . words) . lines <$> getContents
 putStrLn $ maybe "inf" show (scoreAttack n abcs)

scoreAttack n abcs = do
 let gf = apply n (move abcs) (M.singleton 1 0)
 let gs = apply n (move abcs) gf
 guard (gf!n == gs!n)
 return (gf!n)

move abcs g = foldr (\[a,b,c] acc -> if M.member a g then M.insertWith max b ((g!a) + c) acc else acc) g abcs


import Data.IntMap ((!))
import qualified Data.IntMap as M
import Control.Monad

apply n f x = foldr ($) x (replicate n f)

main = do
 [n,_] <- map read . words <$> getLine
 abcs <- map (map read . words) . lines <$> getContents
 putStrLn $ maybe "inf" show (scoreAttack n abcs)

scoreAttack n abcs = do
 let gf = apply n (move abcs) (M.singleton 1 0)
 let gs = apply n (move abcs) gf
 guard (gf!n == gs!n)
 return (gf!n)

move abcs g = foldr (\[a,b,c] acc -> if M.member a g then M.insertWith max b ((g!a) + c) acc else acc) g abcs


{-# LANGUAGE FlexibleContexts #-}

import Control.Monad
import Data.STRef
import Data.Array.MArray
import Data.Array.Unboxed
import Data.Array.ST
import Control.Monad.ST
{--
data Score = Inf | Fin Int deriving (Eq,Show)
instance Ord Score where
  compare Inf     Inf = EQ
  compare (Fin _) Inf = LT
  compare Inf (Fin _) = GT
  compare (Fin a) (Fin b)= compare a b

plus::Score -> Score -> Score
plus Inf _ = Inf
plus _ Inf = Inf
plus (Fin a) (Fin b) = Fin (a+b)

--type W_D_graph = Array (Int,Int) Score
--graph implimentation changed: (a,b,c):a to b wieght c
--}
type Graph = [(Int,Int,Int)]

bellman_ford::Graph -> Int -> Int -> UArray Int Int
bellman_ford gr size st = runSTUArray $ do
  tab<- newArray (1,size) maxBound
  writeArray tab st 0
  flag_tab<- newArray (1,size) True
  flagptr<-newSTRef flag_tab
  tab_ptr<-newSTRef tab
  gr_ptr <-newSTRef gr
  forM_ [1..(size-1)] (propagate gr_ptr tab_ptr)
  forM_ [1..size    ] (propagate' gr_ptr tab_ptr flagptr)
  forM_ [1..size    ] (rewrite tab_ptr flagptr)
  return tab
      where rewrite tab_ptr flagptr i = do
                                        tab<-readSTRef tab_ptr
                                        flags<-readSTRef flagptr
                                        i_res<-readArray tab i
                                        i_flag<-readArray flags i
                                        writeArray tab i (if i_flag then i_res else minBound)

{--
  ar<-freeze tab
  let result =listArray (1,size) $(map (\(x,b)->if b then Just x else Nothing) (elems ar))
  return result
--}

propagate::STRef s Graph ->STRef s (STUArray s Int Int)  -> Int -> (ST s ())
propagate gr_ptr tab_ptr _= do
  gr<-readSTRef gr_ptr
  forM_ gr one_edge_update
        where one_edge_update (a,b,c) = do
                              tab<-readSTRef tab_ptr
                              tab_a<-readArray tab a
                              tab_b<-readArray tab b
                              let next_b = min (tab_a+c) tab_b
                              writeArray tab b next_b

propagate'::STRef s Graph ->STRef s (STUArray s Int Int) -> STRef s (STUArray s Int Bool) -> Int -> (ST s ())
propagate' gr_ptr tab_ptr flagptr _= do
  gr<-readSTRef gr_ptr
  forM_ gr one_edge_update
        where one_edge_update (a,b,c) = do
                              tab<-readSTRef tab_ptr
                              tab_a<-readArray tab a
                              tab_b<-readArray tab b
                              let next_b = min (tab_a+c) tab_b
                              let next_flag = (next_b == tab_b)
                              writeArray tab b next_b
                              flags<-readSTRef flagptr
                              writeArray flags b next_flag

n_get::Int ->IO [(Int,Int,Int)]
n_get 0 =return []
n_get n =do
  d<-getLine
  let a:b:w:[]= map read (words d)
  rest <- n_get (n-1)
  return ((a,b,(-w)):rest)

main::IO()
main=do
  nmc<-getLine
  let n:m:[]=map read (words nmc)::[Int]
  gr<-n_get m
  let ans = (bellman_ford gr n 1)!n
  if ans==minBound then do putStr ("inf"++"\n")
                   else do print (-ans)


{-# LANGUAGE FlexibleContexts #-}

import Control.Monad
import Data.STRef
import Data.Array
import Data.Array.ST
import Control.Monad.ST

data Score = Inf | Fin Int deriving (Eq,Show)
instance Ord Score where
  compare Inf     Inf = EQ
  compare (Fin _) Inf = LT
  compare Inf (Fin _) = GT
  compare (Fin a) (Fin b)= compare a b

plus::Score -> Score -> Score
plus Inf _ = Inf
plus _ Inf = Inf
plus (Fin a) (Fin b) = Fin (a+b)

--type W_D_graph = Array (Int,Int) Score
--graph implimentation changed: (a,b,c):a to b wieght c
type Graph = [(Int,Int,Int)]

bellman_ford::Graph -> Int -> Int -> Array Int (Score,Bool)
bellman_ford gr size st = runSTArray $ do
  tab<- newArray (1,size) (Inf,True)
  writeArray tab st (Fin 0,True)
  tab_ptr<-newSTRef tab
  gr_ptr <-newSTRef gr
  forM_ [1..(size-1)] (propagate True  gr_ptr tab_ptr)
  forM_ [1..size    ] (propagate False gr_ptr tab_ptr)
  return tab

{--
  ar<-freeze tab
  let result =listArray (1,size) $(map (\(x,b)->if b then Just x else Nothing) (elems ar))
  return result
--}

propagate::Bool -> STRef s Graph ->STRef s (STArray s Int (Score,Bool))  -> Int -> (ST s ())
propagate flag gr_ptr tab_ptr _= do
  gr<-readSTRef gr_ptr
  forM_ gr one_edge_update
        where one_edge_update (a,b,c) = do
                              tab<-readSTRef tab_ptr
                              tab_a<-readArray tab a
                              tab_b<-readArray tab b
                              let next_b = min (plus (fst(tab_a)) (Fin (-c))) (fst(tab_b))
                              let next_flag = (next_b == (fst(tab_b)))
                              writeArray tab b (next_b, (flag||next_flag) )

n_get::Int ->IO [(Int,Int,Int)]
n_get 0 =return []
n_get n =do
  d<-getLine
  let a:b:w:[]= map read (words d)
  rest <- n_get (n-1)
  return ((a,b,w):rest)

main::IO()
main=do
  nmc<-getLine
  let n:m:[]=map read (words nmc)::[Int]
  gr<-n_get m
  let ans = (bellman_ford gr n 1)!n
  case ans of
    (_,False) -> do putStr ("inf"++"\n")
    (Fin x,True) -> do print (-x)


import qualified Data.Set as S
import Data.Char

div1 x y = let (d,m) = divMod x y in d + signum m

unionMap f s = foldr (\e acc -> S.union acc (f e)) S.empty s

main = do
 [h,w,k] <- map read . words <$> getLine
 m <- filter isPrint <$> getContents
 let ixm = zip [(i,j) | i<-[1..h], j<-[1..w]] m
 let (sx,sy) = fst (head (filter ((=='S') . snd) ixm))
 let cand ((i,j),c) = elem c ".S" && abs (sx-i) + abs (sy-j) <= k
 let ps = S.fromDistinctAscList (map fst (filter cand ixm))
 print (escape h w k ps (sx,sy))

type Height = Int
type Width = Int
type Opened = S.Set Point
type Point = (Int,Int)
type Init = Point

escape :: Height -> Width -> Int -> Opened -> Init -> Int
escape h w k ps s = minimum (map (nmagic h w k) (S.elems (reachable k ps s)))

nmagic :: Height -> Width -> Int -> Point -> Int
nmagic h w k (i,j) = minimum (map (flip div1 k) [i-1,h-i,j-1,w-j]) + 1

reachable :: Int -> Opened -> Point -> Opened
reachable k ps s = reachable' k (S.singleton s) (S.singleton s)
 where
  reachable' 0 acc _ = acc
  reachable' k' acc b = reachable' (k'-1) (S.union acc b') b'
   where b' = S.difference (unionMap (neighbor ps) b) acc

neighbor :: Opened -> Point -> Opened
neighbor ps (i,j) = S.fromList (filter (flip S.member ps) [(i,j),(i+1,j),(i-1,j),(i,j+1),(i,j-1)])

Score : 700 points

Problem Statement

Takahashi is locked within a building.

This building consists of H×W rooms, arranged in H rows and W columns.
We will denote the room at the i-th row and j-th column as (i,j). The state of this room is represented by a character A_{i,j}. If A_{i,j}= #, the room is locked and cannot be entered; if A_{i,j}= ., the room is not locked and can be freely entered.
Takahashi is currently at the room where A_{i,j}= S, which can also be freely entered.

Each room in the 1-st row, 1-st column, H-th row or W-th column, has an exit.
Each of the other rooms (i,j) is connected to four rooms: (i-1,j), (i+1,j), (i,j-1) and (i,j+1).

Takahashi will use his magic to get out of the building. In one cast, he can do the following:

Move to an adjacent room at most K times, possibly zero. Here, locked rooms cannot be entered.

Then, select and unlock at most K locked rooms, possibly zero. Those rooms will remain unlocked from then on.

His objective is to reach a room with an exit. Find the minimum necessary number of casts to do so.

It is guaranteed that Takahashi is initially at a room without an exit.

Constraints

3 ≤ H ≤ 800

3 ≤ W ≤ 800

1 ≤ K ≤ H×W

Each A_{i,j} is # , . or S.

There uniquely exists (i,j) such that A_{i,j}= S, and it satisfies 2 ≤ i ≤ H-1 and 2 ≤ j ≤ W-1.

Input

Input is given from Standard Input in the following format:

H W K
A_{1,1}A_{1,2}...A_{1,W}
:
A_{H,1}A_{H,2}...A_{H,W}

Output

Print the minimum necessary number of casts.

Sample Input 1

3 3 3
#.#
#S.
###

Sample Output 1

1

Takahashi can move to room (1,2) in one cast.

Sample Input 2

3 3 3
###
#S#
###

Sample Output 2

2

Takahashi cannot move in the first cast, but can unlock room (1,2).
Then, he can move to room (1,2) in the next cast, achieving the objective in two casts.

Sample Input 3

7 7 2
#######
#######
##...##
###S###
##.#.##
###.###
#######

Sample Output 3

2


main = getLine >>= putStrLn . solve . map read . words
solve (a:b:c:_) = if elem c [a * i `mod` b | i <-[1..b]] then "YES" else "NO"

Score : 200 points

Problem Statement

We ask you to select some number of positive integers, and calculate the sum of them.

It is allowed to select as many integers as you like, and as large integers as you wish.
You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer.

Your objective is to make the sum congruent to C modulo B.
Determine whether this is possible.

If the objective is achievable, print YES. Otherwise, print NO.

Constraints

1 ≤ A ≤ 100

1 ≤ B ≤ 100

0 ≤ C < B

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

7 5 1

Sample Output 1

YES

For example, if you select 7 and 14, the sum 21 is congruent to 1 modulo 5.

Sample Input 2

2 2 1

Sample Output 2

NO

The sum of even numbers, no matter how many, is never odd.

Sample Input 3

1 100 97

Sample Output 3

YES

You can select 97, since you may select multiples of 1, that is, all integers.

Sample Input 4

40 98 58

Sample Output 4

YES

Sample Input 5

77 42 36

Sample Output 5

NO


import Control.Monad

main = do
    [n, wmax] <- map read . words <$> getLine
    wvs <- map (map read . words) <$> replicateM n getLine
    print $ maximum $ map last $ filter ([wmax + 1, -1] >=) $ map subSum $ subs wvs

subs [] = [[]]
subs (x:xs) = subs xs ++ map (x:) (subs xs)

subSum = foldr (zipWith (+)) [0, 0]

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.


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

readInt = fst . fromJust . BS.readInteger
readIntList = map readInt . BS.words

getIntList = readIntList <$> BS.getLine

paint :: [Integer] -> Integer -> Integer -> Integer
paint [] t' s = s
paint [t] t' s = paint [] t' (s+t')
paint (t:ts) t' s = paint ts'' t' s'
  where
    (ts', ts'') = partition (<= t + t') (t:ts)
    s' = s + last ts' + t' - t

main = do
  [n, t] <- getIntList
  ts <- getIntList
  print $ paint ts t 0

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


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

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

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

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

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

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

main = do
    [a, b, c] <- map (toUpper . head) <$> readString
    putStrLn $ [a, b, c]

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 Control.Applicative
import Control.Monad
import Data.List
import Data.Char (toUpper)

main :: IO ()
main = do
    xss <- words <$> getLine
    putStrLn $ fmap (toUpper . head) xss


import Control.Applicative
import Control.Monad
import Data.List
import Data.Array
import Data.Char
import qualified Data.Set as S

main = do
  a <- getLine
  b <- getLine
  putStrLn $ judge a b

judge::String -> String -> String
judge a b
  | length a > length b = "GREATER"
  | length a < length b = "LESS"
  | a > b = "GREATER"
  | a < b = "LESS"
  | otherwise = "EQUAL"

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


import qualified Data.ByteString.Char8 as BS
import Data.Ord (comparing)

readInt :: String -> Int
readInt = read

main = do
  first <- map (readInt . BS.unpack) . BS.words <$> BS.getLine
  second <- map (readInt . BS.unpack) . BS.words <$> BS.getLine
  print $ case comparing length first second of
    LT -> "LESS"
    EQ -> "EQUAL"
    GT -> "GREATER"


f a b = if a==b then"EQUAL"else if(length a)>(length b)then"GREATER"else if(length a)<(length b)then"LESS"else if(head a)>(head b)then"GREATER"else if(head a)<(head b)then"LESS"else f(tail a)(tail b)
main=getContents>>=putStrLn.(\[a,b] ->f a b).lines


import Control.Monad

rInt :: String -> Int
rInt str = read str :: Int

main :: IO ()
main = do
    [a,b] <- map rInt <$> replicateM 2 getLine
    if a > b then
        putStrLn "GREATER"
    else if a < b then
        putStrLn "LESS"
    else
        putStrLn "EQUAL"


import Control.Applicative
import Control.Arrow

main = do
  n <- getLine
  as <- map read . words <$> getLine :: IO [Int]

  print $ length $ solve as

  where
    solve [] = []
    solve xs = if length a >= length d then a : solve as else d : solve ds
      where
        (a,as) = aux xs 1
        (d,ds) = aux xs (-1)

    aux (x:[]) _ = ([x],[])
    aux (x:y:xs) 1 = if x<=y then first (x:) (aux (y:xs) 1) else ([x], y:xs)
    aux (x:y:xs) (-1) = if x>=y then first (x:) (aux (y:xs) (-1)) else ([x], y:xs)

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 qualified Data.ByteString.Char8 as B
import Data.List

main = do
  _ <- getLine
  as <- map (maybe undefined fst . B.readInt) . B.words <$> B.getLine
  print (sarray as)

sarray as
  | null ds = 1
  | head ds < 0 = length (cut True as)
  | otherwise = length (cut False as)
  where
    ds = filter (/= 0) $ zipWith (-) (tail as) as

cut _ [] = []
cut False xs = () : cut True (dropWhileBy (<=) xs)
cut True xs = () : cut False (dropWhileBy (>=) xs)

takeWhileBy _ [] = []
takeWhileBy _ [x] = [x]
takeWhileBy op (x1:xxs@(x2:_))
  | op x1 x2 = x1 : takeWhileBy op xxs
  | otherwise = [x1]

dropWhileBy _ [] = []
dropWhileBy _ [x] = []
dropWhileBy op (x1:xxs@(x2:_))
  | op x1 x2 = dropWhileBy op xxs
  | otherwise = xxs


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

main :: IO ()
main = do
    [a, b, c] <- fmap read . words <$> getLine :: IO [Int]
    if (b - a) == (c - b)
        then putStrLn "YES"
        else putStrLn "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.


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


import           Control.Monad
import           Control.Applicative

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

  putStrLn $ gen o e
 where
  gen o e =
    concatMap (\(a, b) -> a : [b]) (zip o e)
      ++ if length o > length e then [last o] else ""

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


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

sort []=[]
sort (x:xs)=
  let s=[a|a<-xs,a<=x]
      l=[a|a<-xs,a>x]
  in sort s++[x]++sort l

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

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

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

q = 10^9+7

main = do
 [n,m] <- map read . words <$> getLine
 xs <- map read . words <$> getLine
 ys <- map read . words <$> getLine
 print (ttt n m xs ys)

ttt :: Integer -> Integer -> [Integer] -> [Integer] -> Integer
ttt n m xs ys = mod (adx * ady) q
 where
  adx = foldl' (\acc (k,dx) -> acc + ((k-1)*dx - (n-k)*dx)) 0 idxs
  ady = foldl' (\acc (k,dy) -> acc + ((k-1)*dy - (m-k)*dy)) 0 idys
  idxs = zip [1..n] xs
  idys = zip [1..m] ys

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


import Data.List

--zeros = listArray ('a', 'z') (repeat 0)

count :: String -> [(Char, Int)]
count = map (\cs -> (head cs, length cs)). group . sort

minCount :: [(Char, Int)] -> [(Char, Int)] -> [(Char, Int)]
minCount [] _ = []
minCount _ [] = []
minCount (hd1 : tl1) (hd2 : tl2)
  | fst hd1 == fst hd2 = (fst hd1, min (snd hd1) (snd hd2)) : minCount tl1 tl2
  | fst hd1 < fst hd2 = minCount tl1 (hd2 : tl2)
  | otherwise = minCount (hd1 : tl1) tl2

main = do
  (tail . lines) <$> getContents >>=
    putStrLn . concatMap (uncurry (flip replicate)) . foldl1 minCount . map count


import Control.Monad
import Data.Array
import Data.List
main = replicateM 2 getLine >>= main'
    where
        main' [s, t] = readLn >>= flip replicateM getLine >>= mapM_ putStrLn . solve (toArr s) (toArr t) . fmap (fmap read . words)
        toArr x = array (1, length x) $ zip [1..] x

solve :: Array Int Char -> Array Int Char -> [[Int]] -> [String]
solve s t ([a, b, c, d] : xs) = res : solve s t xs
    where
        cvt arr = (`mod` 3) . foldl' ff 0
            where
                ff acc x
                    | arr ! x == 'A' = 1 + acc
                    | otherwise = 2 + acc

        res
            | cvt s [a..b] == cvt t [c..d] = "YES"
            | otherwise = "NO"

solve _ _ _ = []

Score : 600 points

Problem Statement

Let us consider the following operations on a string consisting of A and B:

Select a character in a string. If it is A, replace it with BB. If it is B, replace with AA.

Select a substring that is equal to either AAA or BBB, and delete it from the string.

For example, if the first operation is performed on ABA and the first character is selected, the string becomes BBBA.
If the second operation is performed on BBBAAAA and the fourth through sixth characters are selected, the string becomes BBBA.

These operations can be performed any number of times, in any order.

You are given two string S and T, and q queries a_i, b_i, c_i, d_i.
For each query, determine whether S_{a_i} S_{{a_i}+1} ... S_{b_i}, a substring of S, can be made into T_{c_i} T_{{c_i}+1} ... T_{d_i}, a substring of T.

Constraints

1 \leq |S|, |T| \leq 10^5

S and T consist of letters A and B.

1 \leq q \leq 10^5

1 \leq a_i \leq b_i \leq |S|

1 \leq c_i \leq d_i \leq |T|

Input

Input is given from Standard Input in the following format:

S
T
q
a_1 b_1 c_1 d_1
...
a_q b_q c_q d_q

Output

Print q lines. The i-th line should contain the response to the i-th query. If S_{a_i} S_{{a_i}+1} ... S_{b_i} can be made into T_{c_i} T_{{c_i}+1} ... T_{d_i}, print YES. Otherwise, print NO.

Sample Input 1

BBBAAAABA
BBBBA
4
7 9 2 5
7 9 1 4
1 7 2 5
1 7 2 4

Sample Output 1

YES
NO
YES
NO

The first query asks whether the string ABA can be made into BBBA.
As explained in the problem statement, it can be done by the first operation.

The second query asks whether ABA can be made into BBBB, and the fourth query asks whether BBBAAAA can be made into BBB.
Neither is possible.

The third query asks whether the string BBBAAAA can be made into BBBA.
As explained in the problem statement, it can be done by the second operation.

Sample Input 2

AAAAABBBBAAABBBBAAAA
BBBBAAABBBBBBAAAAABB
10
2 15 2 13
2 13 6 16
1 13 2 20
4 20 3 20
1 18 9 19
2 14 1 11
3 20 3 15
6 16 1 17
4 18 8 20
7 20 3 14

Sample Output 2

YES
YES
YES
YES
YES
YES
NO
NO
NO
NO


import Data.List
main = getContents >>= print . solve 0 . reverse . sort . tail . map read . words

solve cnt [] = cnt
solve cnt (_:a:as) = solve (cnt + a) (init 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.


main = do
  li <- getLine
  let [a,b] = map read $ words li
  let ans = compute a b
  print ans

compute :: Int -> Int -> Int
compute a b = (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.


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

readInt = fst . fromJust . BS.readInt

readIntList = map readInt . BS.words

getIntList = readIntList <$> BS.getLine

getIntNList n = map readIntList <$> replicateM (fromIntegral n) BS.getLine

calc :: [Int] -> [[Int]] -> Int -> Int -> Int -> Int
calc xs [] i j d = j
calc xs (ys : yss) i j d | d' == 0 = i
                         | j > 50 = calc xs yss (i + 1) i d'
                         | otherwise = calc xs yss (i + 1) j' d''
  where
    [x1, y1] = xs
    [x2, y2] = ys
    d' = abs (x1 - x2) + abs (y1 - y2)
    [d'', j'] = if d' < d then [d', i] else [d, j]

calcAll (xs : xss) yss = do
  print $ calc xs yss 1 51 (10^8+1)
  when (xss /= []) $ calcAll xss yss

main = do
  [n, m] <- getIntList
  xss <- getIntNList n
  yss <- getIntNList m
  calcAll xss yss

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


import Data.List

main = interact $ show . sol . read

sol n | n<=9 = 1
sol n = succ . floor $ log (fromIntegral (m+1)) / log 10
  where
  q = ceiling . sqrt $ fromIntegral n
  ps = fmap ((,) <$> head <*> length) . group $ primeFactors n
  ds = foldr1 ((<*>) . ((*) <$>)) $ fmap (\x -> (fst x^) <$> [0..snd x]) ps
  m = minimum [d | d <- ds, d>=q]

-- | Prime numbers
primes :: Integral a => [a]
primes = 2 : filter ((==1) . length . primeFactors) [3,5..]

primeFactors :: Integral a => a -> [a]
primeFactors 1 = []
primeFactors n = factor n primes

factor :: Integral a => a -> [a] -> [a]
factor n (p:ps)
  | p*p > n        = [n]
  | n `mod` p == 0 = p : factor (n `div` p) (p:ps)
  | otherwise      = factor n ps

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


import Control.Applicative

digits :: Int -> Int
digits = length . show

f :: Int -> Int -> Int
f a b =
  if a < b
    then digits b
    else digits a

searcher :: Int -> Int
searcher n = minimum [f x (n `div` x) |  x <- [1..(n `div` 2)+1], n `mod` x == 0]

main = do
  n <- readLn
  print $ searcher n


import qualified Data.Map as M
import Data.List (sort)
type Primes = M.Map Integer Integer
type Dim = [Integer]
type Coord = [Integer]
type Base = [Integer]
type Index = Integer

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

solve :: Integer -> Int
solve n = minimum $ map f as
    where
        f a = max (length $ show a) (length $ show $ n `div` a)
        as = takeWhile g . sort $ map (eval dim base) [1 .. m]
        g x = (floor' . sqrt . fromIntegral $ n) > x
        ps0 = primes n
        dim = map (+1) $ M.elems ps0
        base = M.keys ps0
        m = product dim

floor' :: Double -> Integer
floor' = floor

eval :: Dim -> Base -> Index -> Integer
eval dim base i = product $ zipWith (^) base coord
    where coord = index2coord dim i

index2coord :: Dim -> Index -> Coord
index2coord dim i = tail . map snd $ scanl f (i,0) dim
    where f (a,_) x = (a `div` x, a `mod` x)

primes :: Integer -> Primes
primes 1 = M.empty
primes n = M.unionWith (+) p1 (primes n')
    where
        v = factor1 n
        p1 = M.singleton v 1
        n' = n `div` v

factor1 :: Integer -> Integer
factor1 n = head ks
    where ks = [x | x <- 2:[3,5..], n `mod` x == 0]


{-# 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 = do
  (_, a, b) <- readInt3 <$> BS.getLine
  vs <- sortBy (flip compare) . readInt64s <$> BS.getLine
  myprint $ solve a b vs

myprint (p, q) = print p >> print q

solve :: Int -> Int -> [Int64] -> (Float, Int64)
solve a b vs = (p, q) where
  p = (/ fromIntegral a) . fromIntegral . sum $ take a vs
  q = sum $ map (comb n) [1..r] where
    r = min (b-a+1) n
    n = length $ filter (== (vs !! a)) vs

comb n r = iterate (scanl1 (+)) [1,1..] !! (n-r) !! r

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

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

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

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

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


{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NumDecimals #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}

import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Monad.ST

import Data.Char
import Data.List
import Data.Maybe

import qualified Data.ByteString.Char8 as B

import Data.Array.ST.Safe
import Data.STRef

import Debug.Trace
import Text.Printf

readInt = readLn :: IO Int
readInteger = readLn :: IO Integer
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine

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

modifyArray a i f = writeArray a i =<< f <$> readArray a i

main = do
	[ w, a, b ] <- readInts
	print $ maximum [ 0, b - ( a + w ), a - ( b + w ) ]

Score : 200 points

Problem Statement

AtCoDeer the deer found two rectangles lying on the table, each with height 1 and width W.
If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of [0,1] and the horizontal range of [a,a+W], and the second rectangle covers the vertical range of [1,2] and the horizontal range of [b,b+W], as shown in the following figure:

AtCoDeer will move the second rectangle horizontally so that it connects with the first rectangle.
Find the minimum distance it needs to be moved.

Constraints

All input values are integers.

1≤W≤10^5

1≤a,b≤10^5

Input

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

W a b

Output

Print the minimum distance the second rectangle needs to be moved.

Sample Input 1

3 2 6

Sample Output 1

1

This input corresponds to the figure in the statement. In this case, the second rectangle should be moved to the left by a distance of 1.

Sample Input 2

3 1 3

Sample Output 2

0

The rectangles are already connected, and thus no move is needed.

Sample Input 3

5 10 1

Sample Output 3

4


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

main = do
 [n,k] <- map read . words <$> getLine
 as <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
 print (noNeed n k as)

noNeed n k as = length $ filter (\a -> all (\s -> sum s - a >= k) (filter (elem a) subsets)) as
 where subsets = filter ((>=k) . sum) (subsequences as)

Score : 600 points

Problem Statement

AtCoDeer the deer has N cards with positive integers written on them. The number on the i-th card (1≤i≤N) is a_i.
Because he loves big numbers, he calls a subset of the cards good when the sum of the numbers written on the cards in the subset, is K or greater.

Then, for each card i, he judges whether it is unnecessary or not, as follows:

If, for any good subset of the cards containing card i, the set that can be obtained by eliminating card i from the subset is also good, card i is unnecessary.

Otherwise, card i is NOT unnecessary.

Find the number of the unnecessary cards. Here, he judges each card independently, and he does not throw away cards that turn out to be unnecessary.

Constraints

All input values are integers.

1≤N≤5000

1≤K≤5000

1≤a_i≤10^9 (1≤i≤N)

Partial Score

300 points will be awarded for passing the test set satisfying N,K≤400.

Input

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

N K
a_1 a_2 ... a_N

Output

Print the number of the unnecessary cards.

Sample Input 1

3 6
1 4 3

Sample Output 1

1

There are two good sets: {2,3} and {1,2,3}.

Card 1 is only contained in {1,2,3}, and this set without card 1, {2,3}, is also good. Thus, card 1 is unnecessary.

For card 2, a good set {2,3} without card 2, {3}, is not good. Thus, card 2 is NOT unnecessary.

Neither is card 3 for a similar reason, hence the answer is 1.

Sample Input 2

5 400
3 1 4 1 5

Sample Output 2

5

In this case, there is no good set. Therefore, all the cards are unnecessary.

Sample Input 3

6 20
10 4 3 10 25 2

Sample Output 3

3


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

main = do
    _ <- getLine
    as <- sort . map (fst . fromJust . BC.readInt) . BC.words <$> BC.getLine
    print $ solve as

solve :: [Int] -> Int
solve xs =
    let js = scanl (+) 0 xs
        noSmallers = zipWith (\x smallers -> smallers*2 < x) xs js
        in
    (+1) . length . takeWhile not . reverse $ noSmallers

Score : 400 points

Problem Statement

Snuke found N strange creatures.
Each creature has a fixed color and size. The color and size of the i-th creature are represented by i and A_i, respectively.

Every creature can absorb another creature whose size is at most twice the size of itself.
When a creature of size A and color B absorbs another creature of size C and color D (C \leq 2 \times A), they will merge into one creature of size A+C and color B.
Here, depending on the sizes of two creatures, it is possible that both of them can absorb the other.

Snuke has been watching these creatures merge over and over and ultimately become one creature.
Find the number of the possible colors of this creature.

Constraints

2 \leq N \leq 100000

1 \leq A_i \leq 10^9

A_i is an integer.

Input

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

N
A_1 A_2 … A_N

Output

Print the number of the possible colors of the last remaining creature after the N creatures repeatedly merge and ultimately become one creature.

Sample Input 1

3
3 1 4

Sample Output 1

2

The possible colors of the last remaining creature are colors 1 and 3.
For example, when the creature of color 3 absorbs the creature of color 2, then the creature of color 1 absorbs the creature of color 3, the color of the last remaining creature will be color 1.

Sample Input 2

5
1 1 1 1 1

Sample Output 2

5

There may be multiple creatures of the same size.

Sample Input 3

6
40 1 30 2 7 20

Sample Output 3

4


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

solve :: Int -> String -> String
solve n s
  | coresp ss s = ss
  | coresp sw s = sw
  | coresp ws s = ws
  | coresp ww s = ww
  | otherwise = "-1"
  where
    ss = "SS" ++ g 'S' 'S' s
    sw = "SW" ++ g 'S' 'W' s
    ws = "WS" ++ g 'W' 'S' s
    ww = "WW" ++ g 'W' 'W' s
    coresp (x:y:rest) (z:zx) =
      let
        l = last rest
        ll = last.init $ (y:rest)
        z' = last zx
      in
        c x z l y && c l z' ll x

g a b (x:y:[]) = []
g a b (x:y:rest) =
  c : g b c (y:rest)
  where
    not 'S' = 'W'
    not 'W' = 'S'
    c = case (b, y) of
          ('S', 'o') -> a
          ('S', 'x') -> not a
          ('W', 'o') -> not a
          ('W', 'x') -> a
g a b _ = []

c :: Char -> Char -> Char -> Char -> Bool
c sw xo l r =
  case (sw, xo) of
    ('S', 'o') -> l == r
    ('S', 'x') -> l /= r
    ('W', 'o') -> l /= r
    ('W', 'x') -> l == r

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 = print =<< foldr1 ((.) (`mod`(10^9+7 :: Int)) . (*)) . enumFromTo 1 <$> readLn

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 ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

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

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

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

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

main = getLine >>= print . foldl ( \p k -> ( p * k ) `mod` 1000000007 ) ( 1 :: Integer ) . ( \x -> [ 1 .. x ] ) . read


main :: IO ()
main = do
  n <- readLn :: IO Int
  print $ foldl1 (\x y -> mod (x * y) 1000000007) [1..n]


main = do
  n <- read <$> getLine
  print $ ((product [1..n]) `mod` (10 ^ 9 + 7))


main=map read.words<$>getLine>>=print.(\[n,m]->(min n (quot m 2))+(quot (m-(min n (quot m 2))) 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


import Data.List

toInt :: String -> Int
toInt = read :: String -> Int

solve :: (Int, Int) -> Int
solve (n, m)
  | 2*n >= m = n
  | otherwise = n + div (m-2*n) 4

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


main = mapM_ (print . solve) . map (map read . words) . lines =<< getContents
solve [n,m] = min n (m`div`2) + max 0 (m-n*2) `div` 4


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

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

solve :: [Integer] -> Integer
solve [n, m]
  | 2 * n <= m = n + (m - 2 * n) `div` 4
  | otherwise = m `div` 2

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


judge hs
  | a>b = "Alice"
  | a<b = "Bob"
  | otherwise = "Draw"
  where
    [a, b] = map ((`mod`13) . subtract 2) hs

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

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


{-# LANGUAGE ScopedTypeVariables, LambdaCase #-}

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

main :: IO ()
main = do
    [a, b] <- map read . words <$> getContents
    let winner = case (a, b) of
                    (c, d) | c == d -> "Draw"
                    (1, _)          -> "Alice"
                    (_, 1)           -> "Bob"
                    _               -> if a > b then "Alice" else "Bob"
    putStrLn winner


import Control.Applicative

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

solve a b
  | a == b = "Draw"
  | a == 1 = "Alice"
  | b == 1 = "Bob"
  | otherwise = if a < b then "Bob" else "Alice"


main :: IO ()
main = do
  ls <- getNums <$> getLine
  let a = head ls
  let b = last ls
  let msg =  if (a == 1)
                  then if (b == 1)
                       then "Draw"
                       else "Alice"
                  else if (b == 1)
                       then "Bob"
                       else if (a == b)
                            then "Draw"
                            else if (a < b)
                            then "Bob"
                            else "Alice"
  putStrLn msg

getNums :: String -> [Int]
getNums = map read . words


import Control.Monad
match a b i j = let m = length b in b == (map (take m . drop j) . take m . drop i) a
main = do
    [n, m] <- map read . words <$> getLine
    a <- replicateM n getLine
    b <- replicateM m getLine
    putStrLn (if or [match a b i j | i <- [0..n-m], j <- [0..n-m]] then "Yes" else "No")

Score : 200 points

Problem Statement

You are given an image A composed of N rows and N columns of pixels, and a template image B composed of M rows and M columns of pixels.

A pixel is the smallest element of an image, and in this problem it is a square of size 1×1.

Also, the given images are binary images, and the color of each pixel is either white or black.

In the input, every pixel is represented by a character: . corresponds to a white pixel, and # corresponds to a black pixel.

The image A is given as N strings A_1,...,A_N.

The j-th character in the string A_i corresponds to the pixel at the i-th row and j-th column of the image A (1≦i,j≦N).

Similarly, the template image B is given as M strings B_1,...,B_M.

The j-th character in the string B_i corresponds to the pixel at the i-th row and j-th column of the template image B (1≦i,j≦M).

Determine whether the template image B is contained in the image A when only parallel shifts can be applied to the images.

Constraints

1≦M≦N≦50

A_i is a string of length N consisting of # and ..

B_i is a string of length M consisting of # and ..

Input

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

N M
A_1
A_2
:
A_N
B_1
B_2
:
B_M

Output

Print Yes if the template image B is contained in the image A. Print No otherwise.

Sample Input 1

3 2
#.#
.#.
#.#
#.
.#

Sample Output 1

Yes

The template image B is identical to the upper-left 2 × 2 subimage and the lower-right 2 × 2 subimage of A. Thus, the output should be Yes.

Sample Input 2

4 1
....
....
....
....
#

Sample Output 2

No

The template image B, composed of a black pixel, is not contained in the image A composed of white pixels.


import Control.Monad
import qualified Data.List as L

main :: IO ()
main = do
  [n, m] <- getNums <$> getLine
  as <- replicateM n getLine
  bs <- replicateM m getLine
  let msg = if (solve as bs (n, m)) then "Yes" else "No"
  putStrLn msg

getNums :: String -> [Int]
getNums = map read . words

solve :: [String] -> [String] -> (Int, Int) -> Bool
solve as bs (n, m) = _solve as bs 0 0
  where
    _solve :: [String] -> [String] -> Int -> Int -> Bool
    _solve as bs x y = if matrixEquals ass bs
                       then True
                       else if x + 1 > n
                            then if y + 1 > n
                                 then False
                                 else _solve as bs 0 (y+1)
                            else _solve as bs (x+1) y
                       where
                         ass = getSubMatrix m x y (n, m) as

getSubMatrix :: Int -> Int -> Int -> (Int, Int) ->  [String] -> [String]
getSubMatrix size x y (n, m)as =
  map _getSubMatrix ass
  where
    ass = if size + x > n || size + y > n
          then ["a"]
          else (take size . drop x) as
    _getSubMatrix ls
      | null ls = "a"
      | otherwise = (take size . drop y) ls

matrixEquals :: [String] -> [String] -> Bool
matrixEquals as bs = all (\(a, b) -> a == b) $ zip as bs


import Data.Array.IO
import Data.List
import Data.IORef
import Data.Array

all_ord::Int -> [[Int]]
all_ord n = map (1:) (permutations [2..n])

main::IO()
main= do
  nmc<-getLine
  let n:m:[]=map read (words nmc)::[Int]
  con<-newArray ((1,1),(n,n)) False
  ptr<-newIORef con
  create_edge ptr m
  st_ar<-freeze con
  print (solver st_ar n)

create_edge::IORef (IOArray (Int,Int) Bool) -> Int -> IO()
create_edge _ 0 = return ()
create_edge pt n = do
  abc<-getLine
  let a:b:[]=map read (words abc) ::[Int]
  ar<-readIORef pt
  writeArray ar (a,b) True
  writeArray ar (b,a) True
  create_edge  pt (n-1)

solver::(Array (Int,Int) Bool) -> Int -> Int
solver ar n = length (filter (check ar) (all_ord n))

check::(Array (Int,Int) Bool) -> [Int] -> Bool
check _  []       =True
check _  (_:[])   =True
check ar (a:b:xs) =(ar!(a,b))&& (check ar (b:xs))

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.


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

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

#define MOD 1000000007

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

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

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

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.