import Data.List
f ::[Int]->[Int]->Integer->Bool
f [] [] d
    |d>=0 =True
    |otherwise=False
f (a:as) (b:bs) d
    |a <= b =f as bs (fromIntegral((b-a) `div` 2) + d)
    |otherwise=f as bs (d - fromIntegral (a-b))

main = do
       e<-getLine
       a<-getLine
       b<-getLine
       let as=sort $ map read (words a)::[Int]
           bs=sort $ map read (words b)::[Int]
       putStrLn $ if f as bs (0::Integer) then "Yes" else "No"

Score : 300 points

Problem Statement

You are given two integer sequences of length N: a_1,a_2,..,a_N and b_1,b_2,..,b_N.
Determine if we can repeat the following operation zero or more times so that the sequences a and b become equal.

Operation: Choose two integers i and j (possibly the same) between 1 and N (inclusive), then perform the following two actions simultaneously:

Add 2 to a_i.

Add 1 to b_j.

Constraints

1 ≤ N ≤ 10 000

0 ≤ a_i,b_i ≤ 10^9 (1 ≤ i ≤ N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 .. a_N
b_1 b_2 .. b_N

Output

If we can repeat the operation zero or more times so that the sequences a and b become equal, print Yes; otherwise, print No.

Sample Input 1

3
1 2 3
5 2 2

Sample Output 1

Yes

For example, we can perform three operations as follows to do our job:

First operation: i=1 and j=2. Now we have a = \{3,2,3\}, b = \{5,3,2\}.

Second operation: i=1 and j=2. Now we have a = \{5,2,3\}, b = \{5,4,2\}.

Third operation: i=2 and j=3. Now we have a = \{5,4,3\}, b = \{5,4,3\}.

Sample Input 2

5
3 1 4 1 5
2 7 1 8 2

Sample Output 2

No

Sample Input 3

5
2 7 1 8 2
3 1 4 1 5

Sample Output 3

No


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE CPP               #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards   #-}
{-# LANGUAGE TupleSections     #-}
{-# LANGUAGE TypeFamilies      #-}

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Data.Bool
import qualified Data.ByteString.Char8       as B
import qualified Data.ByteString.Unsafe      as B
import           Data.Char
import           Data.Function
import qualified Data.IntMap.Strict          as IM
import qualified Data.IntSet                 as IS
import           Data.List                   hiding (insert)
import qualified Data.Map.Strict             as M
import           Data.Monoid
import           Data.Ord
import           Data.Primitive.MutVar
import qualified Data.Set                    as S
import           Data.Tuple
import qualified Data.Vector                 as V
import qualified Data.Vector.Generic         as G
import qualified Data.Vector.Generic.Mutable as GM
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           Unsafe.Coerce

main :: IO ()
main = do
    [n, m] <- map read.words <$> getLine :: IO [Int]
    xs <- U.unfoldrN n parseInt <$> B.getLine
    es <- U.unfoldrN m parseInt2 <$> B.getContents
    putStrLn.maybe"Impossible"show $ solve n xs es

solve :: Int -> U.Vector Int -> U.Vector (Int, Int) -> Maybe Int
solve 1 _ _ = Just 0
solve 2 xs es
  | U.null es = Just $ U.sum xs
  | otherwise = Just 0
solve n xs es = go 0 (toList $ mergePairs iso) $ fromList nonIso
  where
    (iso, nonIso) = partition isSingleton $ forest n xs es
    go :: Int -> [Int] -> Heap (Heap Int) -> Maybe Int
    go !res is hh
--      | traceShow hh False = undefined
      | isSingleton hh = complete res is hh
      | Just (h', hh') <- deleteFindMin hh
      , Just (h'', hh'') <- deleteFindMin hh'
      , Just (x, rx) <- deleteFindMin h'
      , Just (y, ry) <- deleteFindMin h'' =
          case merge rx ry of
              Empty
                | isEmpty hh'' -> complete (res + x + y) is Empty
                | otherwise -> Nothing
              Fork z [] -> go (res + x + y) (z:is) hh''
              rh -> go (res + x + y) is $ insert rh hh''
      | otherwise = Nothing
    complete :: Int -> [Int] -> Heap (Heap Int) -> Maybe Int
    complete res is (Fork h [])
        | length is <= length vs= Just $ res + (sum $ zipWith (+) is vs)
        | otherwise = Nothing
      where
        vs = toList h

forest :: Int -> U.Vector Int -> U.Vector (Int, Int) -> [Heap Int]
forest n xs es = runST $ do
    uf <- newUnionFind n
    U.forM_ es $ \(x, y) ->
      uniteM x y uf

    hs <- U.foldM (\m i -> do
        p <- findM i uf
        return $ IM.insertWith merge p (singleton (U.unsafeIndex xs i)) m
        ) (IM.empty :: IM.IntMap (Heap Int)) (U.generate n id)
    return . map snd $ IM.toAscList hs

isSingleton :: Ord a => Heap a -> Bool
isSingleton (Fork _ []) = True
isSingleton _ = False
-------------------------------------------------------------------------------
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n = U.forM_ $ U.generate n id
rev !n = U.forM_ $ U.iterateN n (subtract 1) (n - 1)
for :: Monad m => Int -> Int -> (Int -> m ()) -> m ()
for !s !t = U.forM_ $ U.generate (t - s) (+s)
{-# INLINE rep #-}
{-# INLINE rev #-}
{-# INLINE for #-}

type Parser a = B.ByteString -> Maybe (a, B.ByteString)

parseInt :: Parser Int
parseInt = B.readInt . B.dropWhile isSpace

parseInt2 :: Parser (Int, Int)
parseInt2 = runStateT $
    (,) <$> StateT (B.readInt . B.dropWhile isSpace)
        <*> StateT (B.readInt . B.unsafeTail)

data UnionFind m = UF
    { parent :: UM.MVector m Int
    , rank   :: UM.MVector m Int
    }

nothing :: Int
nothing = -1
{-# INLINE nothing #-}

newUnionFind :: PrimMonad m => Int -> m (UnionFind (PrimState m))
newUnionFind n = UF `liftM` UM.replicate n nothing `ap` UM.replicate n 0
{-# INLINE newUnionFind #-}

findM :: PrimMonad m => Int -> UnionFind (PrimState m) -> m Int
findM x uf@UF{..} = do
    px <- UM.unsafeRead parent x
    if px == nothing
    then return x
    else do
        ppx <- findM px uf
        UM.unsafeWrite parent x ppx
        return ppx
{-# INLINE findM #-}

uniteM :: PrimMonad m => Int -> Int -> UnionFind (PrimState m) -> m ()
uniteM x y uf@UF{..} = do
    px <- findM x uf
    py <- findM y uf
    when (px /= py) $ do
        rx <- UM.unsafeRead rank px
        ry <- UM.unsafeRead rank py
        case compare rx ry of
            LT -> UM.unsafeWrite parent px py
            GT -> UM.unsafeWrite parent py px
            EQ -> do
                UM.unsafeWrite parent px py
                UM.unsafeWrite rank py (ry + 1)
{-# INLINE uniteM #-}

equivM :: PrimMonad m => Int -> Int -> UnionFind (PrimState m) -> m Bool
equivM x y uf = (==) `liftM` findM x uf `ap` findM y uf
{-# INLINE equivM #-}

-- | O(n)
countM :: PrimMonad m => UnionFind (PrimState m) -> m Int
countM UF{..} = liftM (U.length . U.filter (==nothing)) $ U.unsafeFreeze parent
{-# INLINE countM #-}

data Heap a = Fork !a [Heap a] | Empty deriving Eq

instance Ord a => Ord (Heap a) where
    compare (Fork x _) (Fork y _) = compare x y
    compare Empty (Fork _ _) = LT
    compare (Fork _ _) Empty = GT
    compare _ _ = EQ

instance (Show a, Ord a) => Show (Heap a) where
    show h = show $ toList h

singleton :: a -> Heap a
singleton x = Fork x []
{-# INLINE singleton #-}

isEmpty :: Heap a -> Bool
isEmpty Empty = True
isEmpty _ = False
{-# INLINE isEmpty #-}

insert :: Ord a => a -> Heap a -> Heap a
insert x = merge (Fork x [])
{-# INLINE insert #-}

minElem :: Heap a -> Maybe a
minElem (Fork x _) = Just x
minElem _ = Nothing
{-# INLINE minElem #-}

deleteMin :: Ord a => Heap a -> Maybe (Heap a)
deleteMin (Fork _ hs) = Just $! mergePairs hs
deleteMin _ = Nothing
{-# INLINE deleteMin #-}

deleteFindMin :: Ord a => Heap a -> Maybe (a, Heap a)
deleteFindMin (Fork x hs) = Just (x, mergePairs hs)
deleteFindMin _ = Nothing
{-# INLINE deleteFindMin #-}

merge :: Ord a => Heap a -> Heap a -> Heap a
merge hx@(Fork x hxs) hy@(Fork y hys)
  | x <= y    = Fork x (hy:hxs)
  | otherwise = Fork y (hx:hys)
merge Empty hy = hy
merge hx _ = hx
{-# INLINE merge #-}

mergePairs :: Ord a => [Heap a] -> Heap a
mergePairs (x:y:hs) = merge (merge x y) (mergePairs hs)
mergePairs [x]      = x
mergePairs []       = Empty
{-# INLINE mergePairs #-}

instance Ord a => IsList (Heap a) where
    type Item (Heap a) = a
    fromList xs = mergePairs $ map singleton xs
    toList (Fork x hs) = x : toList (mergePairs hs)
    toList Empty = []

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

Score : 600 points

Problem Statement

You are given a forest with N vertices and M edges. The vertices are numbered 0 through N-1.
The edges are given in the format (x_i,y_i), which means that Vertex x_i and y_i are connected by an edge.

Each vertex i has a value a_i.
You want to add edges in the given forest so that the forest becomes connected.
To add an edge, you choose two different vertices i and j, then span an edge between i and j.
This operation costs a_i + a_j dollars, and afterward neither Vertex i nor j can be selected again.

Find the minimum total cost required to make the forest connected, or print Impossible if it is impossible.

Constraints

1 ≤ N ≤ 100,000

0 ≤ M ≤ N-1

1 ≤ a_i ≤ 10^9

0 ≤ x_i,y_i ≤ N-1

The given graph is a forest.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_0 a_1 .. a_{N-1}
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the minimum total cost required to make the forest connected, or print Impossible if it is impossible.

Sample Input 1

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

Sample Output 1

7

If we connect vertices 0 and 5, the graph becomes connected, for the cost of 1 + 6 = 7 dollars.

Sample Input 2

5 0
3 1 4 1 5

Sample Output 2

Impossible

We can't make the graph connected.

Sample Input 3

1 0
5

Sample Output 3

0

The graph is already connected, so we do not need to add any edges.

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 FlexibleInstances    #-}
{-# LANGUAGE TypeSynonymInstances #-}

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

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

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

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

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

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

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

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

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

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

putLn :: Show a => a -> IO ()
putLn = print

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

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

main = do
  [x] <- readInt
  [a] <- readInt
  [b] <- readInt
  put $ (x - a) `mod` b

Score : 100 points

Problem Statement

You went shopping to buy cakes and donuts with X yen (the currency of Japan).

First, you bought one cake for A yen at a cake shop.
Then, you bought as many donuts as possible for B yen each, at a donut shop.

How much do you have left after shopping?

Constraints

1 \leq A, B \leq 1 000

A + B \leq X \leq 10 000

X, A and B are integers.

Input

Input is given from Standard Input in the following format:

X
A
B

Output

Print the amount you have left after shopping.

Sample Input 1

1234
150
100

Sample Output 1

84

You have 1234 - 150 = 1084 yen left after buying a cake.
With this amount, you can buy 10 donuts, after which you have 84 yen left.

Sample Input 2

1000
108
108

Sample Output 2

28

Sample Input 3

579
123
456

Sample Output 3

0

Sample Input 4

7477
549
593

Sample Output 4

405


{-# OPTIONS_GHC -O #-}
{-# LANGUAGE ViewPatterns #-}

import Control.Monad
import Control.Monad.ST
import Data.List
import Data.Maybe
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as VM
import qualified Data.ByteString.Char8 as B
import qualified Data.IntMap as M

main = do
    (n:m:_)<-map read.words<$>getLine::IO [Int]
    lrds <- replicateM m $ unfoldr (B.readInt.B.dropWhile(==' ')) <$> B.getLine :: IO[[Int]]
    --
    let grp = foldl (\m (l:r:d:_)->M.alter (ins l (-d)) r $ M.alter (ins r d) l m) M.empty lrds
    --
--    print $ map (\(l:r:d:_)->chk n grp l r d) lrds
    putStrLn $ if all (\(l:r:d:_) -> chk n grp l r d) lrds then "Yes" else "No"
--
ins ::Int -> Int -> Maybe [(Int,Int)] -> Maybe [(Int,Int)]
ins n w Nothing = Just [(n,w)]
ins n w (Just nws) = Just ((n,w):nws)
--
chk :: Int -> M.IntMap [(Int,Int)] -> Int -> Int -> Int -> Bool
chk n grp l r d = path d n grp l r
--
path d n grp l r = runST $ do
    nf <- VM.replicate n False :: ST s (VM.STVector s Bool)
    dfs d grp r nf l 0
--
dfs :: Int -> M.IntMap [(Int,Int)] -> Int -> VM.STVector s Bool -> Int -> Int -> ST s Bool
dfs d grp r nf n w =
    if n==r
        then if d==w then return True else return False
        else do
            f <- VM.unsafeRead nf n
            VM.unsafeWrite nf n True
            if f
                then return True
                else and <$> mapM (\(a,b) -> dfs d grp r nf a (b+w)) (grp M.! n)

Score : 400 points

Problem Statement

There are N people standing on the x-axis.
Let the coordinate of Person i be x_i.
For every i, x_i is an integer between 0 and 10^9 (inclusive).
It is possible that more than one person is standing at the same coordinate.

You will given M pieces of information regarding the positions of these people.
The i-th piece of information has the form (L_i, R_i, D_i).
This means that Person R_i is to the right of Person L_i by D_i units of distance, that is, x_{R_i} - x_{L_i} = D_i holds.

It turns out that some of these M pieces of information may be incorrect.
Determine if there exists a set of values (x_1, x_2, ..., x_N) that is consistent with the given pieces of information.

Constraints

1 \leq N \leq 100 000

0 \leq M \leq 200 000

1 \leq L_i, R_i \leq N (1 \leq i \leq M)

0 \leq D_i \leq 10 000 (1 \leq i \leq M)

L_i \neq R_i (1 \leq i \leq M)

If i \neq j, then (L_i, R_i) \neq (L_j, R_j) and (L_i, R_i) \neq (R_j, L_j).

D_i are integers.

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1 D_1
L_2 R_2 D_2
:
L_M R_M D_M

Output

If there exists a set of values (x_1, x_2, ..., x_N) that is consistent with all given pieces of information, print Yes; if it does not exist, print No.

Sample Input 1

3 3
1 2 1
2 3 1
1 3 2

Sample Output 1

Yes

Some possible sets of values (x_1, x_2, x_3) are (0, 1, 2) and (101, 102, 103).

Sample Input 2

3 3
1 2 1
2 3 1
1 3 5

Sample Output 2

No

If the first two pieces of information are correct, x_3 - x_1 = 2 holds, which is contradictory to the last piece of information.

Sample Input 3

4 3
2 1 1
2 3 5
3 4 2

Sample Output 3

Yes

Sample Input 4

10 3
8 7 100
7 9 100
9 8 100

Sample Output 4

No

Sample Input 5

100 0

Sample Output 5

Yes


main = do
  n <- read . concat . words <$> getLine :: IO Double
  let sq = fromIntegral $ floor $ sqrt n :: Double
  putStr $ if n == (sq*sq) then "Yes" else "No"

Score : 200 points

Problem Statement

AtCoDeer the deer has found two positive integers, a and b.
Determine whether the concatenation of a and b in this order is a square number.

Constraints

1 ≤ a,b ≤ 100

a and b are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

If the concatenation of a and b in this order is a square number, print Yes; otherwise, print No.

Sample Input 1

1 21

Sample Output 1

Yes

As 121 = 11 × 11, it is a square number.

Sample Input 2

100 100

Sample Output 2

No

100100 is not a square number.

Sample Input 3

12 10

Sample Output 3

No


main :: IO ()
main = do
  input <- sqrt . read . concat . words <$> getLine
  putStrLn $ if input == fromIntegral (ceiling input) then "Yes" else "No"


main::IO()
main=do
  abc<-getLine
  let ac:bc:[]=words abc
  let num = read (ac++bc)
  putStr (if elem num (takeWhile (num>=) [n*n| n<-[1..100]])then "Yes\n" else "No\n" )


f :: [String] ->[(Int,Int,Int)]
f []=[]
f (x:xs)=let (t1:x1:y1:[])=map read (words x)::[Int]
         in (t1,x1,y1):f xs

f2 ::(Int,Int,Int)->[(Int,Int,Int)]->String
f2 _ [] = "Yes"
f2 (t0,x0,y0) ((t1,x1,y1):xs) = let d = abs(x0-x1)+abs(y0-y1)
                                in if t1-t0>=d && (t1-t0-d) `mod` 2==0 then f2 (t1,x1,y1) xs else "No"

main = do
      e<-getLine
      xs<-getContents
      let ys=f (lines xs)
      putStrLn $ f2 (0,0,0) ys

Score : 300 points

Problem Statement

AtCoDeer the deer is going on a trip in a two-dimensional plane.
In his plan, he will depart from point (0, 0) at time 0, then for each i between 1 and N (inclusive), he will visit point (x_i,y_i) at time t_i.

If AtCoDeer is at point (x, y) at time t, he can be at one of the following points at time t+1: (x+1,y), (x-1,y), (x,y+1) and (x,y-1).
Note that he cannot stay at his place.
Determine whether he can carry out his plan.

Constraints

1 ≤ N ≤ 10^5

0 ≤ x_i ≤ 10^5

0 ≤ y_i ≤ 10^5

1 ≤ t_i ≤ 10^5

t_i < t_{i+1} (1 ≤ i ≤ N-1)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
t_1 x_1 y_1
t_2 x_2 y_2
:
t_N x_N y_N

Output

If AtCoDeer can carry out his plan, print Yes; if he cannot, print No.

Sample Input 1

2
3 1 2
6 1 1

Sample Output 1

Yes

For example, he can travel as follows: (0,0), (0,1), (1,1), (1,2), (1,1), (1,0), then (1,1).

Sample Input 2

1
2 100 100

Sample Output 2

No

It is impossible to be at (100,100) two seconds after being at (0,0).

Sample Input 3

2
5 1 1
100 1 1

Sample Output 3

No


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

main = do
    [n,k] <- map read.words <$> getLine
    xs <- map (format.words) <$> getLineN n :: IO [[Int]]
    let xs' = map (convert k) xs
    putStrLn.show.maximum $ map (count k xs') [(x,y) | x <- [0..2*k-1], y <- [0..2*k-1]] where
        format [x,y,c] = if c == "W" then [read x, read y,0] else [read x,read y,1]

convert :: Int -> [Int] -> (Int,Int)
convert k [x,y,0] = (x `mod` (2*k),y `mod` (2*k))
convert k [x,y,1] = ((x+k) `mod` (2*k),y `mod` (2*k))

count k xs (bx,by) = length $ filter ((==True).g) xs where
    g (px,py) = (abs (px-bx) < k || abs (px-bx) > k+bx) && (abs (py-by) < k || abs (py-by) > k+by)

getLineN :: Int -> IO [String]
getLineN n = replicateM n getLine

Score : 500 points

Problem Statement

AtCoDeer is thinking of painting an infinite two-dimensional grid in a checked pattern of side K.
Here, a checked pattern of side K is a pattern where each square is painted black or white so that each connected component of each color is a K × K square.
Below is an example of a checked pattern of side 3:

AtCoDeer has N desires.
The i-th desire is represented by x_i, y_i and c_i.
If c_i is B, it means that he wants to paint the square (x_i,y_i) black; if c_i is W, he wants to paint the square (x_i,y_i) white.
At most how many desires can he satisfy at the same time?

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 1000

0 ≤ x_i ≤ 10^9

0 ≤ y_i ≤ 10^9

If i ≠ j, then (x_i,y_i) ≠ (x_j,y_j).

c_i is B or W.

N, K, x_i and y_i are integers.

Input

Input is given from Standard Input in the following format:

N K
x_1 y_1 c_1
x_2 y_2 c_2
:
x_N y_N c_N

Output

Print the maximum number of desires that can be satisfied at the same time.

Sample Input 1

4 3
0 1 W
1 2 W
5 3 B
5 4 B

Sample Output 1

4

He can satisfy all his desires by painting as shown in the example above.

Sample Input 2

2 1000
0 0 B
0 1 W

Sample Output 2

2

Sample Input 3

6 2
1 2 B
2 1 W
2 2 B
1 0 B
0 6 W
4 5 W

Sample Output 3

4


import Control.Monad
import Debug.Trace

main = do
  n <- read <$> getLine :: IO Int
  txys <- replicateM n $
    (\(t:x:[y]) -> (t,x,y)) . map readInt . words <$> getLine
  printAnsLn $  solve $ (0,0,0) : txys

solve (_:[]) = True
solve txys @ ((t1,x1,y1):(t2,x2,y2):_) =
--  traceShow (txys,difft,dist) $
  if isPossible then solve (tail txys)
  else False
  where
    difft = t2 - t1
    dist = x2-x1 + y2-y1
    isPossible = difft>=dist && ((dist-difft) `mod` 2==0)

readInt :: String -> Int
readInt = read

printAnsLn b = putStrLn $ if b then "Yes" else "No"


main=interact$f.map read.words
f (_:a:b:_)|odd (b-a)="Borys"|otherwise="Alice"

Score : 300 points

Problem Statement

A game is played on a strip consisting of N cells consecutively numbered from 1 to N.

Alice has her token on cell A. Borys has his token on a different cell B.

Players take turns, Alice moves first.
The moving player must shift his or her token from its current cell X to the neighboring cell on the left, cell X-1, or on the right, cell X+1.
Note that it's disallowed to move the token outside the strip or to the cell with the other player's token.
In one turn, the token of the moving player must be shifted exactly once.

The player who can't make a move loses, and the other player wins.

Both players want to win. Who wins if they play optimally?

Constraints

2 \leq N \leq 100

1 \leq A < B \leq N

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print Alice if Alice wins, Borys if Borys wins, and Draw if nobody wins.

Sample Input 1

5 2 4

Sample Output 1

Alice

Alice can move her token to cell 3.
After that, Borys will be unable to move his token to cell 3, so he will have to move his token to cell 5.
Then, Alice moves her token to cell 4. Borys can't make a move and loses.

Sample Input 2

2 1 2

Sample Output 2

Borys

Alice can't make the very first move and loses.

Sample Input 3

58 23 42

Sample Output 3

Borys


{-# 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 >>= putStrLn . ( "2018" ++ ) . drop 4

Score : 100 points

Problem Statement

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

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

Constraints

S is a string of length 10.

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

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

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

2017/01/07

Sample Output 1

2018/01/07

Sample Input 2

2017/01/31

Sample Output 2

2018/01/31


import Data.List (nub, sort)
import Control.Monad (replicateM)

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

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

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

mochi
  :: [Int] -> Int
mochi = length . nub . sort

main = do
  n <- cReadLn
  ds <- replicateM n cReadLn
  print $ mochi ds

Score : 200 points

Problem Statement

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

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

Constraints

1 ≤ N ≤ 100

1 ≤ d_i ≤ 100

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
d_1
:
d_N

Output

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

Sample Input 1

4
10
8
8
6

Sample Output 1

3

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

Sample Input 2

3
15
15
15

Sample Output 2

1

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

Sample Input 3

7
50
30
50
100
50
80
30

Sample Output 3

4


main = do
    [a, b] <- map read . words <$> getLine
    s <- getLine
    let (as, (h:bs)) = splitAt a s
    putStrLn $ if all (/='-') as && all (/='-') bs && h=='-' then "Yes" else "No"

Score : 100 points

Problem Statement

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

Constraints

1≤M≤23

M is an integer.

Input

Input is given from Standard Input in the following format:

M

Output

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

Sample Input 1

21

Sample Output 1

27

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

Sample Input 2

12

Sample Output 2

36


{- written by MarekCerny.com -}
{-# LANGUAGE ViewPatterns, PatternSynonyms  #-}
{-# LANGUAGE TupleSections                  #-}
{-# LANGUAGE UnicodeSyntax                  #-}
{-# LANGUAGE LambdaCase, MultiWayIf         #-}
import Data.Tuple
import Data.Bits
import Data.Maybe
import Data.Function
import Data.List
import Control.Exception
import qualified Data.HashMap.Strict as M
import Data.Sequence (Seq, (|>), (<|), (><))
import qualified Data.Sequence as S

main = interact $ unlines . sol . allInt . lines

sol :: [[Int]] -> [String]
sol [[n]] = wrap $ show (48-n)

--------------------------------------------------------------------------------
groupOn :: Int -> [a] -> [[a]]
groupOn _ [] = []
groupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds

fromBool :: Num a => Bool -> a
fromBool b = if b then 1 else 0

allInt :: [String] -> [[Int]]
allInt = map ((map read) . words)

swrt :: Ord a => (a, a) -> (a, a)
swrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)

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

toSnd :: a->b-> (a,b)
toSnd x y = (x,y)

toFst :: b->a-> (a,b)
toFst y x = (x,y)

addCnt :: [String] -> [String]
addCnt ls = (show $ length ls) : ls

toBitMap :: Int -> [(Int, Bool)]
toBitMap = toBitMap' 31
  where
    toBitMap' (-1) _ = []
    toBitMap' n v = (n, v .&. (1`shiftL`n) > 0) : toBitMap' (n-1) v
--------------------------------------------------------------------------------
pattern Empty   <- (S.viewl -> S.EmptyL)
pattern x :< xs <- (S.viewl -> x S.:< xs)
pattern xs :> x <- (S.viewr -> xs S.:> x)
--------------------------------------------------------------------------------


{-# LANGUAGE Strict #-}
import           Data.Char (isDigit)

main :: IO ()
main = do
  [a, b] <- map read . words <$> getLine
  s <- getLine
  putStrLn $ if solve a b s then "Yes" else "No"

solve :: Int -> Int -> String -> Bool
solve a _ s = all isDigit xs && y == '-' && all isDigit ys
  where (xs, y:ys) = splitAt a s

Score : 200 points

Problem Statement

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

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

Constraints

1≤A,B≤5

|S|=A+B+1

S consists of - and digits from 0 through 9.

Input

Input is given from Standard Input in the following format:

A B
S

Output

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

Sample Input 1

3 4
269-6650

Sample Output 1

Yes

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

Sample Input 2

1 1
---

Sample Output 2

No

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

Sample Input 3

1 2
7444

Sample Output 3

No


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

type Stations = [(Int, Int, Int)]

cal :: Int -> State Stations Int
cal a = do ss <- get
           case ss == [] of
             True  -> return a
             False -> do ((t, s, e):xs) <- get
                         put xs
                         case a < s of
                           True  -> cal ( t + s )
                           False -> cal ( t + (head [ y * e | y <- [1..], y * e >= a ]) )

main = do
  n  <- readLn
  cs <- replicateM (n-1) getLine
  let tpls = map (ltp . map ri . words) cs
  mapM_ (print . fst) $ map (runState (cal 0)) $ tails tpls

ri :: String -> Int
ri = read

ltp :: [Int] -> (Int, Int, Int)
ltp (x:y:z:ss) = (x, y, z)

Score : 300 points

Problem Statement

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

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

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

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

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

Here, it is guaranteed that F_i divides S_i.

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

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

Constraints

1≤N≤500

1≤C_i≤100

1≤S_i≤10^5

1≤F_i≤10

S_i％F_i=0

All input values are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

3
6 5 1
1 10 1

Sample Output 1

12
11
0

We will travel from Station 1 as follows:

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

11 seconds: arrive at Station 2.

11 seconds: take the train to Station 3.

12 seconds: arrive at Station 3.

We will travel from Station 2 as follows:

10 seconds: take the train to Station 3.

11 seconds: arrive at Station 3.

Note that we should print 0 for Station 3.

Sample Input 2

4
12 24 6
52 16 4
99 2 2

Sample Output 2

187
167
101
0

Sample Input 3

4
12 13 1
44 17 17
66 4096 64

Sample Output 3

4162
4162
4162
0


import Data.Ix

main :: IO()
main = do
    _ <- getLine
    lrs <- getContents
    mapM_ (print . count . map read . words) (lines lrs)
        where
            count [l,r] = length $ filter is2017Like $ range (l,r)
            is2017Like 2 = False
            is2017Like n = isPrime n && isPrime ((n + 1) `div` 2)
            isPrime n = myElem n primes
            myElem n (p:ps)
                | n < p = False
                | n == p = True
                | otherwise = myElem n ps
            primes = [2, 3] ++ [p | p <- primes', p <= 100000]
                where
                    primes' = 5 : f 1 7 primes'
                    f m s (p : ps) = [n | n <- ns, gcd m n == 1] ++ f (m * p) (p * p) ps
                        where ns = [x + y | x <- [s, s + 6 .. p * p - 2], y <- [0, 4]]

Score : 400 points

Problem Statement

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

You are given Q queries.

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

Constraints

1≤Q≤10^5

1≤l_i≤r_i≤10^5

l_i and r_i are odd.

All input values are integers.

Input

Input is given from Standard Input in the following format:

Q
l_1 r_1
:
l_Q r_Q

Output

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

Sample Input 1

1
3 7

Sample Output 1

2

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

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

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

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

Sample Input 2

4
13 13
7 11
7 11
2017 2017

Sample Output 2

1
0
0
1

Note that 2017 is also similar to 2017.

Sample Input 3

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

Sample Output 3

4
4
1
1
1
2


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

Score : 100 points

Problem Statement

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

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

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

Constraints

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

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

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

Sample Input 1

3 8 7 1

Sample Output 1

Left

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

Sample Input 2

3 4 5 2

Sample Output 2

Balanced

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

Sample Input 3

1 7 6 4

Sample Output 3

Right

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


{-# LANGUAGE OverloadedLists     #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Monad
--import           Control.Monad.Loops
import           Data.IORef
import           Data.Maybe
import qualified Data.Text     as T
import qualified Data.Text.IO  as T
import           GHC.Base
import           System.IO

import qualified Data.Array    as A
import qualified Data.IntMap   as I
import           Data.List
import qualified Data.Map      as M
import qualified Data.Set      as S
import qualified Data.Vector   as V

-- for Text
(+.+) = T.append
(!.!) = T.index

-- for Vector
count :: (a -> Bool) -> V.Vector a -> Int
count p = V.length . V.filter p

-- for IO
readT :: Read a => T.Text -> a
readT = read . T.unpack

getLineSpc :: Read a => IO [a]
getLineSpc = do
  t <- T.getLine
  let xs = map readT $ T.split (== ' ') t
  return xs

getLineSpcVec :: Read a => IO (V.Vector a)
getLineSpcVec = do
  t <- T.getLine
  let xs = V.fromList $ map readT $ T.split (== ' ') t
  return xs

----------
-- main --
----------
main :: IO ()
main = specialTrains

specialTrains :: IO ()
specialTrains = do
  [a, b, c, d] :: [Int] <- getLineSpc
  let ab = a + b
      cd = c + d
  if ab > cd
    then
    putStrLn "Left"
    else if ab == cd
    then
    putStrLn "Balanced"
    else
    putStrLn "Right"


f EQ = "Balanced"
f GT = "Left"
f LT = "Right"

main = do
    [a,b,c,d] <- map read . words <$> getLine
    putStrLn $ f $ compare (a+b) (c+d)


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


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
  [x, y] <- map read . words <$> getLine
  print $ solve x y

solve x y = f x y 1
  where
    f acc y len
      | acc * 2 <= y = f (acc * 2) y (len + 1)
      | otherwise = len

Score : 300 points

Problem Statement

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

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

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

Find the maximum possible length of the sequence.

Constraints

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

All input values are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the maximum possible length of the sequence.

Sample Input 1

3 20

Sample Output 1

3

The sequence 3,6,18 satisfies the conditions.

Sample Input 2

25 100

Sample Output 2

3

Sample Input 3

314159265 358979323846264338

Sample Output 3

31


main = do
  [a,b] <- map read.words <$> getLine
  print $ ceiling ((a+b)/2)

Score : 100 points

Problem Statement

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

Constraints

a and b are integers.

1 \leq a, b \leq 100

Input

Input is given from Standard Input in the following format:

a b

Output

Print x rounded up to the nearest integer.

Sample Input 1

1 3

Sample Output 1

2

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

Sample Input 2

7 4

Sample Output 2

6

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

Sample Input 3

5 5

Sample Output 3

5


main = do
  s <- getLine
  [x, y] <- map read . words <$> getLine
  putStr $ solve s x y

solve s x y = judge $ move x y s

move x y [] = [(0, 0, x, y)]
move x y (c:cs) = move x y cs >>= step  c

step 'F' (x0, y0, x1, y1) = [(x0 + 1, y0, x1, y1)]
step 'T' (x0, y0, x1, y1) = [(x0, y0, -y1, x0), (x0, y0, y1, -x0)]

judge zs
  | any goal zs = "Yes"
  | otherwise = "No"

goal (x0, y0, x1, y1) = (x0, y0) == (x1, y1)


import Data.List

main :: IO ()
main = do
    [s, t] <- lines <$> getContents
    putStrLn $ if sort s < sortBy (flip compare) t then "Yes" else "No"

Score : 200 points

Problem Statement

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

Notes

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

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

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

For example, xy < xya and atcoder < atlas.

Constraints

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

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

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

Sample Input 1

yx
axy

Sample Output 1

Yes

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

Sample Input 2

ratcode
atlas

Sample Output 2

Yes

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

Sample Input 3

cd
abc

Sample Output 3

No

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

Sample Input 4

w
ww

Sample Output 4

Yes

Sample Input 5

zzz
zzz

Sample Output 5

No


module Main where

import           Control.Monad
import           Data.List
import           Data.Ord
import           Data.List.Split
import qualified Data.Vector.Unboxed as V

solve [] = 0
solve (as:ass)
  | length as < head as = length as + solve ass
  | otherwise = length as - head as + solve ass

main :: IO ()
main = do
  _ <- getLine
  ass <- group . sortOn Down . map read . words <$> getLine
  print $ solve ass

Score : 300 points

Problem Statement

You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N).
Your objective is to remove some of the elements in a so that a will be a good sequence.

Here, an sequence b is a good sequence when the following condition holds true:

For each element x in b, the value x occurs exactly x times in b.

For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.

Find the minimum number of elements that needs to be removed so that a will be a good sequence.

Constraints

1 \leq N \leq 10^5

a_i is an integer.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum number of elements that needs to be removed so that a will be a good sequence.

Sample Input 1

4
3 3 3 3

Sample Output 1

1

We can, for example, remove one occurrence of 3. Then, (3, 3, 3) is a good sequence.

Sample Input 2

5
2 4 1 4 2

Sample Output 2

2

We can, for example, remove two occurrences of 4. Then, (2, 1, 2) is a good sequence.

Sample Input 3

6
1 2 2 3 3 3

Sample Output 3

0

Sample Input 4

1
1000000000

Sample Output 4

1

Remove one occurrence of 10^9. Then, () is a good sequence.

Sample Input 5

8
2 7 1 8 2 8 1 8

Sample Output 5

5


{-# 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
    bs <- C.getLine
    let n = C.length bs
    let cs = U.unfoldrN n (runParser char) bs
    [x, y] <- map read.words <$> getLine
    putStrLn.bool"No""Yes" $ solve n cs x y

solve :: Int -> U.Vector Char-> Int-> Int -> Bool
solve n cs x y = and
    [ IS.member x $ F.foldl' step (IS.singleton 0) xs
    , IS.member y $ F.foldl' step (IS.singleton 0) ys
    ]
  where
    (xs, ys) = simulate cs
    step s x = IS.union (IS.map (+x) s) (IS.map (subtract x) s)

simulate :: U.Vector Char -> ([Int], [Int])
simulate = goX [] [] . U.toList
  where
    goX resX resY ('F':cs) = goX (length fs:resX) resY ts
      where
        (fs,ts) = span (=='F') $ 'F':cs
    goX resX resY ('T':cs) = goY resX resY cs
    goX resX resY _ = (resX, resY)

    goY resX resY ('F':cs) = goY resX (length fs:resY) ts
      where
        (fs,ts) = span (=='F') $ 'F':cs
    goY resX resY ('T':cs) = goX resX resY cs
    goY resX resY _ = (resX, resY)

-------------------------------------------------------------------------------
-- 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 : 500 points

Problem Statement

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

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

F : Move in the current direction by distance 1.

T : Turn 90 degrees, either clockwise or counterclockwise.

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

Constraints

s consists of F and T.

1 \leq |s| \leq 8 000

x and y are integers.

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

Input

Input is given from Standard Input in the following format:

s
x y

Output

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

Sample Input 1

FTFFTFFF
4 2

Sample Output 1

Yes

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

Sample Input 2

FTFFTFFF
-2 -2

Sample Output 2

Yes

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

Sample Input 3

FF
1 0

Sample Output 3

No

Sample Input 4

TF
1 0

Sample Output 4

No

Sample Input 5

FFTTFF
0 0

Sample Output 5

Yes

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

Sample Input 6

TTTT
1 0

Sample Output 6

No


import Data.Array.Unboxed

--アイテムリスト、考察するスコア上限、結果テーブルのリスト
sub_total_memo::UArray Int Int->Int->[UArray Int Bool]
sub_total_memo ar n =(listArray (0,n) (True:(replicate n False))):[ listArray (0,n) [(ar_i!k)||(ar_i!(if k >= ar!i then k-ar!i else k)) |k<-[0..n] ] | (ar_i,i)<-zip (sub_total_memo ar n) [1..] ]

sub_total_b::[Int]->Int->Bool
sub_total_b items score = let ls = take ((length items)+1) (sub_total_memo (listArray (1,length items) items ) score) in
                             (last ls)!score

--これが部分和問題のソルバ
--DPができたので、あとは問題を帰着していく。

--まずTF列を必要な情報にパースする。
--最初にゼロ文字以上のFがあるという想定でいく。
--同様に末尾にゼロ文字以上のFがあるという想定でいく。
--最初にFを取得する。これはtakeWhileでよい。止まったらそこにTがあるか、リストが付きたことを意味する。
--リストが尽きなければ次に行く。
--次から、TをtakeWhileで取得する。再び、dropした物が空でない限りFをtakewhileする。

t_f_parse::String->(Int,[(Bool,Int)])
t_f_parse str = let fst_F = length (takeWhile ('F'==) str) in
                let rest  = dropWhile ('F'==) str          in
                (fst_F,tf_rest rest)

--boolフラグは奇数個かどうかの判定。奇数ならTrue、偶数ならFalse
--これは入力先頭が空かTである事が保証されている。
tf_rest::String->[(Bool,Int)]
tf_rest [] = []
tf_rest str = let b = (1 == mod (length (takeWhile ('T'==) str)) 2) in
              let fs = length (takeWhile ('F'==)  (dropWhile ('T'==) str)) in
              let rest = dropWhile ('F'==) (dropWhile ('T'==) str) in
              (b,fs):tf_rest rest

tf_xy_ls::[(Bool,Int)]->([Int],[Int])
tf_xy_ls [] = ([],[])
tf_xy_ls ((b,v):rest) = let (x,y)= tf_xy_ls rest in
                        if b then (y,v:x) else (v:x,y)

--FTリストから、x,yの移動幅リストを構成する。
tot_ls::String->([Int],[Int])
tot_ls str= let (x_fst,ls) = t_f_parse str in
            let (x,y) = tf_xy_ls ls in
            (x_fst:x,y)

--与えられた自然数リストを全てを足すか引くかしてスコア関数を作る問題を、部分和問題に帰着させる。
--リストを倍にしておき、スコアに予め全てを足しておく。
trans::([Int],Int)->([Int],Int)
trans (ls,sc) = (map (2*) ls,sc + (sum ls))

--注意！x_fstは絶対にたさなきゃいけない。コーナーケースだ。

solver::String->(Int,Int)->Bool
solver str (x,y) = let (xs,ys) = tot_ls str in
                   let (xxs,xx) = trans (tail xs,x) in
                   let (yys,yy) = trans (ys,y) in
                   (sub_total_b xxs (xx-head xs))&&(sub_total_b yys yy)

main::IO()
main=do
  str<-getLine
  xyc<-getLine
  let x:y:[]=map read (words xyc)
  putStr (if solver str (x,y) then "Yes\n" else "No\n")


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

main :: IO ()
main = do
    -- 文字列の入力
    s <- getLine
    [gx, gy] <- map strToInt . words <$> getLine
    -- 出力
    putStrLn $ solve (init s) (0, 0) (gx, gy)

solve :: String -> (Int, Int) -> (Int, Int) -> String
solve [] (x', y') (x, y) = if x == x' && y == y' then "Yes" else "No"
solve (s:ss) (x', y') (x, y) = case s of
    'T' -> if y' < y then solve ss (y', x') (y, x) else solve ss (y, x') (y', x)
    'F' -> solve ss (x'+1, y') (x, y)


import Control.Applicative

countDivision :: Integer -> [Integer] -> Integer
countDivision count a
  | all even a = countDivision (count+1) (map (\n -> n `quot` 2) a)
  | otherwise = count

main :: IO ()
main = do
  getLine
  a <- (map read . words) <$> getLine
  putStrLn $ show $ countDivision 0 a

Score : 200 points

Problem Statement

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

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

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

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

Constraints

1 \leq N \leq 200

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

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

Sample Input 1

3
8 12 40

Sample Output 1

2

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

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

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

Thus, Snuke can perform the operation at most twice.

Sample Input 2

4
5 6 8 10

Sample Output 2

0

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

Sample Input 3

6
382253568 723152896 37802240 379425024 404894720 471526144

Sample Output 3

8


import Control.Applicative
import Control.Monad
import System.IO.Unsafe
import Control.Monad.ST
import Data.Functor
import Data.Function
import Data.Monoid
import Data.Maybe
import Data.List
import Data.Foldable (foldMap)
import Data.List.Split
import Data.Bits
import Data.Char
import Data.Ix
import Data.Ratio
import Data.Ord
import Data.Tuple
import Data.Array
import Data.Array.IO
import Data.Array.ST
import Data.IORef
import Data.STRef

readInt = read :: String -> Int
readDouble = read :: String -> Double
getInt = readLn :: IO Int
getInts = map readInt . words <$> getLine
getDouble = readLn :: IO Double
sjoin :: (Show a) => [a] -> String
sjoin = unwords . map show
cond :: a -> a -> Bool -> a
cond t f c = if c then t else f
apply2 :: (a -> a -> b) -> [a] -> b
apply2 f [x,y] = f x y
apply3 :: (a -> a -> a -> b) -> [a] -> b
apply3 f [x,y,z] = f x y z
fnBin :: (b -> c -> d) -> (a -> b) -> (a -> c) -> a -> d
fnBin op f g x = op (f x) $ g x
fnTuple :: (a -> b, a -> c) -> a -> (b, c)
fnTuple (f,g) a = (f a, g a)
replace :: (Eq a) => a -> a -> [a] -> [a]
replace x y = map (\z -> if z==x then y else z)
modifyArray :: (Ix i, MArray a e m) => a i e -> i -> (e -> e) -> m ()
modifyArray arr ix f = readArray arr ix >>= writeArray arr ix . f
-- end of templete

f n = if odd n then 0 else 1 + f (div n 2)

main = getInt >> getInts >>= print . minimum . map f


import Data.Function (on)
import Data.List (group, sort, sortBy)

main :: IO ()
main = do
    (_:k:as) <- getParams
    print $ solve k as

getParams :: IO [Int]
getParams = map read . words <$> getContents

solve :: Int -> [Int] -> Int
solve k = length . rewrites k

rewrites :: Int -> [Int] -> [Int]
rewrites k = concat . drop k . sortBy lenDesc . group . sort
  where
    lenDesc = flip compare `on` length

Score : 300 points

Problem Statement

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

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

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

Constraints

1 \leq K \leq N \leq 200000

1 \leq A_i \leq N

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

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

Sample Input 1

5 2
1 1 2 2 5

Sample Output 1

1

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

Sample Input 2

4 4
1 1 2 2

Sample Output 2

0

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

Sample Input 3

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

Sample Output 3

3


{-# 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 qualified System.IO                         as IO
import           Unsafe.Coerce

#define MOD 1000000007

main :: IO ()
main = do
    n <- readLn @Int
    xs <- U.unfoldrN n (runParser int) <$> C.getLine
    let res = solve n xs
    print $ length res
    forM_ res $ \(x, y) -> do
        putStrLn . unwords $ map show [x + 1, y + 1]

solve :: Int -> U.Vector Int -> [(Int, Int)]
solve n xs
    | U.all (== 0) xs = []
    | m + mm >= 0 = map ((,) ii) negIndices ++ (ii, 0) : [(i, i+1)|i<-[0..n-2]]
    | otherwise = map ((,) i) posIndices ++ (i, n-1) : [(j, j-1)|j<-reverse[1..n-1]]
  where
    (m, i) = U.minimum $ U.imap (flip (,)) xs
    (mm, ii) = U.maximum $ U.imap (flip (,)) xs
    negIndices = U.toList . U.map fst . U.filter ((<0).snd) $ U.indexed xs
    posIndices = U.toList . U.map fst . U.filter ((>0).snd) $ U.indexed xs

-------------------------------------------------------------------------------
-- Utils
-------------------------------------------------------------------------------
rep :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n = U.forM_ $ U.generate n id
{-# INLINE rep #-}
rev :: Monad m => Int -> (Int -> m ()) -> m ()
rev !n = U.forM_ $ U.iterateN n (subtract 1) (n - 1)
{-# INLINE rev #-}
infixl 8 `shiftRL`, `unsafeShiftRL`
shiftRL = unsafeShiftRL
{-# INLINE shiftRL #-}
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 #-}

Score : 600 points

Problem Statement

Snuke has an integer sequence, a, of length N. The i-th element of a (1-indexed) is a_{i}.

He can perform the following operation any number of times:

Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.

He would like to perform this operation between 0 and 2N times (inclusive) so that a satisfies the condition below. Show one such sequence of operations.
It can be proved that such a sequence of operations always exists under the constraints in this problem.

Condition: a_1 \leq a_2 \leq ... \leq a_{N}

Constraints

2 \leq N \leq 50

-10^{6} \leq a_i \leq 10^{6}

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{N}

Output

Let m be the number of operations in your solution. In the first line, print m.
In the i-th of the subsequent m lines, print the numbers x and y chosen in the i-th operation, with a space in between.
The output will be considered correct if m is between 0 and 2N (inclusive) and a satisfies the condition after the m operations.

Sample Input 1

3
-2 5 -1

Sample Output 1

2
2 3
3 3

After the first operation, a = (-2,5,4).

After the second operation, a = (-2,5,8), and the condition is now satisfied.

Sample Input 2

2
-1 -3

Sample Output 2

1
2 1

After the first operation, a = (-4,-3) and the condition is now satisfied.

Sample Input 3

5
0 0 0 0 0

Sample Output 3

0

The condition is satisfied already in the beginning.


import Data.List

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

getAns :: [Int] -> Int -> Int
getAns a k = sum . take n $ sort l
  where
    l = map length . group $ sort a
    n = length l - k

main = do
  [n, k] <- map toInt . words <$> getLine
  a <- map toInt . words <$> getLine
  print $ getAns a k


import Data.List

main :: IO ()
main = do
  [n,k] <- map (read :: String -> Int) . words <$> getLine
  an <- mySort . map (read :: String -> Int) . words <$> getLine
  print $ ans k an

ans :: Int -> [Int] -> Int
ans k an
  | l <= k = 0
  | otherwise = sum $ take (l-k) an
  where l = length an

mySort :: [Int] -> [Int]
mySort xs = sort . map snd $ foldl func [] xs where
  func [] k = [(k,1)]
  func ((a,b):acc) k = if a == k then (a,b+1):acc else (a,b):func acc k


import Data.List
import Debug.Trace

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

solve as k =
  ans
  where
    as' = group $ sort as
    len = length as'
    as'' = sortOn length as'
    check as@(a:_) k' acc
      | k'<=k = acc
      | otherwise =
--        traceShow (as,k',acc) $
        check (tail as) (k'-1) (acc + length a)
    ans = check as'' len 0


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

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

solve :: Int -> [Int] -> Int
solve k = sum . drop k . sortBy (flip compare) . change . sortBy compare

change :: [Int] -> [Int]
change [] = []
change (x:xs) = go x 1 xs
    where go n c [] = [c]
          go n c (x:xs)
            | n == x = go n (c+1) xs
            | otherwise = c : go x 1 xs

main :: IO ()
main = do
    [n, k] <- getInts
    ls <- getInts
    print (solve k ls)


main = do
  [n, a, b] <- map read . words <$> getLine
  print $ b `min` (n * a)

Score : 100 points

Problem Statement

You are parking at a parking lot. You can choose from the following two fee plans:

Plan 1: The fee will be A×T yen (the currency of Japan) when you park for T hours.

Plan 2: The fee will be B yen, regardless of the duration.

Find the minimum fee when you park for N hours.

Constraints

1≤N≤20

1≤A≤100

1≤B≤2000

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

When the minimum fee is x yen, print the value of x.

Sample Input 1

7 17 120

Sample Output 1

119

If you choose Plan 1, the fee will be 7×17=119 yen.

If you choose Plan 2, the fee will be 120 yen.

Thus, the minimum fee is 119 yen.

Sample Input 2

5 20 100

Sample Output 2

100

The fee might be the same in the two plans.

Sample Input 3

6 18 100

Sample Output 3

100


import Data.Char

main :: IO ()
main = do
    n <- getLine
    putStrLn $ if read n `mod` foldl (\t s -> t + digitToInt s) 0 n == 0 then "Yes" else "No"

Score : 200 points

Problem Statement

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

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

Constraints

1?N?10^8

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

12

Sample Output 1

Yes

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

Sample Input 2

57

Sample Output 2

No

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

Sample Input 3

148

Sample Output 3

No


import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.List
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM

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

main = do
    [n,c] <- getIntList
    st <- replicateM n $ do
        [s,t,c] <- getIntList
        return (s,t+1)
    let result = VU.create $ do
            vec <- VUM.replicate 100002 (0 :: Int)
            forM_ st $ \(s,t) -> do
                VUM.modify vec succ s
                VUM.modify vec pred t
            return vec
    let ans = VU.maximum $ VU.scanl (+) 0 result
    print ans

Score : 400 points

Problem Statement

Joisino is planning to record N TV programs with recorders.

The TV can receive C channels numbered 1 through C.

The i-th program that she wants to record will be broadcast from time s_i to time t_i (including time s_i but not t_i) on Channel c_i.

Here, there will never be more than one program that are broadcast on the same channel at the same time.

When the recorder is recording a channel from time S to time T (including time S but not T), it cannot record other channels from time S-0.5 to time T (including time S-0.5 but not T).

Find the minimum number of recorders required to record the channels so that all the N programs are completely recorded.

Constraints

1≤N≤10^5

1≤C≤30

1≤s_i<t_i≤10^5

1≤c_i≤C

If c_i=c_j and i≠j, either t_i≤s_j or s_i≥t_j.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N C
s_1 t_1 c_1
:
s_N t_N c_N

Output

When the minimum required number of recorders is x, print the value of x.

Sample Input 1

3 2
1 7 2
7 8 1
8 12 1

Sample Output 1

2

Two recorders can record all the programs, for example, as follows:

With the first recorder, record Channel 2 from time 1 to time 7. The first program will be recorded. Note that this recorder will be unable to record other channels from time 0.5 to time 7.

With the second recorder, record Channel 1 from time 7 to time 12. The second and third programs will be recorded. Note that this recorder will be unable to record other channels from time 6.5 to time 12.

Sample Input 2

3 4
1 3 2
3 4 4
1 4 3

Sample Output 2

3

There may be a channel where there is no program to record.

Sample Input 3

9 4
56 60 4
33 37 2
89 90 3
32 43 1
67 68 3
49 51 3
31 32 3
70 71 1
11 12 3

Sample Output 3

2


import Data.List

reservation = replicate 200001 0

main = do
  getLine
  chan <- map (:[]) . sortBy compareC . map (readC . words) . lines <$> getContents
  putStrLn $ show . maximum . foldl reserve reservation . map cut . foldl1 connect $ chan

readC :: [String] -> (Double, Double, Int)
readC s = ((read :: String -> Double) (s !! 0), (read :: String -> Double) (s !! 1), (read :: String -> Int) (s !! 2))

compareC :: (Double, Double, Int) -> (Double, Double, Int) -> Ordering
compareC (s1, t1, c1) (s2, t2, c2) = if c1 /= c2 then compare c1 c2
                                                 else compare s1 s2

equalC :: (Double, Double, Int) -> (Double, Double, Int) -> Bool
equalC (_, _, c1) (_, _, c2) = c1 == c2

isConnect :: (Double, Double, Int) -> (Double, Double, Int) -> Bool
isConnect (_, t, _) (s, _, _) = t == s

connect :: [(Double, Double, Int)] -> [(Double, Double, Int)] -> [(Double, Double, Int)]
connect x (y:_) = if equalC (last x) y && isConnect (last x) y
                    then (init x) ++ [connect' (last x) y]
                    else x ++ [y]

connect' :: (Double, Double, Int) -> (Double, Double, Int) -> (Double, Double, Int)
connect' (s, _, c) (_, t, _) = (s, t, c)

cut :: (Double, Double, Int) -> (Int, Int, Int)
cut (s, t, c) = (truncate $ s * 2 - 1, truncate t, c)

reserve :: [Int] -> (Int, Int, Int) -> [Int]
reserve r (s, t, _) = (take s r) ++ (map (+1) (drop s . take (t+1) $ r)) ++ (drop (t+1) r)


{-# LANGUAGE BangPatterns #-}
import Control.Arrow (second)
import Control.Monad
import Control.Monad.Fix
import Data.List (foldl')
import qualified Data.Vector.Unboxed as VU
import qualified Data.ByteString.Char8 as B
import System.IO.Unsafe
import Debug.Trace

solve :: Int -> Int -> VU.Vector (Int,Int) -> Int
solve !n !k !wds = nearest $ let i = findInternal 1 in search i (2*i) where
  calc !t = VU.sum $ VU.map (\(w,d) -> if t > w then (t-w) `div` d + 1 else 0) wds
  nearest !t = VU.maximum $ VU.map (\(w,d) -> w + ((t-w) `div` d) * d) wds

  findInternal !t = last $ takeWhile (\t -> calc t < k) $ map (\k -> 2^k) [0..]

  search !a !b =
    let c = (a + b) `div` 2
        u = calc c
    in
      if u == k then c
      else if u < k then search (c+1) b
      else search a (c-1)

main = do
  let readInt = fmap (second B.tail) . B.readInt

  nk <- VU.unfoldrN 2 readInt <$> B.getLine
  wds <- VU.replicateM (nk VU.! 0) ((\vec -> (vec VU.! 0, vec VU.! 1)) . VU.unfoldrN 2 readInt <$> B.getLine)
  print $ solve (nk VU.! 0) (nk VU.! 1) wds

Score : 100 points

Problem Statement

In your garden, there is a long and narrow flowerbed that stretches infinitely to the east. You have decided to plant N kinds of flowers in this empty flowerbed. For convenience, we will call these N kinds of flowers Flower 1, 2, …, N. Also, we will call the position that is p centimeters from the west end of the flowerbed Position p.

You will plant Flower i (1 ≤ i ≤ N) as follows: first, plant one at Position w_i, then plant one every d_i centimeters endlessly toward the east. That is, Flower i will be planted at the positions w_i, w_i + d_i, w_i + 2 d_i, … Note that more than one flower may be planted at the same position.

Find the position at which the K-th flower from the west is planted. If more than one flower is planted at the same position, they are counted individually.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^9

1 ≤ w_i ≤ 10^{18}

1 ≤ d_i ≤ 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
w_1 d_1
:
w_N d_N

Output

When the K-th flower from the west is planted at Position X, print the value of X. (The westmost flower is counted as the 1-st flower.)

Sample Input 1

2 6
20 10
25 15

Sample Output 1

50

Two kinds of flowers are planted at the following positions:

Flower 1: Position 20, 30, 40, 50, 60, …

Flower 2: Position 25, 40, 55, 70, 85, …

The sixth flower from the west is the Flower 1 planted at Position 50. Note that the two flowers planted at Position 40 are counted individually.

Sample Input 2

3 9
10 10
10 10
10 10

Sample Output 2

30

Three flowers are planted at each of the positions 10, 20, 30, … Thus, the ninth flower from the west is planted at Position 30.

Sample Input 3

1 1000000000
1000000000000000000 1000000000

Sample Output 3

1999999999000000000


import Data.Array (listArray, (!))

lucas n = lucas' n where
  memo = listArray (0,n) $ fmap lucas' [0..n]
  lucas' 0 = 2
  lucas' 1 = 1
  lucas' n = memo ! (n-1) + memo ! (n-2)

main :: IO ()
main = getLine >>=
  print .
  lucas .
  (read :: String -> Int)

Score : 200 points

Problem Statement

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

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

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

L_0=2

L_1=1

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

Constraints

1≤N≤86

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

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the N-th Lucas number.

Sample Input 1

5

Sample Output 1

11

L_0=2

L_1=1

L_2=L_0+L_1=3

L_3=L_1+L_2=4

L_4=L_2+L_3=7

L_5=L_3+L_4=11

Thus, the 5-th Lucas number is 11.

Sample Input 2

86

Sample Output 2

939587134549734843


import Control.Monad
import Control.Applicative
import Data.Functor
import Data.List
import Data.List.Split
import Data.Char
import Data.Ord
import Data.Array.IO

readInt = read :: String -> Int
getInt = readLn :: IO Int
getInts = map readInt . words <$> getLine
sjoin :: (Show a) => [a] -> String
sjoin = unwords . map show
cond :: a -> a -> Bool -> a
cond t f c = if c then t else f
-- end of templete

wf arr range = do
    forM_ range $ \k -> do
        forM_ range $ \i -> do
            forM_ range $ \j -> do
                before <- readArray arr (i,j)
                after1 <- readArray arr (i,k)
                after2 <- readArray arr (k,j)
                writeArray arr (i,j) $ min before $ after1 + after2

cost arr (-1) = return 0
cost arr n = readArray arr (n,1)

main = do
    arr <- newArray ((0,0),(9,9)) 1234 :: IO (IOUArray (Int, Int) Int)
    [h, w] <- getInts
    forM_ [0..9] $ \i -> do
        cs <- getInts
        forM_ (zip cs [0..9]) $ \(c, j) -> writeArray arr (i,j) c
    wf arr [0..9]
    concat <$> replicateM h getInts >>= sequence . map (cost arr) >>= print . sum
    return ()

Score : 400 points

Problem Statement

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

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

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

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

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

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

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

Constraints

1≤H,W≤200

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

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

-1≤A_{i,j}≤9

All input values are integers.

There is at least one digit on the wall.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

12

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

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

Sample Input 2

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

Sample Output 2

0

Note that she may not need to change any digit.

Sample Input 3

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

Sample Output 3

47


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

main :: IO ()
main = do
    [n, _, w] <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
    as <- V.fromList . map (fst . fromJust . B.readInt) . B.words <$> B.getLine
    print $ if n == 1
        then abs (w - V.head as)
        else max (abs (V.last as - V.last (V.init as))) (abs (V.last as - w))

Score : 500 points

Problem Statement

We have a deck consisting of N cards. Each card has an integer written on it. The integer on the i-th card from the top is a_i.

Two people X and Y will play a game using this deck. Initially, X has a card with Z written on it in his hand, and Y has a card with W written on it in his hand. Then, starting from X, they will alternately perform the following action:

Draw some number of cards from the top of the deck. Then, discard the card in his hand and keep the last drawn card instead. Here, at least one card must be drawn.

The game ends when there is no more card in the deck. The score of the game is the absolute difference of the integers written on the cards in the two players' hand.

X will play the game so that the score will be maximized, and Y will play the game so that the score will be minimized. What will be the score of the game?

Constraints

All input values are integers.

1 \leq N \leq 2000

1 \leq Z, W, a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N Z W
a_1 a_2 ... a_N

Output

Print the score.

Sample Input 1

3 100 100
10 1000 100

Sample Output 1

900

If X draws two cards first, Y will draw the last card, and the score will be |1000 - 100| = 900.

Sample Input 2

3 100 1000
10 100 100

Sample Output 2

900

If X draws all the cards first, the score will be |1000 - 100| = 900.

Sample Input 3

5 1 1
1 1 1 1 1

Sample Output 3

0

Sample Input 4

1 1 1
1000000000

Sample Output 4

999999999


main=do
 n<-readLn
 print (f n 1)
  where f n i = if i^2>n then (i-1)^2 else (f n (i+1))

Score : 200 points

Problem Statement

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

Constraints

1 \leq N \leq 10^9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the largest square number not exceeding N.

Sample Input 1

10

Sample Output 1

9

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

Sample Input 2

81

Sample Output 2

81

Sample Input 3

271828182

Sample Output 3

271821169


main :: IO ()
main = do
  n <- readLn
  let sqs = map (^2) [1..n]
  print $ comp sqs n

comp :: [Int] -> Int -> Int
comp (x:y:ys) n
  | x == n = x
  | y > n = x
  | otherwise = comp ys n


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

solve n = go 1
  where
    go x
      | x ^ 2 > n = (x - 1) ^ 2
      | otherwise = go (x + 1)


import qualified Data.Char as Char
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import qualified Text.Printf as Printf
import qualified Control.Monad as Monad

bisectLeft :: (Ord a) => a -> [a] -> Int
bisectLeft n xs = bisectLeft' 0 (length xs) n xs

bisectLeft' :: (Ord a) => Int -> Int -> a -> [a] -> Int
bisectLeft' lo hi n xs = if lo >= hi then lo else
                    if n <= (xs !! mid) then bisectLeft' lo mid n xs
                      else bisectLeft' (mid + 1) hi n xs
                    where mid = (lo + hi) `div` 2

bisectRight :: (Ord a) => a -> [a] -> Int
bisectRight n xs = bisectRight' 0 (length xs) n xs

bisectRight' :: (Ord a) => Int -> Int -> a -> [a] -> Int
bisectRight' lo hi n xs = if lo >= hi then hi else
                    if n < (xs !! mid) then bisectRight' lo mid n xs
                      else bisectRight' (mid + 1) hi n xs
                    where mid = (lo + hi) `div` 2

main :: IO ()
main = do
  n <- (read :: String -> Int) <$> getLine
  as <- List.sort . map (read :: String -> Int) . words <$> getLine
  bs <- map (read :: String -> Int) . words <$> getLine
  cs <- List.sort . map (read :: String -> Int) . words <$> getLine
  print $ foldl (+) 0 $ map (\ b -> (bisectLeft b as) * (n - bisectRight b cs)) bs

Score : 300 points

Problem Statement

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

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

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

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

Constraints

1 \leq N \leq 10^5

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

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

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

All input values are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of different altars that Ringo can build.

Sample Input 1

2
1 5
2 4
3 6

Sample Output 1

3

The following three altars can be built:

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

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

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

Sample Input 2

3
1 1 1
2 2 2
3 3 3

Sample Output 2

27

Sample Input 3

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

Sample Output 3

87


import Control.Monad
main=do
 [a,b]<-replicateM 2 readLn
 print$(a+2)/2

Score : 100 points

Problem Statement

Takahashi is a user of a site that hosts programming contests.

When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows:

Let the current rating of the user be a.

Suppose that the performance of the user in the contest is b.

Then, the new rating of the user will be the avarage of a and b.

For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000.

Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest.

Find the performance required to achieve it.

Constraints

0 \leq R, G \leq 4500

All input values are integers.

Input

Input is given from Standard Input in the following format:

R
G

Output

Print the performance required to achieve the objective.

Sample Input 1

2002
2017

Sample Output 1

2032

Takahashi's current rating is 2002.

If his performance in the contest is 2032, his rating will be the average of 2002 and 2032, which is equal to the desired rating, 2017.

Sample Input 2

4500
0

Sample Output 2

-4500

Although the current and desired ratings are between 0 and 4500, the performance of a user can be below 0.


solve ::Int -> Int -> Int -> Int
solve 0 _ a = a
solve n k a = min (solve n1 k (a + k)) (solve n1 k (a * 2))
  where
    n1 = n - 1

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

Score : 200 points

Problem Statement

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

Operation A: The displayed value is doubled.

Operation B: The displayed value increases by K.

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

Constraints

1 \leq N, K \leq 10

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
K

Output

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

Sample Input 1

4
3

Sample Output 1

10

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

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

Sample Input 2

10
10

Sample Output 2

76

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

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

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


f n k r=if n==0 then r else if k<r then f (n-1) k (r+k) else f (n-1) k (2*r)
main=do
 n<-readLn
 k<-readLn
 print$f n k 1


{-# LANGUAGE FlexibleContexts #-}
import Control.Applicative
import Control.Monad.ST
import Control.Monad
import Control.Monad.State
import Control.Monad.List
import Data.Array.ST
import Data.STRef
import Data.List
import Data.Tuple
import Data.Maybe
import Debug.Trace

modifyArray arr i f = readArray arr i >>= \x -> writeArray arr i (f x)
listToTuple2 [a,b] = (a,b)

bridge n edges = runST $ do
  ord <- newArray (1,n) (-1) :: ST s (STArray s Int Int)
  low <- newArray (1,n) (-1) :: ST s (STArray s Int Int)

  order <- newSTRef 0 :: ST s (STRef s Int)

  let
    dfs cur par order es = do
      let (connected, others) = partition ((==cur) . fst) es
      readSTRef order >>= \x -> writeArray ord cur x >> writeArray low cur x
      modifySTRef order (+1)

      forM_ connected $ \(_,next) -> do
        nextOrder <- readArray ord next
        when (next /= par) $ do
          if nextOrder == -1 then do
            dfs next cur order others
            readArray low next >>= \x -> modifyArray low cur (\y -> min y x)
            else
            readArray ord next >>= \x -> modifyArray low cur (\y -> min y x)

  dfs 1 (-1) order edges

  res <- forM edges $ \(u,v) -> do
    a <- readArray ord u
    b <- readArray low v
    return $ if a<b then Just (u,v) else Nothing
  return $ catMaybes res

main = do
  (n,m) <- listToTuple2 . map read . words <$> getLine :: IO (Int,Int)
  edges <- map (listToTuple2 . map read . words) . lines <$> getContents :: IO [(Int,Int)]

  print $ length $ bridge n (edges ++ (map swap edges))

Score : 300 points

Problem Statement

You are given an undirected connected graph with N vertices and M edges that does not contain self-loops and double edges.

The i-th edge (1 \leq i \leq M) connects Vertex a_i and Vertex b_i.

An edge whose removal disconnects the graph is called a bridge.

Find the number of the edges that are bridges among the M edges.

Notes

A self-loop is an edge i such that a_i=b_i (1 \leq i \leq M).

Double edges are a pair of edges i,j such that a_i=a_j and b_i=b_j (1 \leq i<j \leq M).

An undirected graph is said to be connected when there exists a path between every pair of vertices.

Constraints

2 \leq N \leq 50

N-1 \leq M \leq min(N(N−1)⁄2,50)

1 \leq a_i<b_i \leq N

The given graph does not contain self-loops and double edges.

The given graph is connected.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the number of the edges that are bridges among the M edges.

Sample Input 1

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

Sample Output 1

4

The figure below shows the given graph:

The edges shown in red are bridges. There are four of them.

Sample Input 2

3 3
1 2
1 3
2 3

Sample Output 2

0

It is possible that there is no bridge.

Sample Input 3

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

Sample Output 3

5

It is possible that every edge is a bridge.


import qualified Data.IntMap as IM
import qualified Data.Vector as V
main=print.solve.map(map read.words).lines=<<getContents
solve::[[Int]]->Int
solve([n,m]:abs)=fst(f(-1)0 IM.empty)-1 where
  f s t v=(c+if p==w IM.! t then 1 else 0,w)where
    p=IM.size v
    (c,w)=foldr h(0,IM.insert t p v)$g V.! t
    h i a@(c,v)
      |i==s=a
      |IM.member i v=(c,IM.adjust(min(v IM.! i))t v)
      |otherwise=let(d,w)=f t i v in(c+d,IM.adjust(min(w IM.! i))t w)
  g=V.accum(flip(:))(V.replicate n[])$concatMap(\[a,b]->[(a,b),(b,a)])$map(map pred)abs


-- Try AtCoder
-- author: Leonardone @ NEETSDKASU

import qualified Data.ByteString.Char8 as C
import qualified Data.IntMap as M
import Data.Maybe (fromJust)

main = putStrLn . solve . C.lines =<< C.getContents

solve [_,ds,_,ts] = if ans then "YES" else "NO"
    where
        ds' = map (fst . fromJust . C.readInt) $ C.words ds
        ts' = map (fst . fromJust . C.readInt) $ C.words ts
        mp = foldl (\m x -> M.insertWith (+) x 1 m) M.empty ds'
        mp' = foldl (\m x -> M.insertWith (+) x (-1) m) mp ts'
        ans = (minimum $ M.elems mp') >= 0

Score : 200 points

Problem Statement

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

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

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

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

Constraints

1 \leq N \leq 200,000

1 \leq D_i \leq 10^9

1 \leq M \leq 200,000

1 \leq T_i \leq 10^9

All numbers in the input are integers.

Partial Score

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

5
3 1 4 1 5
3
5 4 3

Sample Output 1

YES

Sample Input 2

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

Sample Output 2

NO

Not enough 1600s.

Sample Input 3

1
800
5
100 100 100 100 100

Sample Output 3

NO

Sample Input 4

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

Sample Output 4

YES


main=do
 [n,m,k]<-map read.words<$>getLine
 putStrLn$if null[1|i<-[0..n],j<-[0..m-1],m*i+n*j-2*i*j==k]then"No"else"Yes"

Score : 200 points

Problem Statement

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

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

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

Constraints

1 \leq N,M \leq 1000

0 \leq K \leq NM

Input

Input is given from Standard Input in the following format:

N M K

Output

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

Sample Input 1

2 2 2

Sample Output 1

Yes

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

Sample Input 2

2 2 1

Sample Output 2

No

Sample Input 3

3 5 8

Sample Output 3

Yes

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

Sample Input 4

7 9 20

Sample Output 4

No


main :: IO ()
main = do
    [n, m, k] <- map read . words <$> getLine
    putStrLn $ if solve n m k then "Yes" else "No"

solve :: Int -> Int -> Int -> Bool
solve n m k =
    k `elem` [ i * (m - j) + (n - i) * j | i <- [0 .. n], j <- [0 .. m] ]


module Main where

main :: IO()
main = do
  [n,m,k] <- map read . words <$> getLine
  putStrLn $ solve n m k

solve :: Int -> Int -> Int -> String
solve n m k = if subSolve n m k then "Yes" else "No"

subSolve :: Int -> Int -> Int -> Bool
subSolve n m k = anyForList . map (\(hp, wp) ->
  case cellsNum n m hp wp of
    Just x  -> x == k
    Nothing -> False) $ zip [1..n] [1..m]

allPattern :: [a] -> [a] -> [(a,a)]
allPattern (x:xs) xss' = map (\x' -> (x, x')) xss' ++ allPattern xs xss'

cellsNum :: Int -> Int -> Int -> Int -> Maybe Int
cellsNum h w hp wp
  | h < hp || w < wp  = Nothing
  | otherwise         = Just $ (w - wp) * hp + (h - hp) * wp

anyForList :: [Bool] -> Bool
anyForList [] = False
anyForList (b:bs)
  | b         = True
  | otherwise = anyForList bs


main :: IO ()
main = do
  _ <- readLn :: IO Int
  k <- readLn :: IO Int
  bs <- map read . words <$> getLine :: IO [Int]
  print $ sum $ map (\x -> if k-x < x then 2*(k-x) else 2*x) bs

Score : 200 points

Problem Statement

There are N balls in the xy-plane. The coordinates of the i-th of them is (x_i, i).
Thus, we have one ball on each of the N lines y = 1, y = 2, ..., y = N.

In order to collect these balls, Snuke prepared 2N robots, N of type A and N of type B.
Then, he placed the i-th type-A robot at coordinates (0, i), and the i-th type-B robot at coordinates (K, i).
Thus, now we have one type-A robot and one type-B robot on each of the N lines y = 1, y = 2, ..., y = N.

When activated, each type of robot will operate as follows.

When a type-A robot is activated at coordinates (0, a), it will move to the position of the ball on the line y = a, collect the ball, move back to its original position (0, a) and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.

When a type-B robot is activated at coordinates (K, b), it will move to the position of the ball on the line y = b, collect the ball, move back to its original position (K, b) and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.

Snuke will activate some of the 2N robots to collect all of the balls. Find the minimum possible total distance covered by robots.

Constraints

1 \leq N \leq 100

1 \leq K \leq 100

0 < x_i < K

All input values are integers.

Inputs

Input is given from Standard Input in the following format:

N
K
x_1 x_2 ... x_N

Outputs

Print the minimum possible total distance covered by robots.

Sample Input 1

1
10
2

Sample Output 1

4

There are just one ball, one type-A robot and one type-B robot.

If the type-A robot is used to collect the ball, the distance from the robot to the ball is 2, and the distance from the ball to the original position of the robot is also 2, for a total distance of 4.

Similarly, if the type-B robot is used, the total distance covered will be 16.

Thus, the total distance covered will be minimized when the type-A robot is used. The output should be 4.

Sample Input 2

2
9
3 6

Sample Output 2

12

The total distance covered will be minimized when the first ball is collected by the type-A robot, and the second ball by the type-B robot.

Sample Input 3

5
20
11 12 9 17 12

Sample Output 3

74


main = do
    _ <- getLine
    k <- fmap read getLine :: IO Int
    xs <- fmap (map read . words) getLine :: IO [Int]
    print $ solve k xs

solve k = foldl (\acc x -> acc + min (x * x) ((k - x) * (k - x))) 0