check [] = True
check (x:[]) = True
check (x1:x2:xs) =
    if x1 == x2
    then False
    else check (x2:xs)

main = do
    moji <-  getLine

    putStrLn $ if check moji then "Good" else "Bad"

Score : 100 points

Problem Statement

The door of Snuke's laboratory is locked with a security code.

The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same.

You are given the current security code S. If S is hard to enter, print Bad; otherwise, print Good.

Constraints

S is a 4-character string consisting of digits.

Input

Input is given from Standard Input in the following format:

S

Output

If S is hard to enter, print Bad; otherwise, print Good.

Sample Input 1

3776

Sample Output 1

Bad

The second and third digits are the same, so 3776 is hard to enter.

Sample Input 2

8080

Sample Output 2

Good

There are no two consecutive digits that are the same, so 8080 is not hard to enter.

Sample Input 3

1333

Sample Output 3

Bad

Sample Input 4

0024

Sample Output 4

Bad


import Data.Bits
import Data.List
import Control.Monad
import qualified Data.Vector.Unboxed as V
import Control.Monad.ST
import Data.Maybe (fromMaybe)
import qualified Data.ByteString.Lazy.Char8 as B
import Debug.Trace

main :: IO ()
main = do
  as <- getLine

  putStrLn $ if (maximum (map length $ group as)) >= 2 then "Bad" else "Good"

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

Submitted source-code file size, in bytes.

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

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


{-# LANGUAGE BangPatterns #-}

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

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

solve (x:xs) = if isBad x xs then "Bad" else "Good"

isBad c (x:xs) = if c == x then True else isBad x xs
isBad _ []     = False

-- 以下ライブラリ

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

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

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

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

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


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

main = do
  [a, b, c, d] <- map (read::String -> Integer) . words <$> getLine
  print $ b - a + 1 - ((b - a + 1) `div` c) - ((b - a + 1) `div` d) + ((b - a + 1) `div` (c * d))

Score : 300 points

Problem Statement

You are given four integers A, B, C, and D. Find the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Constraints

1\leq A\leq B\leq 10^{18}

1\leq C,D\leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Sample Input 1

4 9 2 3

Sample Output 1

2

5 and 7 satisfy the condition.

Sample Input 2

10 40 6 8

Sample Output 2

23

Sample Input 3

314159265358979323 846264338327950288 419716939 937510582

Sample Output 3

532105071133627368


{-# LANGUAGE
  ScopedTypeVariables, BangPatterns, TupleSections, ExplicitForAll,
  LambdaCase, MultiWayIf, Unsafe, RecordWildCards, FlexibleContexts, CPP,
  NoMonomorphismRestriction, GADTs, PatternGuards, MagicHash, UnboxedTuples,
  RankNTypes, EmptyDataDecls, EmptyCase, ViewPatterns, PolyKinds,
  TypeFamilies #-}
{-# OPTIONS_GHC -O2 #-}

import Prelude
import Data.Bits
import Data.List
import Data.Maybe
import Data.Tuple
import Data.Ord
import Data.Int
import Data.Word
import Data.Char
import Data.Ratio
import Data.Function
import Data.STRef
import Data.IORef
import Data.Monoid
import Data.Functor
import System.IO
import Control.Arrow
import Control.Applicative
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.State.Strict
import Control.Monad.ST
import Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)
import qualified Control.Monad.ST.Lazy as STL
-- import Control.Monad.ST.Safe
import Control.DeepSeq
import Data.Coerce
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.ByteString.Builder as BSB
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as IMS
import qualified Data.IntMap.Lazy as IML
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
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
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Storable.Mutable as VSM
import qualified Data.Vector.Primitive as VP
import qualified Data.Vector.Primitive.Mutable as VPM
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import qualified Data.Attoparsec.ByteString.Char8 as Atto
import Debug.Trace
import GHC.Exts (build, Int(..), Int#,
                 (+#), (*#), (-#), (<#), (>=#), (==#), quotRemInt#,
                 remInt#, uncheckedIShiftRL#, andI#, orI#,
                isTrue#)

main :: IO ()
main = do
  [n,k] <- map readInt . words <$> getLine
  if k > ((n-1)*(n-2)) `shiftR` 1 then print (-1) else do
  let takes = ((n-1)*(n-2)) `shiftR` 1 - k
  print $ n-1 + takes
  putStr $ unlines $ map (\(u,v) -> shows u $ ' ':show v)
    $ ([(i,n) | i <- [1..n-1]]++)
    $ take takes
    $ [(x,y)| x <-[1..n-1],y<-[x+1..n-1]]

#define IL(f) {-# INLINE f #-}; f

IL(evalVals) :: [a] -> [a]
evalVals xs = build $ \c n -> foldr (c $!) n xs
IL(forceVals) :: (NFData a) => [a] -> [a]
forceVals xs = build $ \c n -> foldr (c $!!) n xs

rInt :: StateT BSL.ByteString Maybe Int
IL(rInt) = StateT $ BSL.readInt . BSL.dropWhile (<'!')
rIntS :: StateT BS.ByteString Maybe Int
IL(rIntS) = StateT $ BS.readInt . BS.dropWhile (<'!')

unlessM, whenM :: (Monad m) => m Bool -> m () -> m ()
IL(whenM) = (. flip when) . (>>=)
IL(unlessM) = (. flip unless) . (>>=)

IL(wrA) = A.writeArray
IL(rdA) = A.readArray
IL(mdA) = \arr f !i -> do
  ai <- rdA arr i
  let fai = f ai
  wrA arr i fai
  return (ai,fai)
{-# INLINE mdA' #-}
mdA' = \arr f !i -> do
  !ai <- rdA arr i
  let !fai = f ai
  wrA arr i fai
  return (ai,fai)
IL(swapA) = \arr !i !j -> do
  ai <- rdA arr i
  wrA arr i =<< rdA arr j
  wrA arr j ai

#define D(f,r,d)\
  IL(f) :: Integral a=>a->d; f=fromIntegral;\
  IL(r) :: String->d; r=read
#define C(f,r,g,h,d) D(f,r,d);\
  g,h :: RealFrac a=>a->d; IL(g)=floor; IL(h)=ceiling
C(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)
C(toInt,readInt,floorInt,ceilInt,Int)
C(toI8,readI8,floorI8,ceilI8,Int8)
C(toI16,readI16,floorI16,ceilI16,Int16)
C(toI32,readI32,floorI32,ceilI32,Int32)
C(toI64,readI64,floorI64,ceilI64,Int64)
C(toWord,readWord,floorWord,ceilWord,Word)
C(toW8,readW8,floorW8,ceilW8,Word8)
C(toW16,readW16,floorW16,ceilW16,Word16)
C(toW32,readW32,floorW32,ceilW32,Word32)
C(toW64,readW64,floorW64,ceilW64,Word64)
D(toDouble,readDouble,Double)
D(toFloat,readFloat,Float)
#undef D
#undef C

#define N(f,g,h,a,m)\
  IL(f) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e);\
  f=A.newArray;\
  IL(g) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e);\
  g=A.newArray_;\
  IL(h) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> [e] -> m (a i e);\
  h=A.newListArray
#define C(a,m)
N(newIOA,newIOA_,newIOAL,IOArray,IO)
N(newSTA,newSTA_,newSTAL,STArray s,ST s)
#undef C
#define C(a,m) MArray (a) e (m),
N(newIOUA,newIOUA_,newIOUAL,IOUArray,IO)
N(newSTUA,newSTUA_,newSTUAL,STUArray s,ST s)
#undef C
#undef N

#undef IL

Score: 500 points

Problem Statement

Does there exist an undirected graph with N vertices satisfying the following conditions?

The graph is simple and connected.

The vertices are numbered 1, 2, ..., N.

Let M be the number of edges in the graph. The edges are numbered 1, 2, ..., M, the length of each edge is 1, and Edge i connects Vertex u_i and Vertex v_i.

There are exactly K pairs of vertices (i,\ j)\ (i < j) such that the shortest distance between them is 2.

If there exists such a graph, construct an example.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq K \leq \frac{N(N - 1)}{2}

Input

Input is given from Standard Input in the following format:

N K

Output

If there does not exist an undirected graph with N vertices satisfying the conditions, print -1.

If there exists such a graph, print an example in the following format (refer to Problem Statement for what the symbols stand for):

M
u_1 v_1
:
u_M v_M

If there exist multiple graphs satisfying the conditions, any of them will be accepted.

Sample Input 1

5 3

Sample Output 1

5
4 3
1 2
3 1
4 5
2 3

This graph has three pairs of vertices such that the shortest distance between them is 2: (1,\ 4), (2,\ 4), and (3,\ 5). Thus, the condition is satisfied.

Sample Input 2

5 8

Sample Output 2

-1

There is no graph satisfying the conditions.


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

main :: IO ()
main = readLine >>= printRes . solve
    where
        printRes (m, vs)
            | m == -1 = print m
            | otherwise = print m >> mapM_ (putStrLn . unwords . map show) vs

solve :: [Int] -> (Int, [[Int]])
solve [n, k]
    | k > an = (-1, [])
    | otherwise = (m, es)
    where
        an = ((n - 2) * (n - 1)) `div` 2
        m = n - 1 + an - k
        es = addEdges base (an - k) 2 3
        base = map (\x -> [1, x]) [2..n]
        addEdges acc c v u
            | u > n = addEdges acc c (v + 1) (v + 2)
            | c > 0 = addEdges ([v, u] : acc) (c - 1) v (u + 1)
            | otherwise = acc

readLine :: IO [Int]
readLine = unfoldr (fmap (second (maybe B.empty snd . B.uncons)) . B.readInt) <$> B.getLine

readContents :: Int -> IO [[Int]]
readContents = flip replicateM readLine


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns          #-}
{-# LANGUAGE CPP                   #-}
{-# LANGUAGE LambdaCase            #-}
{-# LANGUAGE MagicHash             #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE MultiWayIf            #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE TupleSections         #-}
{-# LANGUAGE TypeFamilies          #-}
{-# LANGUAGE ViewPatterns          #-}

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.ST
import           Control.Monad.State.Strict
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.Unsafe      as B
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
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.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 qualified System.IO                   as IO
import           Unsafe.Coerce

main :: IO ()
main = do
    n <- readLn
    xys <- U.unfoldrN n parseInt2 <$> C.getContents
    print $ solve n xys

lim :: Int
lim = 100001

injX :: Int -> Int
injX x = x

injY :: Int -> Int
injY y = y + lim

nothing :: Int
nothing = -1

solve :: Int -> U.Vector (Int, Int) -> Int
solve n xys = runST $ do
    uf <- newUnionFind $ 2 * lim

    U.forM_ xys $ \(x, y) -> do
        uniteM uf (injX x) (injY y)

    freqX <- UM.replicate (2 * lim) 0
    U.forM_ (U.generate lim id) $ \x -> do
        fx <- findM uf x
        UM.modify freqX (+1) fx

    U.foldM (\acc x -> do
        fx <- findM uf x
        if x == fx
        then do
            xSize <- UM.read freqX fx
            size <- sizeM uf fx
            return $! acc + xSize * (size - xSize)
        else return acc
        ) (-n) $ U.generate (2 * lim) id

-------------------------------------------------------------------------------
newtype UnionFind m = UF { parent :: UM.MVector m Int }

newUnionFind :: PrimMonad m => Int -> m (UnionFind (PrimState m))
newUnionFind n = UF <$> UM.replicate n (-1)
{-# INLINE newUnionFind #-}

findM :: PrimMonad m => UnionFind (PrimState m) -> Int -> m Int
findM uf x = go x return
  where
    go !x k = do
        px <- UM.unsafeRead (parent uf) x
        if px < 0
        then k x
        else go px $ \ppx -> do
            UM.unsafeWrite (parent uf) x ppx
            k ppx
{-# INLINE findM #-}

sizeM :: PrimMonad m => UnionFind (PrimState m) -> Int -> m Int
sizeM uf = fix $ \loop x -> do
    px <- UM.unsafeRead (parent uf) x
    if px < 0
    then return $! negate px
    else loop px
{-# INLINE sizeM #-}

uniteM :: PrimMonad m => UnionFind (PrimState m) -> Int -> Int -> m Bool
uniteM uf x y = do
    px <- findM uf x
    py <- findM uf y
    if px == py
    then return False
    else do
        rx <- UM.unsafeRead (parent uf) px
        ry <- UM.unsafeRead (parent uf) py
        if rx < ry
        then do
            UM.unsafeModify (parent uf) (+ry) px
            UM.unsafeWrite (parent uf) py px
        else do
            UM.unsafeModify (parent uf) (+rx) py
            UM.unsafeWrite (parent uf) px py
        return True
{-# INLINE uniteM #-}

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

-- | O(n)
countGroupM :: PrimMonad m => UnionFind (PrimState m) -> m Int
countGroupM uf = U.length . U.filter (<0) <$> U.unsafeFreeze (parent uf)
{-# INLINE countGroupM #-}

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

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

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

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

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

Score : 600 points

Problem Statement

There are N dots in a two-dimensional plane. The coordinates of the i-th dot are (x_i, y_i).

We will repeat the following operation as long as possible:

Choose four integers a, b, c, d (a \neq c, b \neq d) such that there are dots at exactly three of the positions (a, b), (a, d), (c, b) and (c, d), and add a dot at the remaining position.

We can prove that we can only do this operation a finite number of times. Find the maximum number of times we can do the operation.

Constraints

1 \leq N \leq 10^5

1 \leq x_i, y_i \leq 10^5

If i \neq j, x_i \neq x_j or y_i \neq y_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the maximum number of times we can do the operation.

Sample Input 1

3
1 1
5 1
5 5

Sample Output 1

1

By choosing a = 1, b = 1, c = 5, d = 5, we can add a dot at (1, 5). We cannot do the operation any more, so the maximum number of operations is 1.

Sample Input 2

2
10 10
20 20

Sample Output 2

0

There are only two dots, so we cannot do the operation at all.

Sample Input 3

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

Sample Output 3

16

We can do the operation for all choices of the form a = 1, b = 1, c = i, d = j (2 \leq i,j \leq 5), and no more. Thus, the maximum number of operations is 16.


{-# LANGUAGE BangPatterns #-}
import Control.Arrow
import Control.Monad.Fix
import Data.Char
import Data.Int
import Data.Foldable
import Data.List
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
import qualified Data.ByteString.Char8 as B

solve :: Int -> Int -> Int
solve !x !a | x < a  = 0
            | x >= a = 10

main = do
  let readInt :: Integral a => B.ByteString -> Maybe (a, B.ByteString)
      readInt = fmap (first fromIntegral . second B.tail) . B.readInt

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

Score : 100 points

Problem Statement

X and A are integers between 0 and 9 (inclusive).

If X is less than A, print 0; if X is not less than A, print 10.

Constraints

0 \leq X, A \leq 9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X A

Output

If X is less than A, print 0; if X is not less than A, print 10.

Sample Input 1

3 5

Sample Output 1

0

3 is less than 5, so we should print 0.

Sample Input 2

7 5

Sample Output 2

10

7 is not less than 5, so we should print 10.

Sample Input 3

6 6

Sample Output 3

10

6 is not less than 6, so we should print 10.


{-# LANGUAGE
  ScopedTypeVariables, BangPatterns, TupleSections, ExplicitForAll,
  LambdaCase, MultiWayIf, Unsafe, RecordWildCards, FlexibleContexts, CPP,
  NoMonomorphismRestriction, GADTs, PatternGuards, MagicHash, UnboxedTuples,
  RankNTypes, EmptyDataDecls, EmptyCase, ViewPatterns, PolyKinds,
  TypeFamilies #-}
{-# OPTIONS_GHC -O2 #-}

import Prelude
import Data.Bits
import Data.List
import Data.Maybe
import Data.Tuple
import Data.Ord
import Data.Int
import Data.Word
import Data.Char
import Data.Ratio
import Data.Function
import Data.STRef
import Data.IORef
import Data.Monoid
import Data.Functor
import System.IO
import Control.Arrow
import Control.Applicative
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.State.Strict
import Control.Monad.ST
import Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)
import qualified Control.Monad.ST.Lazy as STL
-- import Control.Monad.ST.Safe
import Control.DeepSeq
import Data.Coerce
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.ByteString.Builder as BSB
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as IMS
import qualified Data.IntMap.Lazy as IML
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
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
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Storable.Mutable as VSM
import qualified Data.Vector.Primitive as VP
import qualified Data.Vector.Primitive.Mutable as VPM
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import qualified Data.Attoparsec.ByteString.Char8 as Atto
import Debug.Trace
import GHC.Exts (build, Int(..), Int#,
                 (+#), (*#), (-#), (<#), (>=#), (==#), quotRemInt#,
                 remInt#, uncheckedIShiftRL#, andI#, orI#,
                isTrue#)

main :: IO ()
main = do
  [x,a] <- map readInt . words <$> getLine
  print $ if x < a then 0 else 10

#define IL(f) {-# INLINE f #-}; f

IL(evalVals) :: [a] -> [a]
evalVals xs = build $ \c n -> foldr (c $!) n xs
IL(forceVals) :: (NFData a) => [a] -> [a]
forceVals xs = build $ \c n -> foldr (c $!!) n xs

rInt :: StateT BSL.ByteString Maybe Int
IL(rInt) = StateT $ BSL.readInt . BSL.dropWhile (<'!')
rIntS :: StateT BS.ByteString Maybe Int
IL(rIntS) = StateT $ BS.readInt . BS.dropWhile (<'!')

unlessM, whenM :: (Monad m) => m Bool -> m () -> m ()
IL(whenM) = (. flip when) . (>>=)
IL(unlessM) = (. flip unless) . (>>=)

IL(wrA) = A.writeArray
IL(rdA) = A.readArray
IL(mdA) = \arr f !i -> do
  ai <- rdA arr i
  let fai = f ai
  wrA arr i fai
  return (ai,fai)
{-# INLINE mdA' #-}
mdA' = \arr f !i -> do
  !ai <- rdA arr i
  let !fai = f ai
  wrA arr i fai
  return (ai,fai)
IL(swapA) = \arr !i !j -> do
  ai <- rdA arr i
  wrA arr i =<< rdA arr j
  wrA arr j ai

#define D(f,r,d)\
  IL(f) :: Integral a=>a->d; f=fromIntegral;\
  IL(r) :: String->d; r=read
#define C(f,r,g,h,d) D(f,r,d);\
  g,h :: RealFrac a=>a->d; IL(g)=floor; IL(h)=ceiling
C(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)
C(toInt,readInt,floorInt,ceilInt,Int)
C(toI8,readI8,floorI8,ceilI8,Int8)
C(toI16,readI16,floorI16,ceilI16,Int16)
C(toI32,readI32,floorI32,ceilI32,Int32)
C(toI64,readI64,floorI64,ceilI64,Int64)
C(toWord,readWord,floorWord,ceilWord,Word)
C(toW8,readW8,floorW8,ceilW8,Word8)
C(toW16,readW16,floorW16,ceilW16,Word16)
C(toW32,readW32,floorW32,ceilW32,Word32)
C(toW64,readW64,floorW64,ceilW64,Word64)
D(toDouble,readDouble,Double)
D(toFloat,readFloat,Float)
#undef D
#undef C

#define N(f,g,h,a,m)\
  IL(f) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e);\
  f=A.newArray;\
  IL(g) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e);\
  g=A.newArray_;\
  IL(h) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> [e] -> m (a i e);\
  h=A.newListArray
#define C(a,m)
N(newIOA,newIOA_,newIOAL,IOArray,IO)
N(newSTA,newSTA_,newSTAL,STArray s,ST s)
#undef C
#define C(a,m) MArray (a) e (m),
N(newIOUA,newIOUA_,newIOUAL,IOUArray,IO)
N(newSTUA,newSTUA_,newSTUAL,STUArray s,ST s)
#undef C
#undef N

#undef IL


main = do
    [n, x] <- map read . words <$> getLine
    l <- map read . words <$> getLine
    print . length . filter (x>=) . reverse . foldl (\a x -> (head a + x):a) [0] $ l

Score : 200 points

Problem Statement

A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}.

How many times will the ball make a bounce where the coordinate is at most X?

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 100

1 \leq X \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
L_1 L_2 ... L_{N-1} L_N

Output

Print the number of times the ball will make a bounce where the coordinate is at most X.

Sample Input 1

3 6
3 4 5

Sample Output 1

2

The ball will make a bounce at the coordinates 0, 3, 7 and 12, among which two are less than or equal to 6.

Sample Input 2

4 9
3 3 3 3

Sample Output 2

4

The ball will make a bounce at the coordinates 0, 3, 6, 9 and 12, among which four are less than or equal to 9.


-- C "Rectangle Cutting"
import Data.Bool
main = do
  [w, h, x, y] <- map read . words <$> getLine
  let (a, b) = solve w h x y
  putStrLn $ show a ++ " " ++ show b

solve w h x y = (a, b)
  where
    a = w*h / 2
    b = bool 0 1 ((w == 2*x) && (h == 2*y))

Score : 300 points

Problem Statement

There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H).
You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the part whose area is not larger than that of the other. Additionally, determine if there are multiple ways to cut the rectangle and achieve that maximum.

Constraints

1 \leq W,H \leq 10^9

0\leq x\leq W

0\leq y\leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

W H x y

Output

Print the maximum possible area of the part whose area is not larger than that of the other, followed by 1 if there are multiple ways to cut the rectangle and achieve that maximum, and 0 otherwise.

The area printed will be judged correct when its absolute or relative error is at most 10^{-9}.

Sample Input 1

2 3 1 2

Sample Output 1

3.000000 0

The line x=1 gives the optimal cut, and no other line does.

Sample Input 2

2 2 1 1

Sample Output 2

2.000000 1


import Data.Array
import Control.Monad
import Data.Maybe
import Data.Either

data Item = Item { _x :: Integer, _y:: Integer, _t:: String } deriving Show

data MinMax = MinMax { _min :: Integer, _max:: Integer } deriving Show
data MinMax2 = MinMax2 { _mmx::MinMax, _mmy::MinMax } deriving Show
data MinMaxs = MinMaxs { _r::MinMax2, _l::MinMax2, _u::MinMax2, _d::MinMax2 } deriving Show

getMinMax2 ::Integer -> Integer -> MinMax2 -> MinMax2
getMinMax2 x y minmax2 =
    MinMax2 (MinMax min_x max_x) (MinMax min_y max_y)
    where
        min_x = min x $ (_min._mmx) minmax2
        max_x = max x $ (_max._mmx) minmax2
        min_y = min y $ (_min._mmy) minmax2
        max_y = max y $ (_max._mmy) minmax2

getMinMax :: Item -> MinMaxs -> MinMaxs

getMinMax (Item { _x = _x, _y = _y, _t = "R" }) minmaxs = MinMaxs (getMinMax2 _x _y (_r minmaxs)) (_l minmaxs) (_u minmaxs) (_d minmaxs)
getMinMax (Item { _x = _x, _y = _y, _t = "L" }) minmaxs = MinMaxs (_r minmaxs) (getMinMax2 _x _y (_l minmaxs)) (_u minmaxs) (_d minmaxs)
getMinMax (Item { _x = _x, _y = _y, _t = "U" }) minmaxs = MinMaxs (_r minmaxs) (_l minmaxs) (getMinMax2 _x _y (_u minmaxs)) (_d minmaxs)
getMinMax (Item { _x = _x, _y = _y, _t = "D" }) minmaxs = MinMaxs (_r minmaxs) (_l minmaxs) (_u minmaxs) (getMinMax2 _x _y (_d minmaxs))

subMinMax :: MinMax -> Integer
subMinMax mm =
    let MinMax _min _max = mm in
    2 * (_max - _min)

mergeMinMax :: MinMax -> MinMax -> MinMax
mergeMinMax mm1 mm2 =
    MinMax (min (_min mm1) (_min mm2)) (max (_max mm1) (_max mm2))

maybeMinMax :: MinMax -> Maybe MinMax
maybeMinMax mm
    | (_min mm) <= (_max mm) = Just mm
    | otherwise = Nothing

ketsugou :: Maybe a -> Maybe a -> Maybe a
ketsugou mm1 mm2 = if (isJust mm1) then mm1 else mm2

getLeft :: Either a b -> Maybe a
getLeft = either Just (const Nothing)

getRight :: Either a b -> Maybe b
getRight = either (const Nothing) Just

-- data Times = Pattern1 ((Integer,Integer,Integer,Integer),(Integer,Integer,Integer,Integer,Integer)) | Pattern2 ((Integer,Integer),(Integer,Integer,Integer))  | Pattern3 Integer deriving Show

calcTime :: Maybe MinMax -> Maybe MinMax -> Maybe MinMax -> (Integer, Maybe ((Integer,Integer),(Integer,Integer),Maybe((Integer,Integer),(Integer,Integer))))

-- i : increment
-- d : decrement
-- c : constant
calcTime (Just mmi) (Just mmd) (Just mmc) =
    (h3_x2, Just((t23_x2, t34_x2),(h2_x2, h4_x2),  Just((t12_x2, t45_x2),(h1_x2, h5_x2))))
    where

        MinMax i_min i_max = mmi
        MinMax c_min c_max = mmc
        MinMax d_min d_max = mmd

        ic_min_x2 = 2 * (c_min - i_min)
        cd_min_x2 = 2 * (d_min - c_min)
        id_min_x2 = d_min - i_min

        cd_max_x2 = 2 * (d_max - c_max)
        ic_max_x2 = 2 * (c_max - i_max)
        id_max_x2 = d_max - i_max

        tmin1_x2 = min ic_min_x2 id_min_x2
        tmin2_x2 = max id_min_x2 cd_min_x2
        tmax1_x2 = min cd_max_x2 id_max_x2
        tmax2_x2 = max id_max_x2 ic_max_x2

        h1_x2 = 2 * ( d_max - i_min )

        h2_x2 = if tmin1_x2 < tmax1_x2
                    then
                        if tmin1_x2 < tmin2_x2
                        then
                            2 * (d_max - c_min)
                        else
                            (2 * d_max) - (i_min + d_min)
                    else
                        if tmax1_x2 < tmax2_x2
                        then
                            2 * (c_max - i_min)
                        else
                            (i_max + d_max) - (2 * i_min)

        h3_x2 = if tmin2_x2 < tmax1_x2
                    then
                        2 * (d_max - d_min)
                    else
                        if tmax2_x2 < tmin1_x2
                        then
                            2 * (i_max - i_min)
                        else
                            if tmin1_x2 < tmin2_x2
                            then
                                if tmax1_x2 < tmax2_x2
                                then
                                    2 * (c_max - c_min)
                                else
                                    (i_max + d_max) - 2 * c_min
                            else
                                if tmax1_x2 < tmax2_x2
                                then
                                    2 * c_max - (i_min + d_min)
                                else
                                    (i_max + d_max) - (i_min + d_min)

        h4_x2 = if tmin2_x2 < tmax2_x2
                    then
                        if tmax1_x2 < tmax2_x2
                        then
                            2 * (c_max - d_min )
                        else
                            (i_max + d_max) - (2 * d_min)
                    else
                        if tmin1_x2 < tmin2_x2
                        then
                            2 * (i_max -  c_min)
                        else
                            (2 * i_max) - (i_min + d_min)

        h5_x2 = 2 * ( i_max - d_min )

        t12_x2 = minimum [ic_min_x2, id_min_x2, cd_max_x2, id_max_x2]
        t23_x2 = min (max tmin1_x2 tmax1_x2) (min tmin2_x2 tmax2_x2)
        t34_x2 = max (max tmin1_x2 tmax1_x2) (min tmin2_x2 tmax2_x2)
        t45_x2 = maximum [id_min_x2, cd_min_x2, id_max_x2, ic_max_x2]

calcTime (Just mmi) (Just mmd) Nothing =
    (h3_x2, Just((t23_x2, t34_x2),(h2_x2, h4_x2),  Just((t12_x2, t45_x2),(h1_x2, h5_x2))))
    where

        MinMax i_min i_max = mmi
        MinMax d_min d_max = mmd

        id_min_x2 = d_min - i_min

        id_max_x2 = d_max - i_max

        h1_x2 = 2 * ( d_max - i_min )

        h2_x2 = if id_min_x2 < id_max_x2
                    then
                        (2 * d_max) - (i_min + d_min)
                    else
                        (i_max + d_max) - (2 * i_min)

        h3_x2 = if id_min_x2 < id_max_x2
                    then
                        2 * (d_max - d_min)
                    else
                        if id_max_x2 < id_min_x2
                        then
                            2 * (i_max - i_min)
                        else
                            2 * ((i_max + d_max) - (i_min + d_min))

        h4_x2 = if id_min_x2 < id_max_x2
                    then
                        (i_max + d_max) - (2 * d_min)
                    else
                        (2 * i_max) - (i_min + d_min)

        h5_x2 = 2 * ( i_max - d_min )

        t12_x2 = min id_min_x2 id_max_x2
        t23_x2 = min id_min_x2 id_max_x2

        t34_x2 = max id_min_x2 id_max_x2
        t45_x2 = max id_min_x2 id_max_x2

calcTime (Just mmi) Nothing (Just mmc) =
    (h3_x2, Just((t23_x2, t34_x2),(h2_x2, h4_x2),Nothing))
    where

        MinMax i_min i_max = mmi
        MinMax c_min c_max = mmc

        ic_min_x2 = 2 * (c_min - i_min)
        ic_max_x2 = 2 * (c_max - i_max)

        h2_x2 = 2 * (c_max - i_min)

        h3_x2 = if ic_min_x2 < ic_max_x2
                then
                    2 * (c_max - c_min)
                else
                    2 * (i_max - i_min)

        h4_x2 =  2 * (i_max -  c_min)

        t23_x2 = min ic_min_x2 ic_max_x2

        t34_x2 = max ic_min_x2 ic_max_x2

calcTime Nothing (Just mmd) (Just mmc) =
    (h3_x2, Just((t23_x2, t34_x2),(h2_x2, h4_x2),Nothing))
    where

        MinMax c_min c_max = mmc
        MinMax d_min d_max = mmd

        cd_min_x2 = 2 * (d_min - c_min)
        cd_max_x2 = 2 * (d_max - c_max)

        h2_x2 = 2 * (d_max - c_min)

        h3_x2 = if cd_min_x2 < cd_max_x2
                then
                    2 * (d_max - d_min)
                else
                    2 * (c_max - c_min)

        h4_x2 =  2 * (c_max -  d_min)

        t23_x2 = min cd_max_x2 cd_min_x2

        t34_x2 = max cd_max_x2 cd_min_x2

calcTime Nothing (Just mmd) Nothing =
    (result,Nothing)
    where

        MinMax d_min d_max = mmd

        result = 2 * (d_max - d_min)

calcTime Nothing Nothing (Just mmc) =
    (result,Nothing)
    where

        MinMax c_min c_max = mmc

        result = 2 * (c_max - c_min)

calcTime (Just mmi) Nothing Nothing =
    (result,Nothing)
    where

        MinMax i_min i_max = mmi

        result = 2 * (i_max - i_min)

--calcTime :: Maybe MinMax -> Maybe MinMax -> Maybe MinMax -> (Integer, Maybe ((Integer,Integer),(Integer,Integer),Maybe((Integer,Integer),(Integer,Integer))))

getFunc :: (Integer, Maybe ((Integer,Integer),(Integer,Integer),Maybe((Integer,Integer),(Integer,Integer)))) -> Integer -> Integer
getFunc neta =
    let (h3,times) = neta in if isNothing times
    then
        const h3
    else
        let Just ((t23,t34),(h2,h4),m) = times in
        let func1 = \t ->
                if t < t23
                then
                    h2 - t
                else
                    if t34 < t
                    then
                        h4 + t
                    else
                        h3 in
        if isNothing m
        then
            func1
        else
            let Just ((t12,t45),(h1,h5)) = m in
                \t ->
                    if t < t12
                    then
                        h1 - 2 * t
                    else
                        if t45 < t
                        then
                            h5 + 2 * t
                        else
                            func1 t

getTimes :: (Integer, Maybe ((Integer,Integer),(Integer,Integer),Maybe((Integer,Integer),(Integer,Integer)))) -> [Integer]
getTimes neta =
    let (h3,times) = neta in if isNothing times
    then
        []
    else
        let Just ((t23,t34),(h2,h4),m) = times in
        if isNothing m
        then
            [t23,t34]
        else
            let Just ((t12,t45),(h1,h5)) = m in
                [t12,t23,t34,t45]

main :: IO()
main = do

    n <- (read :: String -> Int)  <$> getLine

    arr <- map words <$> replicateM n getLine

    let arr2 = do
        [x, y, d] <- arr
        let x' = (read :: String -> Integer) x
        let y' = (read :: String -> Integer) y
        return $ Item x' y' d

    let initMinMax  = MinMax 200000000 (-200000000)

    let initMinMax2 = MinMax2 initMinMax initMinMax

    let seed = MinMaxs initMinMax2 initMinMax2 initMinMax2 initMinMax2

    let MinMaxs { _r = _r, _l = _l, _u = _u, _d = _d } = foldr getMinMax seed arr2

    let r_mmx = maybeMinMax $ _mmx _r

    let l_mmx = maybeMinMax $ _mmx _l

    let rl_mmy = maybeMinMax $ mergeMinMax (_mmy _r) (_mmy _l)

    let u_mmy = maybeMinMax $ _mmy _u

    let d_mmy = maybeMinMax $ _mmy _d

    let ud_mmx = maybeMinMax $ mergeMinMax (_mmx _u) (_mmx _d)

    let x_neta = calcTime r_mmx l_mmx ud_mmx

    let y_neta = calcTime u_mmy d_mmy rl_mmy

    let xFunc = getFunc x_neta
    let yFunc = getFunc y_neta
    let xTimes = getTimes x_neta
    let yTimes = getTimes y_neta

    let xResults = map (\t -> (t,(xFunc t)*(yFunc t))) xTimes
    let yResults = map (\t -> (t,(xFunc t)*(yFunc t))) yTimes

    let results = concat [xResults, yResults]

    let result_zero =   xFunc(0) * yFunc(0)

    print $ (/4) $ (realToFrac :: Integer -> Float) $ minimum $ (result_zero :) $ map snd $ filter ((0<=).fst) $  results

Score : 600 points

Problem Statement

There are N points in a two-dimensional plane. The initial coordinates of the i-th point are (x_i, y_i). Now, each point starts moving at a speed of 1 per second, in a direction parallel to the x- or y- axis. You are given a character d_i that represents the specific direction in which the i-th point moves, as follows:

If d_i = R, the i-th point moves in the positive x direction;

If d_i = L, the i-th point moves in the negative x direction;

If d_i = U, the i-th point moves in the positive y direction;

If d_i = D, the i-th point moves in the negative y direction.

You can stop all the points at some moment of your choice after they start moving (including the moment they start moving).
Then, let x_{max} and x_{min} be the maximum and minimum among the x-coordinates of the N points, respectively. Similarly, let y_{max} and y_{min} be the maximum and minimum among the y-coordinates of the N points, respectively.

Find the minimum possible value of (x_{max} - x_{min}) \times (y_{max} - y_{min}) and print it.

Constraints

1 \leq N \leq 10^5

-10^8 \leq x_i,\ y_i \leq 10^8

x_i and y_i are integers.

d_i is R, L, U, or D.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1 d_1
x_2 y_2 d_2
.
.
.
x_N y_N d_N

Output

Print the minimum possible value of (x_{max} - x_{min}) \times (y_{max} - y_{min}).

The output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-9}.

Sample Input 1

2
0 3 D
3 0 L

Sample Output 1

0

After three seconds, the two points will meet at the origin. The value in question will be 0 at that moment.

Sample Input 2

5
-7 -10 U
7 -6 U
-8 7 D
-3 3 D
0 -6 R

Sample Output 2

97.5

The answer may not be an integer.

Sample Input 3

20
6 -10 R
-4 -9 U
9 6 D
-3 -2 R
0 7 D
4 5 D
10 -10 U
-1 -8 U
10 -6 D
8 -5 U
6 4 D
0 3 D
7 9 R
9 -4 R
3 10 D
1 9 U
1 -6 U
9 -8 R
6 7 D
7 -3 D

Sample Output 3

273


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

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

main = do
    n <- getInt
    xys <- replicateM n $ do
        [x,y] <- getIntList
        return (x,y)
    print . (n -) . (\xs -> if null xs then 0 else maximum xs) . map length . group . sort $ zipWith (\(x1,y1) (x2,y2) -> (x1-x2, y1-y2)) (tail xys) xys

Score : 300 points

Problem Statement

There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i).

We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation:

Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates of this ball. If we collected a ball at coordinates (a - p, b - q) in the previous operation, the cost of this operation is 0. Otherwise, including when this is the first time to do this operation, the cost of this operation is 1.

Find the minimum total cost required to collect all the balls when we optimally choose p and q.

Constraints

1 \leq N \leq 50

|x_i|, |y_i| \leq 10^9

If i \neq j, x_i \neq x_j or y_i \neq y_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the minimum total cost required to collect all the balls.

Sample Input 1

2
1 1
2 2

Sample Output 1

1

If we choose p = 1, q = 1, we can collect all the balls at a cost of 1 by collecting them in the order (1, 1), (2, 2).

Sample Input 2

3
1 4
4 6
7 8

Sample Output 2

1

If we choose p = -3, q = -2, we can collect all the balls at a cost of 1 by collecting them in the order (7, 8), (4, 6), (1, 4).

Sample Input 3

4
1 1
1 2
2 1
2 2

Sample Output 3

2


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

readInt' = fst.fromJust.C.readInt
readLnInt = map readInt'.C.words<$>C.getLine
readCsInt n = concat<$>replicateM n readLnInt

x ? (a,b) = if x then a else b

main = do
 [n] <- readLnInt
 inputs <- readCsInt n
 print $ solve inputs

solve s = 1 + sum (nubx s)

nubx s = tail $ reverse $ sort $ map length $ group $ sort (distance s)
distance (a:b:[]) = []
distance (a:b:c:d:e)= [(c-a,d-b)] ++ distance (c:d:e)


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns          #-}
{-# LANGUAGE CPP                   #-}
{-# LANGUAGE LambdaCase            #-}
{-# LANGUAGE MagicHash             #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE MultiWayIf            #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE TupleSections         #-}
{-# LANGUAGE TypeFamilies          #-}
{-# LANGUAGE ViewPatterns          #-}

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.ST
import           Control.Monad.State.Strict
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.Unsafe      as B
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
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.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 qualified System.IO                   as IO
import           Unsafe.Coerce

main :: IO ()
main = do
    !n <- readLn :: IO Int
    xys <- U.unfoldrN n parseInt2 <$> C.getContents
    print $ solve n xys

solve :: Int -> U.Vector (Int, Int) -> Int
solve n xys = minimum [ n - score (xys U.! i) (xys U.! j)| i<-[0..n-1],j<-[0..n-1], i /= j]
  where
    !set = S.fromList $ U.toList xys
    score (x0, y0) (x1, y1) = sum $ do
        i <- [0..n-1]
        let (z0, w0) = xys U.! i
        (z1,w1) <- map (xys U.!) [i+1..n-1]
        guard $ ((z1-z0)==p && (w1-w0)==q) || ((z0-z1)==p && (w0-w1)==q)
        return (1::Int)
      where
        !p = x1 - x0
        !q = y1 - y0

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

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

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

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

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


-- https://github.com/minoki/my-atcoder-solutions
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
import Data.Char (isSpace)
import Data.List (unfoldr, sort)
import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.Ord
import Data.Coerce

sortDown :: forall a. Ord a => [a] -> [a]
sortDown = coerce (sort :: [Down a] -> [Down a])

exchangeOne :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int
exchangeOne !gA !sA !bA !gB !sB !bB !n =
  let dg = gB - gA
      ds = sB - sA
      db = bB - sB
      l = sortDown $ filter ((> 0) . fst) [(dg, gA), (ds, sA), (db, bA)]
  in case l of
       [] -> n
       [(dx,xA)] -> let (q,r) = n `quotRem` xA
                    in n + q * dx
       [(dx,xA),(dy,yA)] -> let (qx,rx) = n `quotRem` xA
                                (qy,ry) = rx `quotRem` yA
                            in n + qx * dx + qy * dy
       [(dx,xA),(dy,yA),(dz,zA)] -> let (qx,rx) = n `quotRem` xA
                                        (qy,ry) = rx `quotRem` yA
                                        (qz,rz) = rz `quotRem` zA
                                    in n + qx * dx + qy * dy + qz * dz

main = do
  n <- readLn
  [gA,sA,bA] <- unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  [gB,sB,bB] <- unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  print $ exchangeOne gB sB bB gA sA bA $ exchangeOne gA sA bA gB sB bB n

Score : 600 points

Problem Statement

The squirrel Chokudai has N acorns.
One day, he decides to do some trades in multiple precious metal exchanges to make more acorns.

His plan is as follows:

Get out of the nest with N acorns in his hands.

Go to Exchange A and do some trades.

Go to Exchange B and do some trades.

Go to Exchange A and do some trades.

Go back to the nest.

In Exchange X (X = A, B), he can perform the following operations any integer number of times (possibly zero) in any order:

Lose g_{X} acorns and gain 1 gram of gold.

Gain g_{X} acorns and lose 1 gram of gold.

Lose s_{X} acorns and gain 1 gram of silver.

Gain s_{X} acorns and lose 1 gram of silver.

Lose b_{X} acorns and gain 1 gram of bronze.

Gain b_{X} acorns and lose 1 gram of bronze.

Naturally, he cannot perform an operation that would leave him with a negative amount of acorns, gold, silver, or bronze.

What is the maximum number of acorns that he can bring to the nest?
Note that gold, silver, or bronze brought to the nest would be worthless because he is just a squirrel.

Constraints

1 \leq N \leq 5000

1 \leq g_{X} \leq 5000

1 \leq s_{X} \leq 5000

1 \leq b_{X} \leq 5000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
g_A s_A b_A
g_B s_B b_B

Output

Print the maximum number of acorns that Chokudai can bring to the nest.

Sample Input 1

23
1 1 1
2 1 1

Sample Output 1

46

He can bring 46 acorns to the nest, as follows:

In Exchange A, trade 23 acorns for 23 grams of gold. {acorns, gold, silver, bronze}={ 0,23,0,0 }

In Exchange B, trade 23 grams of gold for 46 acorns. {acorns, gold, silver, bronze}={ 46,0,0,0 }

In Exchange A, trade nothing. {acorns, gold, silver, bronze}={ 46,0,0,0 }

He cannot have 47 or more acorns, so the answer is 46.


import Control.Arrow
import Control.Monad
import Data.List
import qualified Data.ByteString.Char8 as B
import Data.Ord

main :: IO ()
main = readLine >>= print . solve

solve :: [Int] -> Int
solve = sum . tail . sortOn Down

readLine :: IO [Int]
readLine = unfoldr (fmap (second (maybe B.empty snd . B.uncons)) . B.readInt) <$> B.getLine

readContents :: Int -> IO [[Int]]
readContents = flip replicateM readLine

Score : 100 points

Problem Statement

There are three airports A, B and C, and flights between each pair of airports in both directions.

A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours.

Consider a route where we start at one of the airports, fly to another airport and then fly to the other airport.

What is the minimum possible sum of the flight times?

Constraints

1 \leq P,Q,R \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

P Q R

Output

Print the minimum possible sum of the flight times.

Sample Input 1

1 3 4

Sample Output 1

4

The sum of the flight times in the route A \rightarrow B \rightarrow C: 1 + 3 = 4 hours

The sum of the flight times in the route A \rightarrow C \rightarrow C: 4 + 3 = 7 hours

The sum of the flight times in the route B \rightarrow A \rightarrow C: 1 + 4 = 5 hours

The sum of the flight times in the route B \rightarrow C \rightarrow A: 3 + 4 = 7 hours

The sum of the flight times in the route C \rightarrow A \rightarrow B: 4 + 1 = 5 hours

The sum of the flight times in the route C \rightarrow B \rightarrow A: 3 + 1 = 4 hours

The minimum of these is 4 hours.

Sample Input 2

3 2 3

Sample Output 2

5


-- https://github.com/minoki/my-atcoder-solutions
import Data.Char
import qualified Data.Vector.Unboxed as U
import qualified Data.ByteString.Char8 as BS

main = do
  n <- readLn
  ws <- U.unfoldrN n (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  let wss = U.scanl' (+) 0 ws
      total = U.last wss
  print $ U.minimum $ U.map (\s -> abs (total - 2 * s)) wss

Score : 200 points

Problem Statement

We have N weights indexed 1 to N. The mass of the weight indexed i is W_i.

We will divide these weights into two groups: the weights with indices not greater than T, and those with indices greater than T, for some integer 1 \leq T < N. Let S_1 be the sum of the masses of the weights in the former group, and S_2 be the sum of the masses of the weights in the latter group.

Consider all possible such divisions and find the minimum possible absolute difference of S_1 and S_2.

Constraints

2 \leq N \leq 100

1 \leq W_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
W_1 W_2 ... W_{N-1} W_N

Output

Print the minimum possible absolute difference of S_1 and S_2.

Sample Input 1

3
1 2 3

Sample Output 1

0

If T = 2, S_1 = 1 + 2 = 3 and S_2 = 3, with the absolute difference of 0.

Sample Input 2

4
1 3 1 1

Sample Output 2

2

If T = 2, S_1 = 1 + 3 = 4 and S_2 = 1 + 1 = 2, with the absolute difference of 2. We cannot have a smaller absolute difference.

Sample Input 3

8
27 23 76 2 3 5 62 52

Sample Output 3

2


-- vim: set fdm=marker : -- {{{
{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Control.Monad.Fix (fix)
import Data.Maybe
import Data.Array.Unboxed (Array, Ix, array, (!), range)
import qualified Data.ByteString.Char8 as BS

tuplify2 (x:y:_) = (x,y)
tuplify2 _ = undefined

--Input functions with ByteString
readInt :: Num a => BS.ByteString -> a
readInt = fromIntegral . fst . fromJust . BS.readInteger
readIntTuple :: Num a => BS.ByteString -> (a, a)
readIntTuple = tuplify2 . map readInt . BS.words
readIntList :: Num a => BS.ByteString -> [a]
readIntList = map readInt . BS.words

getInt :: Num a => IO a
getInt = readInt <$> BS.getLine
getIntList :: Num a => IO [a]
getIntList = readIntList <$> BS.getLine
getIntN n = map readInt <$> replicateM (fromIntegral n) BS.getLine
getIntNList n = map readIntList <$> replicateM (fromIntegral n) BS.getLine
getIntMatrix = map readIntList . BS.lines <$> BS.getContents
getIntTuple = readIntTuple <$> BS.getLine
getIntNTuples n = map readIntTuple <$> replicateM (fromIntegral n) BS.getLine
getIntTuples = map readIntTuple . BS.lines <$> BS.getContents
-- }}}

type Index = Int
type Value = Integer
type Data  = Array Int Int

main = do
    [n,m] <- getIntList :: IO [Int]
    as <- getIntN m :: IO [Int]
    print $ slvMemo n (genArray m as) 0 `mod` 1000000007

genArray :: Int -> [Int] -> Data
genArray n xs = array (0, n-1) [x | x <- zip [0..n] xs]

memo :: (Index -> a) -> (Index -> a)
memo !f = (map f [0..] !!)

slvMemo :: Int -> Data -> Index -> Value
slvMemo !n !d = fix (memo . slv n d)

slv :: Int -> Data -> (Index -> Value) -> Index -> Value
slv !n !d !f !i
  | i `elem` d = 0
  | i  > n = 0
  | i == n = 1
  | i == (n-1) = 1
  | otherwise = f (i+1) + f (i+2)

Score : 300 points

Problem Statement

There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step.
He can climb up one or two steps at a time.

However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps.

How many are there to climb up to the top step, that is, the N-th step, without setting foot on the broken steps?
Find the count modulo 1\ 000\ 000\ 007.

Constraints

1 \leq N \leq 10^5

0 \leq M \leq N-1

1 \leq a_1 < a_2 < ... < a_M \leq N-1

Input

Input is given from Standard Input in the following format:

N M
a_1
a_2
.
.
.
a_M

Output

Print the number of ways to climb up the stairs under the condition, modulo 1\ 000\ 000\ 007.

Sample Input 1

6 1
3

Sample Output 1

4

There are four ways to climb up the stairs, as follows:

0 \to 1 \to 2 \to 4 \to 5 \to 6

0 \to 1 \to 2 \to 4 \to 6

0 \to 2 \to 4 \to 5 \to 6

0 \to 2 \to 4 \to 6

Sample Input 2

10 2
4
5

Sample Output 2

0

There may be no way to climb up the stairs without setting foot on the broken steps.

Sample Input 3

100 5
1
23
45
67
89

Sample Output 3

608200469

Be sure to print the count modulo 1\ 000\ 000\ 007.


-- https://github.com/minoki/my-atcoder-solutions
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
import Data.Char (isSpace)
import Data.Bits (xor)
import Control.Monad (forM_,when)
import Control.Monad.ST
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as GM
import qualified Data.ByteString.Char8 as BS
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray
import System.Environment (getArgs)
import Debug.Trace
---
import Data.Coerce
import qualified Data.Vector.Generic
import qualified Data.Vector.Generic.Mutable
import qualified Data.Array.Base
import qualified Unsafe.Coerce

type NN = N
type Mat = UArray (Int,Int) NN
type Vec = U.Vector NN
{-
type NN = Rational
type Mat = Array (Int,Int) Rational
type Vec = V.Vector NN
-}

main = do
  n :: Int <- readLn -- 1 <= n <= 18
  as <- U.unfoldrN (2^n) (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  let s = U.sum as :: Int
      !as' = G.map fromIntegral (V.convert as) :: Vec
      !s' = recip (fromIntegral s) :: NN
      coeffMat :: Mat
      coeffMat = array ((1,1),(2^n-1,2^n)) $
        [ ((i,j),v)
        | i <- [1..2^n-1]
        , j <- [1..2^n-1]
        , let v | i == j = 1 - (as' G.! 0) * s'
                | otherwise = - (as' G.! (i `xor` j)) * s'
        ]
        ++ [((i,2^n),1) | i <- [1..2^n-1]]
      coeffMatV :: V.Vector Vec
      coeffMatV = V.generate (2^n-1) $ \i ->
        G.generate (2^n) $ \j ->
        if j == 2^n-1
        then 1
        else if i == j
             then 1 - (as' G.! 0) * s'
             else - (as' G.! ((i+1) `xor` (j+1))) * s'
  let result = solve coeffMat
  let resultV = solveV coeffMatV
  print 0
  args <- getArgs
  case args of
    "array":_ -> do
      forM_ [1..2^n-1] $ \j -> do
        print $ result!(j,2^n) / result!(j,j)
    _ -> do -- print resultV
            V.imapM_ (\j row -> print $ row G.! (2^n-1) / row G.! j) resultV

-- 行基本変形を行う
solve :: (Eq k, Fractional k, IArray arr k) => arr (Int,Int) k -> arr (Int,Int) k
solve m | i0 == j0 = loop i0 m
        | otherwise = error "not supported"
  where
    b@((i0,j0),(iN,_)) = bounds m
    loop !i !m
      | i > iN = m
      | otherwise = case [(k,w) | k <- [i..iN], let w = m!(k,i), w /= 0] of
          (!k,!w):_ -> let !r = recip w -- r == recip (m!(k,i))
                       in loop (i+1) $ array b
                          [ ((i'',j),v)
                          | (i',j) <- indices m
                          , let !v | i' == k = m!(i',j)
                                   | otherwise = m!(i',j) - m!(k,j)*m!(i',i)*r
                                !i''  | i' == k = i
                                      | i' == i = k
                                      | otherwise = i'
                          ]
          [] -> error "singular matrix"

solveV :: forall vector k. (Eq k, Fractional k, G.Vector vector k, Show k, Show (vector k)) => V.Vector (vector k) -> V.Vector (vector k)
solveV m = runST $ do
  m' <- V.mapM G.thaw m
  m'' <- V.thaw m'
  elim 0 m''
  subst (n-2) m''
  m''' <- V.unsafeFreeze m''
  V.mapM G.unsafeFreeze m'''
  -- V.createT is not available on AtCoder
  where
    !n = V.length m
    elim :: Int -> VM.MVector s (G.Mutable vector s k) -> ST s ()
    elim !i !m
      | i >= n = return ()
      | otherwise = do
          let findK k | k >= n = error "singular matrix"
                      | otherwise = do
                          row <- VM.read m k
                          w <- GM.read row i
                          if w == 0
                            then findK (k + 1)
                            else return (k,row,w)
          (k,rowK,w) <- findK i -- i <= k
          let !r = recip w -- r == recip (m!(k,i))
          forM_ [i..GM.length rowK - 1] $ \j -> do
            GM.modify rowK (\x -> x * r) j
          -- GM.set (GM.take i rowK) 0
          forM_ [i..n-1] $ \i' -> do
            row' <- VM.read m i'
            when (i' /= k) $ do
              y <- GM.read row' i -- m!(i',i)
              let !yy = y
              forM_ [i..GM.length row' - 1] $ \j -> do
                z <- GM.read rowK j
                GM.modify row' (\x -> x - z * yy) j
          VM.swap m i k
          elim (i+1) m
    subst :: Int -> VM.MVector s (G.Mutable vector s k) -> ST s ()
    subst !i !m
      | i < 0 = return ()
      | otherwise = do
          row <- VM.read m i
          let loop !j !x | j >= n = GM.write row n x
                         | otherwise = do
                             c <- GM.read row j
                             y <- VM.read m j >>= (`GM.read` n)
                             loop (j+1) (x - c * y)
          rhs <- GM.read row n
          loop (i + 1) rhs
          -- GM.set (GM.drop (i+1) $ GM.take n row) 0
          subst (i - 1) m
{-
    dump :: VM.MVector s (G.Mutable vector s k) -> ST s ()
    dump m = do m' <- V.freeze m
                fr <- V.mapM G.freeze m'
                traceShow fr $ return ()
-}

---

exEuclid :: (Eq a, Integral a) => a -> a -> (a, a, a)
exEuclid !f !g = loop 1 0 0 1 f g
  where loop !u0 !u1 !v0 !v1 !f 0 = (f, u0, v0)
        loop !u0 !u1 !v0 !v1 !f g =
          case divMod f g of
            (q,r) -> loop u1 (u0 - q * u1) v1 (v0 - q * v1) g r

modulo = 998244353 :: Int
addMod, subMod, mulMod, divM :: Int -> Int -> Int
addMod !x !y = (x + y) `rem` modulo
subMod !x !y = (x - y) `mod` modulo
mulMod !x !y = (x * y) `rem` modulo
recipM :: Int -> Int
recipM !x = case exEuclid x modulo of
             (1,a,_) -> a `mod` modulo
             (-1,a,_) -> (-a) `mod` modulo
divM !x !y = x `mulMod` recipM y

newtype N = N { unwrapN :: Int } deriving (Eq)
instance Show N where
  show (N x) = show x
instance Num N where
  N x + N y = N ((x + y) `rem` modulo)
  N x - N y = N ((x - y) `mod` modulo)
  N x * N y = N ((x * y) `rem` modulo)
  fromInteger n = N (fromInteger (n `mod` fromIntegral modulo))
  abs = undefined; signum = undefined

instance Fractional N where
  N x / N y = N (divM x y)
  recip (N x) = N (recipM x)
  fromRational = undefined

---

newtype instance UM.MVector s N = MV_N (UM.MVector s Int)
newtype instance U.Vector N = V_N (U.Vector Int)

instance Data.Vector.Generic.Mutable.MVector UM.MVector N where -- needs MultiParamTypeClasses here
  basicLength (MV_N mv) = Data.Vector.Generic.Mutable.basicLength mv
  basicUnsafeSlice i l (MV_N mv) = MV_N (Data.Vector.Generic.Mutable.basicUnsafeSlice i l mv)
  basicOverlaps (MV_N mv) (MV_N mv') = Data.Vector.Generic.Mutable.basicOverlaps mv mv'
  basicUnsafeNew l = MV_N <$> Data.Vector.Generic.Mutable.basicUnsafeNew l
  basicInitialize (MV_N mv) = Data.Vector.Generic.Mutable.basicInitialize mv
  basicUnsafeReplicate i x = MV_N <$> Data.Vector.Generic.Mutable.basicUnsafeReplicate i (coerce x)
  basicUnsafeRead (MV_N mv) i = coerce <$> Data.Vector.Generic.Mutable.basicUnsafeRead mv i
  basicUnsafeWrite (MV_N mv) i x = Data.Vector.Generic.Mutable.basicUnsafeWrite mv i (coerce x)
  basicClear (MV_N mv) = Data.Vector.Generic.Mutable.basicClear mv
  basicSet (MV_N mv) x = Data.Vector.Generic.Mutable.basicSet mv (coerce x)
  basicUnsafeCopy (MV_N mv) (MV_N mv') = Data.Vector.Generic.Mutable.basicUnsafeCopy mv mv'
  basicUnsafeMove (MV_N mv) (MV_N mv') = Data.Vector.Generic.Mutable.basicUnsafeMove mv mv'
  basicUnsafeGrow (MV_N mv) n = MV_N <$> Data.Vector.Generic.Mutable.basicUnsafeGrow mv n

instance Data.Vector.Generic.Vector U.Vector N where -- needs MultiParamTypeClasses here
  basicUnsafeFreeze (MV_N mv) = V_N <$> Data.Vector.Generic.basicUnsafeFreeze mv
  basicUnsafeThaw (V_N v) = MV_N <$> Data.Vector.Generic.basicUnsafeThaw v
  basicLength (V_N v) = Data.Vector.Generic.basicLength v
  basicUnsafeSlice i l (V_N v) = V_N (Data.Vector.Generic.basicUnsafeSlice i l v)
  basicUnsafeIndexM (V_N v) i = coerce <$> Data.Vector.Generic.basicUnsafeIndexM v i
  basicUnsafeCopy (MV_N mv) (V_N v) = Data.Vector.Generic.basicUnsafeCopy mv v
  elemseq (V_N v) x y = Data.Vector.Generic.elemseq v (coerce x) y

instance U.Unbox N

unsafeCoerce_UArray_N_Int :: UArray i N -> UArray i Int
unsafeCoerce_UArray_N_Int = Unsafe.Coerce.unsafeCoerce
unsafeCoerce_UArray_Int_N :: UArray i Int -> UArray i N
unsafeCoerce_UArray_Int_N = Unsafe.Coerce.unsafeCoerce

instance Data.Array.Base.IArray UArray N where
  bounds arr = Data.Array.Base.bounds (unsafeCoerce_UArray_N_Int arr)
  numElements arr = Data.Array.Base.numElements (unsafeCoerce_UArray_N_Int arr)
  unsafeArray lu ies = unsafeCoerce_UArray_Int_N $ Data.Array.Base.unsafeArray lu (coerce ies)
  unsafeAt arr i = coerce (Data.Array.Base.unsafeAt (unsafeCoerce_UArray_N_Int arr) i)
  unsafeReplace arr ies = unsafeCoerce_UArray_Int_N (Data.Array.Base.unsafeReplace (unsafeCoerce_UArray_N_Int arr) (coerce ies))
  unsafeAccum f arr ies = unsafeCoerce_UArray_Int_N (Data.Array.Base.unsafeAccum (coerce f) (unsafeCoerce_UArray_N_Int arr) ies)
  unsafeAccumArray f e lu ies = unsafeCoerce_UArray_Int_N (Data.Array.Base.unsafeAccumArray (coerce f) (coerce e) lu ies)

Score : 1600 points

Problem Statement

Snuke found a random number generator.
It generates an integer between 0 and 2^N-1 (inclusive).
An integer sequence A_0, A_1, \cdots, A_{2^N-1} represents the probability that each of these integers is generated. The integer i (0 \leq i \leq 2^N-1) is generated with probability A_i / S, where S = \sum_{i=0}^{2^N-1} A_i. The process of generating an integer is done independently each time the generator is executed.

Snuke has an integer X, which is now 0.
He can perform the following operation any number of times:

Generate an integer v with the generator and replace X with X \oplus v, where \oplus denotes the bitwise XOR.

For each integer i (0 \leq i \leq 2^N-1), find the expected number of operations until X becomes i, and print it modulo 998244353.
More formally, represent the expected number of operations as an irreducible fraction P/Q. Then, there exists a unique integer R such that R \times Q \equiv P \mod 998244353,\ 0 \leq R < 998244353, so print this R.

We can prove that, for every i, the expected number of operations until X becomes i is a finite rational number, and its integer representation modulo 998244353 can be defined.

Constraints

1 \leq N \leq 18

1 \leq A_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_0 A_1 \cdots A_{2^N-1}

Output

Print 2^N lines.
The (i+1)-th line (0 \leq i \leq 2^N-1) should contain the expected number of operations until X becomes i, modulo 998244353.

Sample Input 1

2
1 1 1 1

Sample Output 1

0
4
4
4

X=0 after zero operations, so the expected number of operations until X becomes 0 is 0.

Also, from any state, the value of X after one operation is 0, 1, 2 or 3 with equal probability.
Thus, the expected numbers of operations until X becomes 1, 2 and 3 are all 4.

Sample Input 2

2
1 2 1 2

Sample Output 2

0
499122180
4
499122180

The expected numbers of operations until X becomes 0, 1, 2 and 3 are 0, 7/2, 4 and 7/2, respectively.

Sample Input 3

4
337 780 799 10 796 875 331 223 941 67 148 483 390 565 116 355

Sample Output 3

0
468683018
635850749
96019779
657074071
24757563
745107950
665159588
551278361
143136064
557841197
185790407
988018173
247117461
129098626
789682908


main = readLn >>= print . (180 *) . flip (-) 2

Score : 100 points

Problem Statement

Given an integer N not less than 3, find the sum of the interior angles of a regular polygon with N sides.

Print the answer in degrees, but do not print units.

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print an integer representing the sum of the interior angles of a regular polygon with N sides.

Sample Input 1

3

Sample Output 1

180

The sum of the interior angles of a regular triangle is 180 degrees.

Sample Input 2

100

Sample Output 2

17640


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

solve :: Int -> Int
solve n = 180 * (n - 2)


main :: IO ()
main = do
  n <- readLn
  print $ 180 * (n - 2)


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns          #-}
{-# LANGUAGE CPP                   #-}
{-# LANGUAGE LambdaCase            #-}
{-# LANGUAGE MagicHash             #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE MultiWayIf            #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE TupleSections         #-}
{-# LANGUAGE TypeFamilies          #-}
{-# LANGUAGE ViewPatterns          #-}

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Data.Bool
import qualified Data.ByteString             as B
import qualified Data.ByteString.Char8       as C
import qualified Data.ByteString.Unsafe      as B
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
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.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 <- readLn :: IO Int
    qs <- U.unfoldrN n parseInt3 <$> C.getContents
    putStr.unlines.map show.U.toList $ solve n qs

solve :: Int -> U.Vector (Int, Int, Int) -> U.Vector Int
solve _ = U.map solve'

solve' :: (Int, Int, Int) -> Int
solve' (x, d, n)
    | n >= modulus = 0
    | xd == 0 = 0
    | xd == 1 = fact n
    | otherwise = (d ^% n) *% (fact (xd + n - 1) /% fact (xd - 1))
  where
    !xd = x /% d

-------------------------------------------------------------------------------
#define MOD 1000003

modulus :: Int
modulus = MOD

infixr 8 ^%
infixl 7 *%, /%
infixl 6 +%, -%

type IntMod = Int

intMod :: Int -> IntMod
intMod x = mod x MOD

intModValidate :: Int -> Bool
intModValidate x = 0 <= x && x < MOD

(+%) :: IntMod -> IntMod -> IntMod
(I# x#) +% (I# y#) = case x# +# y# of
    r# -> I# (r# -# ((r# >=# MOD#) *# MOD#))
{-# INLINE (+%) #-}

(-%) :: IntMod -> IntMod -> IntMod
(I# x#) -% (I# y#) = case x# -# y# of
    r# -> I# (r# +# ((r# <# 0#) *# MOD#))
{-# INLINE (-%) #-}

(*%) :: IntMod -> IntMod -> IntMod
(I# x#) *% (I# y#) = I# ((x# *# y#) `remInt#` MOD#)
{-# INLINE (*%) #-}

(/%) :: IntMod -> IntMod -> IntMod
(I# x#) /% (I# y#) = go# y# MOD# 1# 0#
  where
    go# a# b# u# v#
        | isTrue# (b# ># 0#) = case a# `quotInt#` b# of
            q# -> go# b# (a# -# (q# *# b#)) v# (u# -# (q# *# v#))
        | otherwise = I# ((x# *# (u# +# MOD#)) `remInt#` MOD#)
{-# INLINE (/%) #-}

(^%) :: IntMod -> Int -> IntMod
x ^% n
    | n > 0 = go 1 x n
    | n == 0 = 1
    | otherwise = go 1 (1 /% x) (-n)
  where
    go !acc !y !m
        | m .&. 1 == 0 = go acc (y *% y) (unsafeShiftR m 1)
        | m == 1 = acc *% y
        | otherwise = go (acc *% y) (y *% y) (unsafeShiftR (m - 1) 1)

fact :: Int -> IntMod
fact = U.unsafeIndex factCache
{-# INLINE fact #-}

recipFact :: Int -> IntMod
recipFact = U.unsafeIndex recipFactCache
{-# INLINE recipFact #-}

comb :: Int -> Int -> IntMod
comb n k = fact n *% recipFact (n - k) *% recipFact k
{-# INLINE comb #-}

factCacheSize :: Int
factCacheSize = 2000200
{-# INLINE factCacheSize #-}

factCache :: U.Vector IntMod
factCache = U.scanl' (*%) 1 $ U.generate factCacheSize (+1)
{-# NOINLINE factCache #-}

recipFactCache :: U.Vector IntMod
recipFactCache = U.scanr' (*%) (1 /% (factCache U.! factCacheSize))
    $ U.generate factCacheSize (+1)
{-# NOINLINE recipFactCache #-}

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

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

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

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

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

Score : 600 points

Problem Statement

Consider the following arithmetic progression with n terms:

x, x + d, x + 2d, \ldots, x + (n-1)d

What is the product of all terms in this sequence?
Compute the answer modulo 1\ 000\ 003.

You are given Q queries of this form.
In the i-th query, compute the answer in case x = x_i, d = d_i, n = n_i.

Constraints

1 \leq Q \leq 10^5

0 \leq x_i, d_i \leq 1\ 000\ 002

1 \leq n_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

Q
x_1 d_1 n_1
:
x_Q d_Q n_Q

Output

Print Q lines.

In the i-th line, print the answer for the i-th query.

Sample Input 1

2
7 2 4
12345 67890 2019

Sample Output 1

9009
916936

For the first query, the answer is 7 \times 9 \times 11 \times 13 = 9009.
Don't forget to compute the answer modulo 1\ 000\ 003.


main = getLine >>= print . (\[a, p] -> (a * 3 + p) `div` 2) . map read . words

Score : 100 points

Problem Statement

We have A apples and P pieces of apple.

We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan.

Find the maximum number of apple pies we can make with what we have now.

Constraints

All values in input are integers.

0 \leq A, P \leq 100

Input

Input is given from Standard Input in the following format:

A P

Output

Print the maximum number of apple pies we can make with what we have.

Sample Input 1

1 3

Sample Output 1

3

We can first make one apple pie by simmering two of the three pieces of apple. Then, we can make two more by simmering the remaining piece and three more pieces obtained by cutting the whole apple.

Sample Input 2

0 1

Sample Output 2

0

We cannot make an apple pie in this case, unfortunately.

Sample Input 3

32 21

Sample Output 3

58


main = do
  [a, p] <- map read . words <$> getLine
  putStrLn . show $ (3 * a + p) `div` 2


import Control.Monad

ok' bit s p = (length $ [] ++ [ ()| si <- s, bit !! (si-1) ]) `mod` 2 == p
ok bit s p m = (length $ [] ++ [ ()| i <- [0..m - 1], ok' bit (s !! i) (p !! i)]) == m
main = do
    [n, m] <- fmap (map read . words) getLine
    s <- replicateM m $ fmap (tail . map read . words) getLine
    p <- fmap(map read . words) getLine
    let bit = sequence $ replicate n [False, True]
    print.length $ [ () | b <- bit, ok b s p m ]

Score : 300 points

Problem Statement

We have N switches with "on" and "off" state, and M bulbs. The switches are numbered 1 to N, and the bulbs are numbered 1 to M.

Bulb i is connected to k_i switches: Switch s_{i1}, s_{i2}, ..., and s_{ik_i}. It is lighted when the number of switches that are "on" among these switches is congruent to p_i modulo 2.

How many combinations of "on" and "off" states of the switches light all the bulbs?

Constraints

1 \leq N, M \leq 10

1 \leq k_i \leq N

1 \leq s_{ij} \leq N

s_{ia} \neq s_{ib} (a \neq b)

p_i is 0 or 1.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
k_1 s_{11} s_{12} ... s_{1k_1}
:
k_M s_{M1} s_{M2} ... s_{Mk_M}
p_1 p_2 ... p_M

Output

Print the number of combinations of "on" and "off" states of the switches that light all the bulbs.

Sample Input 1

2 2
2 1 2
1 2
0 1

Sample Output 1

1

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

There are four possible combinations of states of (Switch 1, Switch 2): (on, on), (on, off), (off, on) and (off, off). Among them, only (on, on) lights all the bulbs, so we should print 1.

Sample Input 2

2 3
2 1 2
1 1
1 2
0 0 1

Sample Output 2

0

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an even number of switches that are "on" among the following: Switch 1.

Bulb 3 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

Switch 1 has to be "off" to light Bulb 2 and Switch 2 has to be "on" to light Bulb 3, but then Bulb 1 will not be lighted. Thus, there are no combinations of states of the switches that light all the bulbs, so we should print 0.

Sample Input 3

5 2
3 1 2 5
2 2 3
1 0

Sample Output 3

8


-- Your code here!
import Control.Monad
import Data.Bits

calc :: [[Int]] -> [Int] -> [Int] -> Int
calc ks ps ns = length . filter (==True) $ map allOk ns
  where
    allOk n = all (\(k,p) -> calc' k p n) (zip ks ps)

calc' :: [Int] -> Int -> Int -> Bool
calc' k p n = jdg
  where
    ct = length . filter (==1) $ map (\e -> (.&.) (shift n (1-e)) 1 ) k
    jdg = if ct`mod`2 == p then True else False

main = do
  [n,m] <- map read . words <$> getLine
  k <- replicateM m $ tail . map read . words <$> getLine :: IO [[Int]]
  p <- map read . words <$> getLine :: IO [Int]
  let ans = calc k p [0..2^n-1]
  print ans


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

getVals :: Read a => IO [a]
getVals = map read . words <$> getLine
getStrs :: IO [String]
getStrs = words <$> getLine
readInts :: IO [Int]
readInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine

type Elem = Either (Int, Int, Int) Int

f :: (S.Set (Int, Int), [Int]) -> Elem ->
    (S.Set (Int, Int), [Int])
f (set, ans) (Left (_, t, x)) = (S.insert (x, t) set, ans)
f (set, ans) (Right d)
    | S.null set = (set, (-1):ans)
    | t-x <= d = f (S.deleteMin set, ans) $ Right d
    | otherwise = (set, x:ans)
    where (x, t) = S.findMin set

solve :: [[Int]] -> [Int] -> [Int]
solve stxs ds = reverse $ snd $ foldl f (S.empty, []) way
    where
        wayTo = [Left (s, t, x) | [s, t, x] <- stxs]
        wayFrom = [Right d | d <- ds]
        way = sortBy cmp $ wayTo ++ wayFrom

cmp :: Elem -> Elem -> Ordering
Left (s1, _, x1) `cmp` Left (s2, _, x2) = compare (s1-x1) (s2-x2)
Left (s, _, x) `cmp` Right d
    | s-x == d = LT
    | otherwise = compare (s-x) d
Right d `cmp` Left stx = flipOrd $ Left stx `cmp` Right d
Right d1 `cmp` Right d2 = compare d1 d2

flipOrd :: Ordering -> Ordering
flipOrd EQ = EQ
flipOrd GT = LT
flipOrd LT = GT

main :: IO ()
main = do
    [n, q] <- map fromIntegral <$> readInts
    stxs <- replicateM n readInts :: IO [[Int]]
    ds <- replicateM q $ head <$> readInts
    mapM_ print $ solve stxs ds

Score : 500 points

Problem Statement

There is an infinitely long street that runs west to east, which we consider as a number line.

There are N roadworks scheduled on this street.
The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5.

Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point.

Find the distance each of the Q people will walk.

Constraints

All values in input are integers.

1 \leq N, Q \leq 2 \times 10^5

0 \leq S_i < T_i \leq 10^9

1 \leq X_i \leq 10^9

0 \leq D_1 < D_2 < ... < D_Q \leq 10^9

If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap.

Input

Input is given from Standard Input in the following format:

N Q
S_1 T_1 X_1
:
S_N T_N X_N
D_1
:
D_Q

Output

Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever.

Sample Input 1

4 6
1 3 2
7 13 10
18 20 13
3 4 2
0
1
2
3
5
8

Sample Output 1

2
2
10
-1
13
-1

The first person starts coordinate 0 at time 0 and stops walking at coordinate 2 when reaching a point blocked by the first roadwork at time 2.

The second person starts coordinate 0 at time 1 and reaches coordinate 2 at time 3. The first roadwork has ended, but the fourth roadwork has begun, so this person also stops walking at coordinate 2.

The fourth and sixth persons encounter no roadworks while walking, so they walk forever. The output for these cases is -1.


-- https://github.com/minoki/my-atcoder-solutions
{-# LANGUAGE BangPatterns #-}
import Data.Char
import Data.List
import Data.Monoid
import Control.Monad
import qualified Data.ByteString.Char8 as BS
import qualified Data.Vector.Unboxed as U

data Tree a = Leaf !Int !Int a
            | Bin !Int !Int !Int (Tree a) (Tree a)

getAt :: Tree a -> Int -> a
getAt (Leaf a b x) !i | a <= i && i < b = x
                      | otherwise = error "out of range"
getAt (Bin a b c l r) !i | i < b = getAt l i
                         | otherwise = getAt r i

fill :: Int -> Int -> a -> Tree a -> Tree a
fill !a !b x l@(Leaf a' b' y)
  | b < a' || b' < a = l
  -- a' <= b && a <= b':
  | a <= a' && b' <= b = Leaf a' b' x
  | a <= a' {- , b < b' -} = Bin a' b b' (Leaf a' b x) (Leaf b b' y)
  | {- a' < a, -} b' <= b = Bin a' a b' (Leaf a' a x) (Leaf a b' x)
  | otherwise {- a' < a, b < b' -} = Bin a' a b' (Leaf a' a y) (Bin a b b' (Leaf a b x) (Leaf b b' y))
fill !a !b x (Bin a' b' c' l r)
  | a <= a' && c' <= b = Leaf a b x
  | b <= b' = Bin a' b' c' (fill a b x l) r
  | b' <= a = Bin a' b' c' l (fill a b x r)
  | otherwise {- a < b', b' < b -} = Bin a' b' c' (fill a b' x l) (fill b' b x r)

main = do
  [n,q] <- map (read . BS.unpack) . BS.words <$> BS.getLine
  -- 1 <= n <= 2*10^5, 1 <= q <= 2*10^5
  works <- replicateM n $ do
    [s,t,x] <- unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
    return (s,t,x)
  let works' = U.fromListN n $ sortBy (\(s,t,x) (s',t',x') -> compare x' x <> compare s s' <> compare t t') works
  ds <- U.replicateM q $ do
    Just (d, _) <- BS.readInt <$> BS.getLine
    return d
  let result = U.foldl (\r (s,t,x) ->
                          let !s' = s - x
                              !t' = t - x
                          in fill s' t' x r
                       ) (Leaf 0 (10^9+1) (-1)) works'
  U.forM_ ds $ \d -> print (getAt result d :: Int)


-- https://github.com/minoki/my-atcoder-solutions
{-# LANGUAGE BangPatterns #-}
import Data.Char
import Data.List
import Control.Monad
import qualified Data.ByteString.Char8 as BS
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM

-- let k = search v f i j
-- => (k < j || f k) && (k == i || not (f (k-1)))
search :: (U.Unbox a) => U.Vector a -> (a -> Bool) -> Int -> Int -> Int
search !v !f !i !j | f (v U.! i) = i
                   | otherwise = loop i j
  where loop !i !j | j == i + 1 = j
                   | f (v U.! k) = loop i k
                   | otherwise = loop k j
          where k = (i + j) `quot` 2

main = do
  [n,q] <- map (read . BS.unpack) . BS.words <$> BS.getLine
  works <- U.replicateM n $ do
    [s,t,x] <- unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
    return (s,t,x)
  ds <- U.replicateM q $ do
    Just (d, _) <- BS.readInt <$> BS.getLine
    return d
  let result = U.create $ do
        vec <- UM.replicate q (10^9+1)
        U.forM_ works $ \(s,t,x) -> do
          let !s' = s - x
              !t' = t - x
              i0 = search ds (\d -> s' <= d) 0 q
              i1 | i0 == q = q
                 | otherwise = search ds (\d -> t' <= d) i0 q
          forM_ [i0..(min i1 q)-1] $ \i -> do
            UM.modify vec (\y -> min y x) i
        return vec
  U.forM_ result $ \r ->
    if r == 10^9+1
    then putStrLn "-1"
    else print r


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns          #-}
{-# LANGUAGE CPP                   #-}
{-# LANGUAGE LambdaCase            #-}
{-# LANGUAGE MagicHash             #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE MultiWayIf            #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE TupleSections         #-}
{-# LANGUAGE TypeFamilies          #-}
{-# LANGUAGE ViewPatterns          #-}

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Data.Bool
import qualified Data.ByteString             as B
import qualified Data.ByteString.Char8       as C
import qualified Data.ByteString.Unsafe      as B
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
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.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 <- readLn :: IO Int
    xs <- U.unfoldrN n (C.readInt.C.dropWhile isSpace) <$> C.getLine
    print $ solve n xs

solve :: Int -> U.Vector Int -> Int
solve n xs = F.foldl' max 0 $ map step [1..n - 2]
  where
    step diff = go 0 0 (n - 1) 0 IS.empty
      where
        go !res !acc !l !r !used
            -- | traceShow (diff, l, r, acc) False = undefined
            | 0 < l', r' < n - 1
            , l' /= r'
            , IS.notMember l' used
            , IS.notMember r' used
            = go (max res acc') acc' l' r' (IS.insert l' $ IS.insert r' used)
            | otherwise = res
          where
            l' = l - diff
            r' = r + diff
            acc' = acc + U.unsafeIndex xs l' + U.unsafeIndex xs r'

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

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

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

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

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

Score : 600 points

Problem Statement

There is an infinitely large pond, which we consider as a number line.
In this pond, there are N lotuses floating at coordinates 0, 1, 2, ..., N-2 and N-1.
On the lotus at coordinate i, an integer s_i is written.

You are standing on the lotus at coordinate 0. You will play a game that proceeds as follows:

1. Choose positive integers A and B. Your score is initially 0.

2. Let x be your current coordinate, and y = x+A. The lotus at coordinate x disappears, and you move to coordinate y.

If y = N-1, the game ends.

If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y.

If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends.

3. Let x be your current coordinate, and y = x-B. The lotus at coordinate x disappears, and you move to coordinate y.

If y = N-1, the game ends.

If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y.

If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends.

4. Go back to step 2.

You want to end the game with as high a score as possible.
What is the score obtained by the optimal choice of A and B?

Constraints

3 \leq N \leq 10^5

-10^9 \leq s_i \leq 10^9

s_0=s_{N-1}=0

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
s_0 s_1 ...... s_{N-1}

Output

Print the score obtained by the optimal choice of A and B.

Sample Input 1

5
0 2 5 1 0

Sample Output 1

3

If you choose A = 3 and B = 2, the game proceeds as follows:

Move to coordinate 0 + 3 = 3. Your score increases by s_3 = 1.

Move to coordinate 3 - 2 = 1. Your score increases by s_1 = 2.

Move to coordinate 1 + 3 = 4. The game ends with a score of 3.

There is no way to end the game with a score of 4 or higher, so the answer is 3. Note that you cannot land the lotus at coordinate 2 without drowning later.

Sample Input 2

6
0 10 -7 -4 -13 0

Sample Output 2

0

The optimal strategy here is to land the final lotus immediately by choosing A = 5 (the value of B does not matter).

Sample Input 3

11
0 -4 0 -99 31 14 -15 -39 43 18 0

Sample Output 3

59


solver::Int->Int->Int
solver a b = if a >= 13 then b else if a>=6 then div b 2 else 0

main::IO()
main=do
  a:b:_ <- return.map read.words =<< getLine
  print (solver a b)

Score : 100 points

Problem Statement

Takahashi, who is A years old, is riding a Ferris wheel.

It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currency of Japan.)

Find the cost of the Ferris wheel for Takahashi.

Constraints

0 ≤ A ≤ 100

2 ≤ B ≤ 1000

B is an even number.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the cost of the Ferris wheel for Takahashi.

Sample Input 1

30 100

Sample Output 1

100

Takahashi is 30 years old now, and the cost of the Ferris wheel is 100 yen.

Sample Input 2

12 100

Sample Output 2

50

Takahashi is 12 years old, and the cost of the Ferris wheel is the half of 100 yen, that is, 50 yen.

Sample Input 3

0 100

Sample Output 3

0

Takahashi is 0 years old, and he can ride the Ferris wheel for free.


import Control.Applicative
import Control.Monad

main = do
  [r, d, init] <- map (read::String -> Int) . words <$> getLine
  let arr = scanl (\acc i -> r * acc - d) init [0..9]
  forM_ arr (\i -> print i)

Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds:

x_{i+1} = rx_i - D

You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order.

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

Print 10 lines. The i-th line (1 ≤ i ≤ 10) should contain x_{2000+i} as an integer.

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

For example, x_{2001} = rx_{2000} - D = 2 \times 20 - 10 = 30 and x_{2002} = rx_{2001} - D = 2 \times 30 - 10 = 50.

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


main = do
  [r,d,x] <- map read . words <$> getLine
  putStrLn $ unlines $ map show (f r d x [])
f :: Int -> Int -> Int -> [Int] -> [Int]
f a b y ans
  | length ans < 10 = f a b (y*a-b) (ans ++ [y*a-b])
  | otherwise = ans


import Data.Bits
import Data.Foldable (foldlM,foldrM)
import Data.Maybe (fromJust)
import Data.List
import qualified Data.Vector.Unboxed.Mutable as V
import Control.Monad
import qualified Data.ByteString.Lazy.Char8 as B
import Debug.Trace

main :: IO ()
main = do
  [r,d,x] <- map read.words <$> getLine :: IO [Int]
  forM_ (take 10 $ iterate (\y -> r*y - d) x) $ \ans -> do
    print $ ans


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

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

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

limit :: [[Int]] -> Int -> Int -> Int
limit [] mi ma = ma - mi + 1
limit (lr : lrs) mi ma
  | mi <= ma = limit lrs mi' ma'
  | otherwise = 0
  where
    l = head lr
    r = last lr
    mi' = maximum [l, mi]
    ma' = minimum [r, ma]

main = do
  [n, m] <- getIntList
  lrs <- getIntNList m
  print $ limit lrs 1 n

Score : 300 points

Problem Statement

We have N ID cards, and there are M gates.

We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.

How many of the ID cards allow us to pass all the gates alone?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

Print the number of ID cards that allow us to pass all the gates alone.

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

Two ID cards allow us to pass all the gates alone, as follows:

The first ID card does not allow us to pass the second gate.

The second ID card allows us to pass all the gates.

The third ID card allows us to pass all the gates.

The fourth ID card does not allow us to pass the first gate.

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


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

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

--------------------------------------------------------------------------
step :: VU.Vector Int -> (Int, Int) -> VU.Vector Int
step vec (l,r) = VU.accumulate (+) vec (VU.fromList [(l,1),(r+1,-1)])

main = do
    [n,m] <- sLineToIntL
    lrs <- mLinesToTupleV m
    let vec = VU.scanl' (+) 0 $ VU.foldl' step (VU.replicate (n+2) 0) lrs
    print $ VU.length $ VU.filter (==m) vec
--------------------------------------------------------------------------

-- Input Util
int :: IO Int
int = readLn

double :: IO Double
double = readLn

str :: IO String
str = getLine

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

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

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

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

sLineToIntL :: IO [Int]
sLineToIntL = strBS >>= return . map bsToInt . BC.words

sLineToDoubleL :: IO [Double]
sLineToDoubleL = strBS >>= return . map bsToDouble . BC.words

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

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

mLinesToIntL :: Int -> IO [Int]
mLinesToIntL n = replicateM n (strBS >>= return . bsToInt)

mLinesToDoubleL :: Int -> IO [Double]
mLinesToDoubleL n = replicateM n (strBS >>= return . bsToDouble)

mLinesToIntV :: Int -> IO (VU.Vector Int)
mLinesToIntV n = VU.replicateM n (strBS >>= return . bsToInt)

mLinesToDoubleV :: Int -> IO (VU.Vector Double)
mLinesToDoubleV n = VU.replicateM n (strBS >>= return . bsToDouble)

mLinesToTupleL :: Int -> IO [(Int, Int)]
mLinesToTupleL n = replicateM n (strBS >>= return . (\[a,b] -> (a,b)) . map bsToInt . BC.words)

mLinesToTripleL :: Int -> IO [(Int, Int, Int)]
mLinesToTripleL n = replicateM n (strBS >>= return . (\[a,b,c] -> (a,b,c)) . map bsToInt . BC.words)

mLinesToTupleV :: Int -> IO (VU.Vector (Int, Int))
mLinesToTupleV n = VU.replicateM n $ do
    bs <- strBS
    let
        Just (a, bs') = parseInt bs
        Just (b, _) = parseInt bs'
    return (a,b)

mLinesToTripleV :: Int -> IO (VU.Vector (Int, Int, Int))
mLinesToTripleV n = VU.replicateM n $ do
    bs <- strBS
    let
        Just (a, bs') = parseInt bs
        Just (b, bs'') = parseInt bs'
        Just (c, _) = parseInt bs''
    return (a,b,c)

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

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

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

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

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

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

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


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

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine
toTuple (x : y : _) = (x, y)

main = do
    [n, m] <- getIntList
    lrs <- map toTuple <$> replicateM m getIntList
    let (x, y) = foldl solve (1, n) lrs
    print $ max 0 (y - x + 1)

solve (l, r) (l', r') = (max l l', min r r')


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

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

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

import qualified Data.ByteString.Char8 as B

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

import Debug.Trace
import Text.Printf

readInt = readLn :: IO Int
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readNInts = readInt >>= flip replicateM readInt

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

main = do
	[ _, m ] <- readInts
	[ ls, rs ] <- transpose <$> replicateM m readInts
	let
		lb = foldl1 max ls
		ub = foldl1 min rs
	print $ max 0 $ ub - lb + 1