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

{- base -}
import qualified Control.Arrow               as Arrow
import           Control.Monad
import           Control.Monad.ST
import qualified Data.Bits                   as Bits
import qualified Data.Char                   as Char
import qualified Data.Foldable               as Foldable
import qualified Data.List                   as List
import           Data.Monoid
import           Data.Ord
import           Data.Ratio
import           Data.Semigroup
import qualified Data.Word                   as Word
import           GHC.Exts
import           Foreign                     hiding (void)
import           Unsafe.Coerce
{- bytestring -}
import qualified Data.ByteString.Char8       as BSC8
{- containers -}
import           Data.IntMap.Strict          (IntMap)
import qualified Data.IntMap.Strict          as IntMap
import           Data.IntSet                 (IntSet)
import qualified Data.IntSet                 as IntSet
import qualified Data.Sequence               as Seq
{- mtl -}
import           Control.Monad.State.Strict
{- transformers -}
import           Control.Monad.Reader
{- vector -}
import qualified Data.Vector                   as V
import qualified Data.Vector.Generic           as VG
import qualified Data.Vector.Generic.Mutable   as VGM
import qualified Data.Vector.Mutable           as VM
import qualified Data.Vector.Primitive         as VP
import qualified Data.Vector.Primitive.Mutable as VPM
import qualified Data.Vector.Unboxed           as VU
import qualified Data.Vector.Unboxed.Mutable   as VUM

main :: IO ()
main = do
  (n, k) <- parse2
  forM_ [1..k] $ \i -> do
    print $ comb (n-k+1) i * comb (k-1) (i-1)

-- Mint
#define MOD 1000000007

modulus :: (Num a) => a
modulus = MOD
{-# INLINE modulus #-}

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

(+%) :: Int -> Int -> Int
(I# x#) +% (I# y#) = case x# +# y# of
  r# -> I# (r# -# ((r# >=# MOD#) *# MOD#))
{-# INLINE (+%) #-}
(-%) :: Int -> Int -> Int
(I# x#) -% (I# y#) = case x# -# y# of
  r# -> I# (r# +# ((r# <# 0#) *# MOD#))
{-# INLINE (-%) #-}
(*%) :: Int -> Int -> Int
(I# x#) *% (I# y#) = I# ((x# *# y#) `remInt#` MOD#)
{-# INLINE (*%) #-}
(/%) :: Int -> Int -> Int
(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 (/%) #-}
(^%) :: Int -> Int -> Int
x ^% n
  | n > 0  = go 1 x n
  | n == 0 = 1
  | otherwise = go 1 (1 /% x) (-n)
  where
    go !acc !y !m
      | m Bits..&. 1 == 0 = go acc (y *% y) (Bits.unsafeShiftR m 1)
      | m == 1 = acc *% y
      | otherwise = go (acc *% y) (y *% y) (Bits.unsafeShiftR (m - 1) 1)

newtype Mint = Mint{ getMint :: Int} deriving (Eq, Ord)

-- Mintは数値
instance Num Mint where
  (+) = coerce (+%)
  (-) = coerce (-%)
  (*) = coerce (*%)
  abs                 = id
  signum              = const (Mint 1)
  fromInteger x       = Mint . fromInteger $ mod x modulus
-- Mintは表示可能
instance Show Mint where
  show (Mint x) = show x
-- Mintは上限・下限を持つ
instance Bounded Mint where
  minBound = Mint 0
  maxBound = Mint $ MOD - 1
-- Mintは列挙型
instance Enum Mint where
  toEnum = intMod
  fromEnum = fromIntegral
-- Mintは実数
instance Real Mint where
  toRational (Mint x) = toRational x
-- Mintは有理数
instance Fractional Mint where
  (Mint x) / (Mint y) = Mint (x /% y)
  fromRational q      = fromInteger (numerator q) / fromInteger (denominator q)
-- Mintは整数
instance Integral Mint where
  quotRem x y = (x / y, x - x / y * y)
  toInteger (Mint x) = toInteger x

newtype instance VUM.MVector s Mint = MV_Mint (VUM.MVector s Int)
newtype instance VU.Vector Mint     =  V_Mint (VU.Vector Int)

-- MintをVectorに乗せることができる
instance VU.Unbox Mint
instance VGM.MVector VUM.MVector Mint where
  {-# INLINE basicLength #-}
  basicLength (MV_Mint v) = VGM.basicLength v
  {-# INLINE basicUnsafeSlice #-}
  basicUnsafeSlice i n (MV_Mint v) = MV_Mint $ VGM.basicUnsafeSlice i n v
  {-# INLINE basicOverlaps #-}
  basicOverlaps (MV_Mint v1) (MV_Mint v2) = VGM.basicOverlaps v1 v2
  {-# INLINE basicUnsafeNew #-}
  basicUnsafeNew n = MV_Mint `fmap` VGM.basicUnsafeNew n
  {-# INLINE basicInitialize #-}
  basicInitialize (MV_Mint v) = VGM.basicInitialize v
  {-# INLINE basicUnsafeReplicate #-}
  basicUnsafeReplicate n x = MV_Mint `fmap` VGM.basicUnsafeReplicate n (coerce x)
  {-# INLINE basicUnsafeRead #-}
  basicUnsafeRead (MV_Mint v) i = coerce `fmap` VGM.basicUnsafeRead v i
  {-# INLINE basicUnsafeWrite #-}
  basicUnsafeWrite (MV_Mint v) i x = VGM.basicUnsafeWrite v i (coerce x)
  {-# INLINE basicClear #-}
  basicClear (MV_Mint v) = VGM.basicClear v
  {-# INLINE basicSet #-}
  basicSet (MV_Mint v) x = VGM.basicSet v (coerce x)
  {-# INLINE basicUnsafeCopy #-}
  basicUnsafeCopy (MV_Mint v1) (MV_Mint v2) = VGM.basicUnsafeCopy v1 v2
  {-# INLINE basicUnsafeMove #-}
  basicUnsafeMove (MV_Mint v1) (MV_Mint v2) = VGM.basicUnsafeMove v1 v2
  {-# INLINE basicUnsafeGrow #-}
  basicUnsafeGrow (MV_Mint v) n = MV_Mint `fmap` VGM.basicUnsafeGrow v n

instance VG.Vector VU.Vector Mint where
  {-# INLINE basicUnsafeFreeze #-}
  basicUnsafeFreeze (MV_Mint v) = V_Mint `fmap` VG.basicUnsafeFreeze v
  {-# INLINE basicUnsafeThaw #-}
  basicUnsafeThaw (V_Mint v) = MV_Mint `fmap` VG.basicUnsafeThaw v
  {-# INLINE basicLength #-}
  basicLength (V_Mint v) = VG.basicLength v
  {-# INLINE basicUnsafeSlice #-}
  basicUnsafeSlice i n (V_Mint v) = V_Mint $ VG.basicUnsafeSlice i n v
  {-# INLINE basicUnsafeIndexM #-}
  basicUnsafeIndexM (V_Mint v) i = coerce `fmap` VG.basicUnsafeIndexM v i
  basicUnsafeCopy (MV_Mint mv) (V_Mint v) = VG.basicUnsafeCopy mv v
  {-# INLINE elemseq #-}
  elemseq _ = seq

intMod :: (Integral int) => int -> Mint
intMod x = fromIntegral $ mod (fromIntegral x) MOD
{-# INLINE intMod #-}
mintValidate :: Mint -> Bool
mintValidate (Mint x) = 0 <= x && x < MOD
{-# INLINE mintValidate #-}

-- utils
{-# INLINE fact #-}
fact :: Int -> Mint
fact = VU.unsafeIndex factCache

{-# INLINE recipFact #-}
recipFact :: Int -> Mint
recipFact = VU.unsafeIndex recipFactCache

{-# INLINE perm #-}
perm :: Int -> Int -> Mint
perm n k
  | n < k     = 0
  | otherwise = fact n * recipFact k

{-# INLINE comb #-}
comb :: Int -> Int -> Mint
comb n k
  | n < k     = Mint 0
  | otherwise = fact n * recipFact (n - k) * recipFact k

#define FACT_CACHE_SIZE 2048

{-# INLINE factCacheSize #-}
factCacheSize :: Int
factCacheSize = min (modulus - 1) FACT_CACHE_SIZE

{-# NOINLINE factCache #-}
factCache :: VU.Vector Mint
factCache = VU.scanl' (\ x y -> x * coerce y) (1 :: Mint) $ VU.generate factCacheSize (+ 1)
{-# NOINLINE recipFactCache #-}
recipFactCache :: VU.Vector Mint
recipFactCache = VU.scanr' ((*) . coerce) (1 / factCache VU.! factCacheSize) $ VU.generate factCacheSize (+ 1)

powN :: Int -> VU.Vector Mint
powN n = VU.scanl' (\acc x -> acc * intMod x) 1 $ VU.replicate factCacheSize n

--input
type Parser a = BSC8.ByteString -> Maybe (a, BSC8.ByteString)
parseInt :: Parser Int
parseInt = fmap (Arrow.second BSC8.tail) . BSC8.readInt
parseChar :: [Char] -> VU.Vector Char
parseChar = VU.fromList
parse1 :: IO Int
parse1 = readLn
parse2 :: IO (Int, Int)
parse2 = (\vec -> (vec VU.! 0, vec VU.! 1)) . VU.unfoldrN 2 parseInt <$> BSC8.getLine
parse3 :: IO (Int, Int, Int)
parse3 = (\vec -> (vec VU.! 0, vec VU.! 1, vec VU.! 2)) . VU.unfoldrN 3 parseInt <$> BSC8.getLine
parse4 :: IO (Int, Int, Int, Int)
parse4 = (\vec -> (vec VU.! 0, vec VU.! 1, vec VU.! 2, vec VU.! 3)) . VU.unfoldrN 4 parseInt <$> BSC8.getLine
parseM :: Int -> IO (VU.Vector Int)
parseM m = VU.unfoldrN m parseInt <$> BSC8.getLine
parseN :: Int -> IO (VU.Vector Int)
parseN n = VU.replicateM n parse1
parseNM :: Int -> Int -> IO (V.Vector (VU.Vector Int))
parseNM n m = V.replicateM n $ VU.unfoldrN m parseInt <$> BSC8.getLine
parseANBN :: Int -> IO (VU.Vector Int, VU.Vector Int)
parseANBN n = VU.unzip . VU.unfoldrN n (runStateT $ (,) <$> pint <*> pint) <$> BSC8.getContents
  where
    pint :: StateT BSC8.ByteString Maybe Int
    pint = coerce $ BSC8.readInt . BSC8.dropWhile Char.isSpace

-- 使い方
--
-- 入力
-- n
-- => parse1
--
-- 入力
-- n m
-- => parse2
--
-- 入力
-- n m l
-- => parse3
--
-- 入力
-- p q r s
-- => parse4
--
-- 入力
-- m
-- a1 a2 a3 .. am
-- => parseM m
--
-- 入力
-- n
-- a1
-- a2
-- a3
-- ...
-- an
-- => parseN n
--
-- 入力
-- n m
-- a1,1 a1,2 ....... a1,m
-- a2,1 a2,2 ....... a2,m
-- ...
-- ...
-- ...
-- an,1 an,1 ....... an,m
-- => parseNM n m
--
-- 入力
-- n
-- a1 b1
-- a2 b2
-- a3 b3
-- ...
-- an bn
-- => parseANBN n

Score : 400 points

Problem Statement

There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.

First, Snuke will arrange the N balls in a row from left to right.

Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible.

How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.

Constraints

1 \leq K \leq N \leq 2000

Input

Input is given from Standard Input in the following format:

N K

Output

Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7.

Sample Input 1

5 3

Sample Output 1

3
6
1

There are three ways to arrange the balls so that Takahashi will need exactly one move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B stands for red and blue, respectively).

There are six ways to arrange the balls so that Takahashi will need exactly two moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B), (B, R, B, B, R), and (B, R, R, B, B).

There is one way to arrange the balls so that Takahashi will need exactly three moves: (B, R, B, R, B).

Sample Input 2

2000 3

Sample Output 2

1998
3990006
327341989

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


{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE RankNTypes #-}

import GHC.TypeLits

import Data.Int
import Data.Proxy
import qualified Data.Map.Lazy as Map
import Data.List
import Data.Bits
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
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.Array.IArray as Array
import Data.Array.MArray
import Data.Array.ST
--import Data.Monoid
--import Data.Semigroup

import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Control.Monad.Primitive
import Control.Monad.State

import Debug.Trace

type M = Mint 1000000007

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

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

  let factorial = factorialTable 200000 :: V.Vector M

  let
    p n k
      | n < k || n < 0 || k < 0 = 0
      | otherwise = (factorial V.! n) * (invMint $ factorial V.! (n-k))

  let
    c n k
      | n < k || n < 0 || k < 0 = 0
      | otherwise = (p n k) * (invMint $ factorial V.! k)

  let
    h n k
      | n == 0 && k == 0 = 1
      | otherwise = c (n+k-1) k

  forM_ [1..k] $ \i -> do
    print $ getMintValue $ (c (k-1) (i-1)) * (h (i+1) (n-k-i+1))

{-- Mod Int --}
data Mint (m :: Nat) = Mint {getMintValue :: Integer} deriving (Eq, Show)

getMintMod :: forall p. KnownNat p => Mint p -> Integer
getMintMod = natVal

makeMint :: forall p. KnownNat p => Integer -> Mint p
makeMint a
  | 0 <= a && a < p = Mint $ fromInteger $ a
  | otherwise = Mint $ fromInteger $ a `mod` p
  where p = natVal $ (Proxy :: Proxy p)

instance KnownNat p => Num (Mint p) where
  (Mint a) + (Mint b) = makeMint $ a + b
  (Mint a) - (Mint b) = makeMint $ a - b
  (Mint a) * (Mint b) = makeMint $ a * b
  negate (Mint a) = makeMint $ negate a
  abs = id
  signum (Mint a) = if a == 0 then 0 else 1
  fromInteger = makeMint

invMint :: forall p. KnownNat p => Mint p -> Mint p
invMint m = let p = getMintMod m in m ^ (p - 2)

powerMint :: forall p. KnownNat p => Integer -> Integer -> Mint p
powerMint n p
  | p >= 0 = (fromInteger n :: Mint p) ^ p
  | otherwise = invMint $ powerMint n (-p)

factorialTable :: forall p. KnownNat p => Int -> V.Vector (Mint p)
factorialTable n = V.scanl (*) (makeMint 1) (V.fromList $ map (makeMint . fromIntegral) [1..n])

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.


-- https://github.com/minoki/my-atcoder-solutions
{-# LANGUAGE BangPatterns #-}
import Data.Char (isSpace)
import Data.List (unfoldr)
import Control.Monad
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.ByteString.Char8 as BS
import qualified Data.IntSet as IntSet
import Data.Foldable
import Control.Monad.ST

main = do
  [n,m] <- unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  edges <- U.replicateM m $ do
    [u,v] <- unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
    return (u-1,v-1)
  [s,t] <- map (subtract 1) . unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  let graph1 :: V.Vector IntSet.IntSet
      graph1 = V.create $ do
        vec <- VM.replicate n IntSet.empty
        U.forM_ edges $ \(u,v) -> do
          s <- VM.read vec u
          VM.write vec u $! IntSet.insert v s
        return vec
      graph2 :: V.Vector IntSet.IntSet
      graph2 = V.create $ do
        vec <- VM.new n
        let go 0 !u = IntSet.singleton u
            go 1 !u = graph1 V.! u
            go i !u = foldMap_IntSet (go (i - 1)) $ graph1 V.! u
        forM_ [0..n-1] $ \u -> do
          VM.write vec u $! go 3 u
        return vec
      result = runST $ do
        visited <- UM.replicate n False
        -- bfs :: IntSet -> ST s (Maybe Int)
        let bfs !depth ss = do
              forM_IntSet ss $ \u ->
                UM.write visited u True
              let ts = foldMap_IntSet (graph2 V.!) ss
              ts' <- foldMapM_IntSet (\v -> do
                                         d <- UM.read visited v
                                         pure $ if d then IntSet.empty else IntSet.singleton v
                                     ) ts
              if t `IntSet.member` ts'
                then return (Just depth)
                else if IntSet.null ts'
                     then return Nothing
                     else bfs (depth+1) ts'
        bfs 1 (IntSet.singleton s)
  case result of
    Nothing -> putStrLn "-1"
    Just d -> print d

foldMap_IntSet :: (Monoid n) => (Int -> n) -> IntSet.IntSet -> n
foldMap_IntSet f set = go set
  where
    go set = case IntSet.splitRoot set of
               [] -> mempty
               [x] -> foldMap f (IntSet.toList x)
               xs -> foldMap go xs

forM_IntSet :: Monad m => IntSet.IntSet -> (Int -> m ()) -> m ()
forM_IntSet set f = go set
  where
    go set = case IntSet.splitRoot set of
               [] -> return ()
               [x] -> forM_ (IntSet.toList x) f
               xs -> forM_ xs go

foldMapM_IntSet :: (Monoid n, Monad m) => (Int -> m n) -> IntSet.IntSet -> m n
foldMapM_IntSet f set = go set
  where
    go set = case IntSet.splitRoot set of
               [] -> return mempty
               [x] -> foldlM (\x v -> mappend x <$> f v) mempty (IntSet.toList x)
               xs -> foldlM (\x set' -> mappend x <$> go set') mempty xs

Score : 500 points

Problem Statement

Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G.
G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.

First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.

Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.

Constraints

2 \leq N \leq 10^5

0 \leq M \leq \min(10^5, N (N-1))

1 \leq u_i, v_i \leq N(1 \leq i \leq M)

u_i \neq v_i (1 \leq i \leq M)

If i \neq j, (u_i, v_i) \neq (u_j, v_j).

1 \leq S, T \leq N

S \neq T

Input

Input is given from Standard Input in the following format:

N M
u_1 v_1
:
u_M v_M
S T

Output

If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1.
If he can, print the minimum number of ken-ken-pa needed to reach vertex T.

Sample Input 1

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

Sample Output 1

2

Ken can reach Vertex 3 from Vertex 1 in two ken-ken-pa, as follows: 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 in the first ken-ken-pa, then 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 in the second ken-ken-pa. This is the minimum number of ken-ken-pa needed.

Sample Input 2

3 3
1 2
2 3
3 1
1 2

Sample Output 2

-1

Any number of ken-ken-pa will bring Ken back to Vertex 1, so he cannot reach Vertex 2, though he can pass through it in the middle of a ken-ken-pa.

Sample Input 3

2 0
1 2

Sample Output 3

-1

Vertex S and Vertex T may be disconnected.

Sample Input 4

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

Sample Output 4

2


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

main = do
 n <- getLine
 putStrLn $ (solve n)?("Good","Bad")

solve s@(a:b:x) = (a==b)?(False,True)&&(null x)?(True,solve(tail s))

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


main :: IO ()
main = do
  [a,b,c,d] <- getLine
  putStrLn $ if a /= b && b /= c && c /= d
             then "Good"
             else "Bad"


import Control.Monad

import Data.Ord
import Data.List
import Data.Function
import Data.Maybe

import qualified Data.ByteString.Char8 as BS

import Debug.Trace

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

readInt = read :: String -> Integer
readIntTuple = tuplify2 . map readInt . words
readIntList = map readInt . words

getInt = readInt <$> getLine
getIntList = readIntList <$> getLine
getIntMatrix = map readIntList . lines <$> getContents
getIntTuple = readIntTuple <$> getLine
getIntTuples = map readIntTuple . lines <$> getContents

main = do
  [n,l] <- getIntList
  print $ f n l

-- リンゴ1の味はl
-- リンゴnの味はl+n+1
-- 総計はn*l+(n-1)n/2
-- 絶対値最小のリンゴを引けば良い、それは両端のいずれか又は0
f n l
  | taste1 > 0 && tasteN > 0 = tasteSum-taste1
  | taste1 < 0 && tasteN < 0 = tasteSum-tasteN
  | otherwise = tasteSum
  where
    taste1 = l
    tasteN = l+n-1
    tasteSum = n*l + (n-1)*n `div` 2

Score : 200 points

Problem Statement

You have N apples, called Apple 1, Apple 2, Apple 3, ..., Apple N. The flavor of Apple i is L+i-1, which can be negative.

You can make an apple pie using one or more of the apples. The flavor of the apple pie will be the sum of the flavors of the apples used.

You planned to make an apple pie using all of the apples, but being hungry tempts you to eat one of them, which can no longer be used to make the apple pie.

You want to make an apple pie that is as similar as possible to the one that you planned to make. Thus, you will choose the apple to eat so that the flavor of the apple pie made of the remaining N-1 apples will have the smallest possible absolute difference from the flavor of the apple pie made of all the N apples.

Find the flavor of the apple pie made of the remaining N-1 apples when you choose the apple to eat as above.

We can prove that this value is uniquely determined.

Constraints

2 \leq N \leq 200

-100 \leq L \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N L

Output

Find the flavor of the apple pie made of the remaining N-1 apples when you optimally choose the apple to eat.

Sample Input 1

5 2

Sample Output 1

18

The flavors of Apple 1, 2, 3, 4, and 5 are 2, 3, 4, 5, and 6, respectively. The optimal choice is to eat Apple 1, so the answer is 3+4+5+6=18.

Sample Input 2

3 -1

Sample Output 2

0

The flavors of Apple 1, 2, and 3 are -1, 0, and 1, respectively. The optimal choice is to eat Apple 2, so the answer is (-1)+1=0.

Sample Input 3

30 -50

Sample Output 3

-1044


main = do
    [a,b,c,d] <- map read . words <$> getLine :: IO [Int]
    let f x = x - (x `div` c + x `div` d - (x `div` (c * d `div` gcd c d)))
    print $ f b - f (a-1)

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


{- A
f :: [Char] -> String
f (x:y:ys)
    | x == y = "Bad"
    | ys == [] ="Good"
    | otherwise = f (y:ys)

main = getLine >>= putStrLn . f
-}

{- B
del :: Int -> Int -> Int -> Int
del d x y
    | d == abs x = y
    | d == abs y = x
    | otherwise = x + y

f :: [Int] -> String
f (n:l:xs) = do
    let x = [l+i-1 | i <- [1..n] ]
    let d = minimum $ map abs x
    show $ foldr1 (del d) x

main = getLine >>= putStrLn . f . map read . words
-}

{- C, TLE
f (a:b:c:d:xs) = length [x | x <- [a..b], x `mod` c /= 0 && x `mod` d /= 0 ]
-}

div2 (a,b) d
    | a <= 1    = b `div` d
    | otherwise = b `div` d - (a - 1) `div` d

f (a:b:c:d:xs)
    | c `mod` d == 0 = b - a + 1 - (a,b) `div2` c
    | d `mod` c == 0 = b - a + 1 - (a,b) `div2` d
    | otherwise      = b - a + 1 - (a,b) `div2` c - (a,b) `div2` d + (a,b) `div2` (lcm c d)

main = getLine >>= putStrLn . show . f . map read . words


{- A
f :: [Char] -> String
f (x:y:ys)
    | x == y = "Bad"
    | ys == [] ="Good"
    | otherwise = f (y:ys)

main = getLine >>= putStrLn . f
-}

{- B
del :: Int -> Int -> Int -> Int
del d x y
    | d == abs x = y
    | d == abs y = x
    | otherwise = x + y

f :: [Int] -> String
f (n:l:xs) = do
    let x = [l+i-1 | i <- [1..n] ]
    let d = minimum $ map abs x
    show $ foldr1 (del d) x

main = getLine >>= putStrLn . f . map read . words
-}

{- C, TLE
f (a:b:c:d:xs) = length [x | x <- [a..b], x `mod` c /= 0 && x `mod` d /= 0 ]
-}

div2 (a,b) d = b `div` d - a `div` d

f (a:b:c:d:xs)
    | c `mod` d == 0 = (a,b) `div2` c
    | d `mod` c == 0 = (a,b) `div2` d
    | otherwise = b - a +1 - (a,b) `div2` c - (a,b) `div2` d + (a,b) `div2` (lcm c d)

main = getLine >>= putStrLn . show . f . map read . words


{-# 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
import Debug.Trace

solve :: Int -> VU.Vector (Int, Int) -> Bool
solve !n !abn = snd $ foldr
  ( \(!a, !b) (!acc, !r) ->
    if r then let acc' = acc + a in (acc', acc' <= b) else (acc, r)
  )
  (0, True)
  abn'
  where abn' = sortBy (\(x, y) (x1, y1) -> compare y1 y) $ VU.toList abn

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

  n   <- (\vec -> (vec VU.! 0)) . VU.unfoldrN 1 readInt <$> B.getLine
  abn <-
    VU.replicateM n
    $   (\vec -> (vec VU.! 0, vec VU.! 1))
    .   VU.unfoldrN 2 readInt
    <$> B.getLine
  putStrLn $ if solve n abn then "Yes" else "No"

Score: 400 points

Problem Statement

Kizahashi, who was appointed as the administrator of ABC at National Problem Workshop in the Kingdom of AtCoder, got too excited and took on too many jobs.

Let the current time be time 0. Kizahashi has N jobs numbered 1 to N.

It takes A_i units of time for Kizahashi to complete Job i. The deadline for Job i is time B_i, and he must complete the job before or at this time.

Kizahashi cannot work on two or more jobs simultaneously, but when he completes a job, he can start working on another immediately.

Can Kizahashi complete all the jobs in time? If he can, print Yes; if he cannot, print No.

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
.
.
.
A_N B_N

Output

If Kizahashi can complete all the jobs in time, print Yes; if he cannot, print No.

Sample Input 1

5
2 4
1 9
1 8
4 9
3 12

Sample Output 1

Yes

He can complete all the jobs in time by, for example, doing them in the following order:

Do Job 2 from time 0 to 1.

Do Job 1 from time 1 to 3.

Do Job 4 from time 3 to 7.

Do Job 3 from time 7 to 8.

Do Job 5 from time 8 to 11.

Note that it is fine to complete Job 3 exactly at the deadline, time 8.

Sample Input 2

3
334 1000
334 1000
334 1000

Sample Output 2

No

He cannot complete all the jobs in time, no matter what order he does them in.

Sample Input 3

30
384 8895
1725 9791
170 1024
4 11105
2 6
578 1815
702 3352
143 5141
1420 6980
24 1602
849 999
76 7586
85 5570
444 4991
719 11090
470 10708
1137 4547
455 9003
110 9901
15 8578
368 3692
104 1286
3 4
366 12143
7 6649
610 2374
152 7324
4 7042
292 11386
334 5720

Sample Output 3

Yes


import Data.Graph.Inductive.Graph
import Data.List
import Data.Graph.Inductive.PatriciaTree

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

solve n k = case ans of
  Nothing -> "-1"
  Just g -> toAns g
  where
  ans = go k addingEdges (mkUGraph [1..n] []) :: (Maybe (Gr () ()))
  addingEdges = [(a,b,())|a<-[1..n-1],b<-[a+1..n-1]]
  go 0 _ g = Just g
  go _ [] _ = Nothing
  go k (e:es) g = go (k-1) es (insEdge e g)
  toAns = unlines . con . map f . go es . sort . edges
    where
    go es [] = es
    go []  _ = []
    go (e:es) (r:rs)
      | e == r = go es rs
      | otherwise = e : go es (r:rs)
    f (a,b) = unwords $ map show [a,b]
    es = [(a,b)|a<-[1..n-1],b<-[a+1..n-1]]
    con es = show (length es):es

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.


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

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.


-- {-# OPTIONS_GHC -Wall -Werror #-}

main :: IO()
main = do
  [x,a] <- map read . words <$> getLine
  ls <- map read . words <$> getLine
  print . length . filter (<= x) $ scanl (+) 0 ls

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.


import Data.Bits
import Data.List
import Control.Monad
import Data.Array.Unboxed
import Data.Array.MArray
import Data.Array.ST
import Control.Monad.ST
import Data.Maybe (fromJust)
import qualified Data.ByteString.Lazy.Char8 as B
import Debug.Trace

solve :: Int -> Int -> Int -> Int -> (Double,Int)
solve  w h x y = if (w `div` 2 == x && h `div` 2 == y)
  then ((fromIntegral (w*h) :: Double) / 2,1)
  else ((fromIntegral (w*h) :: Double) / 2,0)

print0 :: (Double,Int) -> IO ()
print0 (x,y) = putStrLn $ (show x) ++ " " ++ (show y)

main :: IO ()
main = do
  [w,h,x,y] <- map read.words <$> getLine :: IO [Int]
  print0 $ solve w h x 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.List

main = do
    -- r <- readLn -- 入力が一行に一文字の場合
    a <- map read . words <$> getLine -- 一行に入力が複数ある場合
    -- putStrLn $ show $ solve a b -- showの返り値がString型の場合
    -- putStrLn $ solve a b

    putStrLn $ show $ solve $ sort a -- showの返り値がString型の場合

solve :: [Int] -> Int
solve [a, b, _] = a + b

{-- その他 備忘録
    {{{ 型変換
       int 2 float: fromIntegral
       float 2 int: round
       int 2 string: show
    }}}

    {{{ モジュール
    Data.List: sort
    }}}
--}

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


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

ans :: [Int] -> Int
ans wn = snd $ foldl func (allW,allW) wn where
  func (a,m) w = (a-2*w,min m $ abs (a-2*w))
  allW = sum wn

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


import qualified Data.ByteString.Char8 as BC
import Data.Maybe
import Control.Monad.ST
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Set as Set

readIntLines :: IO [Int]
readIntLines = map (fst . fromJust . BC.readInt) . BC.lines <$> BC.getContents

solve :: Int -> Set.Set Int -> Int
solve n as = runSTUArray func ! n
  where
    func = do
      arr <- newArray (0, 10000) 0 :: ST s (STUArray s Int Int)
      mapM_ (iter arr) [0..10000]
      return arr
    iter a 0 = writeArray a 0 1
    iter a 1 = writeArray a 1 1
    iter a i = do
      v1 <- readArray a (i - 2)
      v2 <- readArray a (i - 1)
      let r1 = if Set.member (i - 2) as then 0 else v1
      let r2 = if Set.member (i - 1) as then 0 else v2
      writeArray a i ((r1 + r2) `mod` 1000000007)

main :: IO ()
main = do
  [n, m] <- map read . words <$> getLine
  as <- readIntLines
  print . solve n $ Set.fromList as

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.


import qualified Data.Vector.Unboxed as U
import qualified Data.Vector as V
import qualified Data.ByteString.Char8 as C
import qualified Data.Array.IO as A
import Debug.Trace
import Data.List
import Control.Monad
import Data.Ord

r :: Int -> IO (U.Vector Int)
r n = U.unfoldrN n (C.readInt . C.dropWhile (==' ')) <$> C.getLine

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

rp :: IO (Int,Int)
rp  = toTup . unfoldr    (C.readInt . C.dropWhile (==' ')) <$> C.getLine

toTup [a,b] = (a,b)

main :: IO ()
main = do
    [n,m] <- r'
    as' <- replicateM m readLn :: IO [Int]
    let as = (-1):(as' ++ [n+1])
    let dif = map ((fib!!) . pred) $ zipWith (-) (tail as) as
    print $ (foldl' (*) 1 dif) `mod` 1000000007

fib = 0:1:zipWith(+)fib(tail fib)


{-# 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 = readInt >>= print . ( * 180 ) . subtract 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 = do
    k <- getLine
    let x = length $ filter (== 'x') k
    putStrLn $ if x < 8 then "YES" else "NO"

Score : 200 points

Problem Statement

Takahashi is competing in a sumo tournament.
The tournament lasts for 15 days, during which he performs in one match per day.
If he wins 8 or more matches, he can also participate in the next tournament.

The matches for the first k days have finished.
You are given the results of Takahashi's matches as a string S consisting of o and x.
If the i-th character in S is o, it means that Takahashi won the match on the i-th day; if that character is x, it means that Takahashi lost the match on the i-th day.

Print YES if there is a possibility that Takahashi can participate in the next tournament, and print NO if there is no such possibility.

Constraints

1 \leq k \leq 15

S is a string of length k consisting of o and x.

Input

Input is given from Standard Input in the following format:

S

Output

Print YES if there is a possibility that Takahashi can participate in the next tournament, and print NO otherwise.

Sample Input 1

oxoxoxoxoxoxox

Sample Output 1

YES

Takahashi has 7 wins and 7 losses before the last match. If he wins that match, he will have 8 wins.

Sample Input 2

xxxxxxxx

Sample Output 2

NO


import           Control.Monad
import qualified Data.ByteString.Char8       as BS
import           Data.List
import           Data.Maybe
import qualified Data.Vector                 as VB
import qualified Data.Vector.Mutable         as VBM
import qualified Data.Vector.Unboxed         as V
import qualified Data.Vector.Unboxed.Mutable as VM

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

main = do
  n <- getInt

  vs <- VBM.new (n+1)
  VBM.set vs ([] :: [Int])

  replicateM (n-1) $ do
    [a, b] <- getIntList
    la <- VBM.read vs a
    VBM.write vs a (b:la)
    lb <- VBM.read vs b
    VBM.write vs b (a:lb)

  vs' <- VB.freeze vs

  cs <- getIntList
  let cs' = sortBy (flip compare) cs

  ws <- VM.new (n+1)
  VM.set ws (0::Int)

  let bfs [] _ = return ()
      bfs (x:xs) cs = do
        w <- VM.read ws x
        if w == 0
          then do VM.write ws x (head cs)
                  let cs' = tail cs
                      xs' = xs ++ (vs' VB.! x)
                  bfs xs' cs'
          else bfs xs cs

  bfs [1] cs'

  print $ sum $ tail cs'

  forM_ [1..n] $ \i -> do
    when (i > 1) $ putStr " "
    w <- VM.read ws i
    (putStr . show) w

  putStrLn ""

Score : 500 points

Problem Statement

You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N.
The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.

We will write a positive integer on each vertex in T and calculate our score as follows:

On each edge, write the smaller of the integers written on the two endpoints.

Let our score be the sum of the integers written on all the edges.

Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.

Constraints

1 \leq N \leq 10000

1 \leq a_i,b_i \leq N

1 \leq c_i \leq 10^5

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N

Output

Use the following format:

M
d_1 \ldots d_N

where M is the maximum possible score, and d_i is the integer to write on Vertex i.
d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N.
If there are multiple ways to achieve the maximum score, any of them will be accepted.

Sample Input 1

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

Sample Output 1

10
1 2 3 4 5

If we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written on the four edges will be 1,2,3,4, for the score of 10. This is the maximum possible score.

Sample Input 2

5
1 2
1 3
1 4
1 5
3141 59 26 53 59

Sample Output 2

197
59 26 3141 59 53

c_1,c_2,\ldots,c_N may not be pairwise distinct.


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

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 GHC.Exts (build, Int(..), Int#,
                 (+#), (*#), (-#), (<#), (>=#), (==#), quotRemInt#,
                 remInt#, uncheckedIShiftRL#, andI#, orI#,
                isTrue#)

#define MOD 1000003
modulus :: Int
modulus = MOD

main :: IO ()
main = do
  q <- readInt <$> getLine
  queries <- VU.unfoldrN q (runStateT $ liftA3 (,,) rInt rInt rInt)
             <$> BSL.getContents
  BSB.hPutBuilder stdout
    $ VU.foldr (\x -> (BSB.intDec x <>) . (BSB.char7 '\n' <>)) mempty
    $ (`VU.map` queries)
    $ \(!x, !d, !n) -> query x d n

{-# INLINE query #-}
query :: Int -> Int -> Int -> Int
query (I# x#) (I# d#) (I# n#) = I# (query# x# d# n#)

{-# INLINE query# #-}
query# :: Int# -> Int# -> Int# -> Int#
query# x# d# n#
  | isTrue# (x# ==# 0#) = 0#
  | isTrue# (n# >=# MOD#) = 0#
  | isTrue# (d# ==# 0#) = x# `powRem#` n#
query# x# d# n#
  | isTrue# (end# >=# MOD#) = 0#
  | otherwise = (unI# $ factorial `VU.unsafeIndex` (I# end#))
                `mult#` (unI# $ invFact `VU.unsafeIndex` (I# begm1#))
                `mult#` (d# `powRem#` n#)
  where
    begm1# = (x# `mult#` invMod# d#) -# 1#
    end# = begm1# +# n#

{-# INLINE CONLIKE unI# #-}
unI# :: Int -> Int#
unI# = \(I# x#) -> x#

-- assumes 0 <= x# < modulus, y# >= 0#.
powRem# :: Int# -> Int# -> Int#
powRem# x# y# = go 1# x# y#
  where
    go acc# val# 0# = acc#
    go acc# val# expt#
      = go (if isTrue# (andI# expt# 1#) then acc# `mult#` val# else acc#)
           (val# `mult#` val#)
           (expt# `uncheckedIShiftRL#` 1#)

{-# NOINLINE factorial #-}
factorial :: VU.Vector Int
factorial = VU.scanl' mult 1 $ VU.tail $ VU.generate modulus id

{-# NOINLINE invFact #-}
invFact :: VU.Vector Int
invFact = VU.map invMod factorial

{-# INLINE mult #-}
mult :: Int -> Int -> Int
mult = \(I# x#) (I# y#) -> I# (mult# x# y#)

{-# INLINE mult# #-}
mult# :: Int# -> Int# -> Int#
mult# = \ x# y# -> (x# *# y#) `remInt#` MOD#

{-# INLINE invMod #-}
invMod :: Int -> Int
invMod = \(I# x#) -> I# (invMod# x#)

{-# INLINE invMod# #-}
-- assumes 0 < x < modulus.
invMod# :: Int# -> Int#
invMod# x# = go 0# MOD# 1# x#
  where
    go a# x# b# 0# = a# +# if isTrue# (a# <# 0#) then MOD# else 0#
    go a# x# b# y# = go b# y# (a# -# q# *# b#) z#
      where (# q#,z# #) = x# `quotRemInt#` y#

#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 : 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 = do
    [a,p] <- map read . words <$> getLine :: IO [Int]
    print $ div ((a*3) + p) 2

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


import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T

main :: IO ()
main = do
  (a : p : _) <- map unsafeSignedDecimal . T.words <$> T.getLine :: IO [Int]
  print $ (3 * a + p) `div` 2

unsafeSignedDecimal :: T.Text -> Int
unsafeSignedDecimal s = case T.signed T.decimal s of
  Right (n, _) -> n


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

--------------------------------------------------------------------------
f :: String -> (String, Int)
f xs = (name, num)
    where
        name :: String
        name = takeWhile (not . isSpace) xs
        num :: Int
        num = read $ tail $ dropWhile (not . isSpace) xs

main = do
    n <- int
    xs <- sort . map (\(i,(s,p)) -> (s,negate p,i)) . zip [1..n] <$> (replicateM n $ getLine >>= return . f)
    forM_ xs $ \(_,_,i) -> print i
--------------------------------------------------------------------------

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

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

str :: IO String
str = getLine

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

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

Score : 200 points

Problem Statement

You have decided to write a book introducing good restaurants.
There are N restaurants that you want to introduce: Restaurant 1, Restaurant 2, ..., Restaurant N. Restaurant i is in city S_i, and your assessment score of that restaurant on a 100-point scale is P_i.
No two restaurants have the same score.

You want to introduce the restaurants in the following order:

The restaurants are arranged in lexicographical order of the names of their cities.

If there are multiple restaurants in the same city, they are arranged in descending order of score.

Print the identification numbers of the restaurants in the order they are introduced in the book.

Constraints

1 ≤ N ≤ 100

S is a string of length between 1 and 10 (inclusive) consisting of lowercase English letters.

0 ≤ P_i ≤ 100

P_i is an integer.

P_i ≠ P_j (1 ≤ i < j ≤ N)

Input

Input is given from Standard Input in the following format:

N
S_1 P_1
:
S_N P_N

Output

Print N lines. The i-th line (1 ≤ i ≤ N) should contain the identification number of the restaurant that is introduced i-th in the book.

Sample Input 1

6
khabarovsk 20
moscow 10
kazan 50
kazan 35
moscow 60
khabarovsk 40

Sample Output 1

3
4
6
1
5
2

The lexicographical order of the names of the three cities is kazan < khabarovsk < moscow. For each of these cities, the restaurants in it are introduced in descending order of score. Thus, the restaurants are introduced in the order 3,4,6,1,5,2.

Sample Input 2

10
yakutsk 10
yakutsk 20
yakutsk 30
yakutsk 40
yakutsk 50
yakutsk 60
yakutsk 70
yakutsk 80
yakutsk 90
yakutsk 100

Sample Output 2

10
9
8
7
6
5
4
3
2
1


import qualified Data.Vector.Unboxed as U
import qualified Data.Vector as V
import qualified Data.ByteString.Char8 as C
import qualified Data.Array.IO as A
import Debug.Trace
import Data.List
import Control.Monad
import Data.Ord

main :: IO ()
main = do
    n <- readLn
    sps <- replicateM n $ do
        [s,p] <- words <$> getLine
        return (s,read p) :: IO (String,Int)
    let procs = (sortOn (fst . snd) . sortBy (flip $ comparing (snd . snd)) . zip [1..]) sps
    mapM_ (print . fst) procs


import Control.Monad

import Data.Ord
import Data.List
import Data.Function
import Data.Maybe

import qualified Data.ByteString.Char8 as BS

import Debug.Trace

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

--Input functions with ByteString
readInt = fst . fromJust . BS.readInt
readIntTuple = tuplify2 . map readInt . BS.words
readIntList = map readInt . BS.words

getInt = readInt <$> BS.getLine
getIntList = readIntList <$> 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

main = do
  [nSw,nLight] <- getIntList
  ss <- getIntNList nLight
  swAllOn <- getIntList
  let swMatrix = map (indexToVec nSw 1 . drop 1) ss
  print . sum . map (f swAllOn swMatrix) $ allSw nSw

indexToVec :: Int -> Int -> [Int] -> [Int]
indexToVec n i [] = take (n-i+1) [0,0..]
indexToVec n i indices@(x:xs)
  | x == i    = (1 : indexToVec n (i+1) xs)
  | otherwise = (0 : indexToVec n (i+1) indices)

f :: [Int] -> [[Int]] -> [Int] -> Int
f ps swMatrix sw
  | ps' == ps = 1
  | otherwise  = 0
  where
    ps' = map (flip mod 2 . sum . zipWith (*) sw) swMatrix

allSw :: Int -> [[Int]]
allSw 0 = [[]]
allSw n = [x:y | x <- [0,1], y <- allSw (n-1)]

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


-- https://github.com/minoki/my-atcoder-solutions
{-# LANGUAGE BangPatterns #-}
import Data.Char (isSpace)
import Data.Int (Int64)
import Data.Bifunctor (first)
import qualified Data.ByteString.Char8 as BS
import qualified Data.Vector.Unboxed as U

-- skipping 3 (U.fromList [0,1,2,3,4,5]) = [0,3]
skipping :: (U.Unbox a) => Int -> U.Vector a -> U.Vector a
skipping !d !v = U.generate ((U.length v + d - 1) `quot` d) $ \i -> v U.! (i * d)

main = do
  n <- readLn
  ss <- U.unfoldrN n (readInt64 . BS.dropWhile isSpace) <$> BS.getLine
  let ts = U.zipWith (+) ss (U.reverse ss)
  print $ maximum $ [ U.maximum $ U.scanl (+) 0 (skipping d $ U.take l ts)
                    | d <- [1..n-2]
                    , let l | (n - 1) `rem` d == 0 = min (n `quot` 2) (n - 1 - d)
                            | otherwise = n - 1 - d
                    ]

readInt64 :: BS.ByteString -> Maybe (Int64, BS.ByteString)
readInt64 s = first fromIntegral <$> BS.readInt s

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


-- https://github.com/minoki/my-atcoder-solutions
{-# LANGUAGE BangPatterns #-}
import Data.Char (isSpace)
import Data.Int (Int64)
import Data.Bifunctor (first)
import qualified Data.ByteString.Char8 as BS
import qualified Data.Vector.Unboxed as U

-- skipping 3 (U.fromList [0,1,2,3,4,5]) = [0,3]
skipping :: (U.Unbox a) => Int -> U.Vector a -> U.Vector a
skipping !d !v = U.generate ((U.length v + d - 1) `quot` d) $ \i -> v U.! (i * d)

main = do
  n <- readLn
  ss <- U.unfoldrN n (readInt64 . BS.dropWhile isSpace) <$> BS.getLine
  let ts = U.zipWith (+) ss (U.reverse ss)
  print $ maximum $ [ U.maximum $ U.scanl (+) 0 (skipping d $ U.take l ts)
                    | d <- [1..n-2]
                    , let l | (n - 1) `rem` d == 0 = max (n `quot` 2) (n - 1 - d)
                            | otherwise = n - 1 - d
                    ]

readInt64 :: BS.ByteString -> Maybe (Int64, BS.ByteString)
readInt64 s = first fromIntegral <$> BS.readInt s


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
    [a, b] <- getIntList
    print $ solve a b

solve a b | a >= 13 = b
          | a >= 6 = b `div` 2
          | otherwise = 0

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 qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T

main :: IO ()
main = do
  (r : d : x0 : _) <- map unsafeSignedDecimal . T.words <$> T.getLine :: IO [Int]
  let
    f x = r * x - d
  mapM_ print . take 10 . tail . iterate f $ x0

unsafeSignedDecimal :: T.Text -> Int
unsafeSignedDecimal s = case T.signed T.decimal s of
  Right (n, _) -> n

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


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

toTuple :: B.ByteString -> (Int, Int)
toTuple bs =
    let
        Just (a, bs') = B.readInt bs
        Just (b, _) = B.readInt $ B.dropWhile isSpace bs'
    in
        (a, b)

main = do
    [n,m] <- map read . words <$> getLine :: IO [Int]
    table <- VUM.replicate (10^5+1) (0 :: Int)
    fts <- replicateM m $ do
        (a,b) <- toTuple <$> B.getLine
        VU.mapM_ (VUM.modify table (+1)) $ VU.fromList [a..b]
    table' <- VU.unsafeFreeze table
    print $ VU.length $ VU.filter (==m) table'

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 #-}
import Data.List
import Data.Char
import qualified Data.ByteString.Char8 as BS
import qualified Data.Vector.Unboxed as U

main = do
  [n,m] <- unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  (ls,rs) <- fmap U.unzip $ U.replicateM m $ do
    [l,r] <- unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
    return (l,r)
  let maxL = U.maximum ls
      minR = U.minimum rs
  print $ max 0 (minR - maxL + 1)


import Control.Monad

main = do
  [n, m] <- map read . words <$> getLine
  xs <- replicateM m (map read . words <$> getLine)
  let x = concat xs
  print $ func x 1 n

func :: [Int] -> Int -> Int -> Int
func [] a b = if (a >= b)
              then b - a + 1
              else 0
func (x:y:xs) a b = func xs na nb
  where
    na =
      if a > x
        then a
        else x
    nb =
      if b < y
        then b
        else y


main=do
    line<-getLine
    let n=head [read x::Int|x<-words line]
    let m=last [read x::Int|x<-words line]
    ctx<-getContents
    let r=[(read (head $words x)::Int,read (last $words x)::Int)|x<- lines ctx]
    let ha=hana r
    let ta=tana r
    if ha<=ta then print (ta-ha+1) else print 0

hana :: [(Int,Int)]->Int
hana [x] = fst x
hana (x:xs) = max (fst x) (hana xs)

tana :: [(Int,Int)]->Int
tana [x] = snd x
tana (x:xs) = min (snd x) (tana xs)


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

main :: IO ()
main = readLine >>= main'
    where
        main' [n, m] = readContents m >>= print . solve n m

solve :: Int -> Int -> [[Int]] -> Int
solve n m = count . check 0 n
    where
        count (l, h) = h - l

        check x y ([l, r] : xs) = check (max x $ l - 1) (min y r) xs
        check x y _ = (x, y)

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


import Control.Monad
import Data.List
main=do
 [n,m]<-map read.words<$>getLine
 a<-map read.words<$>getLine
 cb<-replicateM m ((\x->(x!!1,x!!0)).map read.words<$>getLine)
 (print.sum)(take n (reverse(sort((f n m (reverse(sort cb)))++a))))
  where f n m cb = if n*m<=0 then [] else ((take(snd(head cb))(repeat(fst(head cb))))++(f (n-(snd(head cb))) (m-1) (tail cb)))

Score : 400 points

Problem Statement

You have N cards. On the i-th card, an integer A_i is written.

For each j = 1, 2, ..., M in this order, you will perform the following operation once:

Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j.

Find the maximum possible sum of the integers written on the N cards after the M operations.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i, C_i \leq 10^9

1 \leq B_i \leq N

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N
B_1 C_1
B_2 C_2
\vdots
B_M C_M

Output

Print the maximum possible sum of the integers written on the N cards after the M operations.

Sample Input 1

3 2
5 1 4
2 3
1 5

Sample Output 1

14

By replacing the integer on the second card with 5, the sum of the integers written on the three cards becomes 5 + 5 + 4 = 14, which is the maximum result.

Sample Input 2

10 3
1 8 5 7 100 4 52 33 13 5
3 10
4 30
1 4

Sample Output 2

338

Sample Input 3

3 2
100 100 100
3 99
3 99

Sample Output 3

300

Sample Input 4

11 3
1 1 1 1 1 1 1 1 1 1 1
3 1000000000
4 1000000000
3 1000000000

Sample Output 4

10000000001

The output may not fit into a 32-bit integer type.


import Data.Char

main :: IO ()
main = do
  [n,k] <- map read . words <$> getLine :: IO [Int]
  s <- getLine
  print $ take (k-1) s ++  [toLower (s!!(k-1))] ++ drop k s

Score : 100 points

Problem Statement

You are given a string S of length N consisting of A, B and C, and an integer K which is between 1 and N (inclusive).
Print the string S after lowercasing the K-th character in it.

Constraints

1 ≤ N ≤ 50

1 ≤ K ≤ N

S is a string of length N consisting of A, B and C.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the string S after lowercasing the K-th character in it.

Sample Input 1

3 1
ABC

Sample Output 1

aBC

Sample Input 2

4 3
CABA

Sample Output 2

CAbA


solve s1 s2
 | s1 && s2       = "NA"
 | (not s1) && s2 = "MMYY"
 | s1 && (not s2) = "YYMM"
 | otherwise      = "AMBIGUOUS"

main = do
 s <- getLine
 let s1 = (\x -> (x > 12) || (x == 0)) $ read $ take 2 s
 let s2 = (\x -> (x > 12) || (x == 0)) $ read $ drop 2 s
 putStr $ solve s1 s2

Score : 200 points

Problem Statement

You have a digit sequence S of length 4. You are wondering which of the following formats S is in:

YYMM format: the last two digits of the year and the two-digit representation of the month (example: 01 for January), concatenated in this order

MMYY format: the two-digit representation of the month and the last two digits of the year, concatenated in this order

If S is valid in only YYMM format, print YYMM; if S is valid in only MMYY format, print MMYY; if S is valid in both formats, print AMBIGUOUS; if S is valid in neither format, print NA.

Constraints

S is a digit sequence of length 4.

Input

Input is given from Standard Input in the following format:

S

Output

Print the specified string: YYMM, MMYY, AMBIGUOUS or NA.

Sample Input 1

1905

Sample Output 1

YYMM

May XX19 is a valid date, but 19 is not valid as a month. Thus, this string is only valid in YYMM format.

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

Both December XX01 and January XX12 are valid dates. Thus, this string is valid in both formats.

Sample Input 3

1700

Sample Output 3

NA

Neither 0 nor 17 is valid as a month. Thus, this string is valid in neither format.


main = do
  s <- getLine
  putStrLn $ f s

f :: String -> String
f xs
  | inc (take 2 xs) && inc (drop 2 xs) = "AMBIGUOUS"
  | inc (take 2 xs) = "MMYY"
  | inc (drop 2 xs) = "YYMM"
  | otherwise = "NA"
  where
    inc x = x `elem` ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]


import Control.Applicative

main = do
  s <- getLine
  putStrLn $ case s of
    s
      | isMatchMonth first &&
        isMatchYear first &&
        isMatchMonth second &&
        isMatchYear second -> "AMBIGUOUS"
      | isMatchMonth first &&
        isMatchYear second -> "MMYY"
      | isMatchYear first &&
        isMatchMonth second -> "YYMM"
      | otherwise -> "NA"
      where
        first = read $ take 2 s
        second = read $ drop 2 s

isMatchMonth::Int -> Bool
isMatchMonth x
  | x <= 0 = False
  | x <= 12 = True
  | otherwise = False

isMatchYear::Int -> Bool
isMatchYear x
  | x < 0 = False
  | x <= 99 = True
  | otherwise = False


main = do
  s <- read <$> getLine
  let a = div s 100
  let b = mod s 100
  putStrLn $ func a b

func :: Int -> Int -> String
func a b
  | (a < 1) || (a > 12) = if (b > 0) && (b <= 12)
                             then "YYMM"
                             else "NA"
  | (a > 0) && (a <= 12) = if (b > 0) && (b <= 12)
                             then "AMBIGUOUS"
                             else "MMYY"


--out of memory ???????????
--考え方はあってると思うがコーディングの技量不足
readInt :: String -> Int
readInt = read
x ? (a,b) = if x then a else b
------
main = do
  s <- map readInt.words<$>getLine
  print $ solve s

solve :: [Int] -> Double
solve [n,k] = (sum list)/(f n) where
  list = map (\a -> 1/(f(2^a))) as
  as = map (calc k) [1..n]
  f n = fromIntegral n

calc :: Int -> Int -> Int
calc k i = end?(0, 1 + next) where
  end = i >= k
  next = calc k 2*i

Score : 300 points

Problem Statement

Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them:

Throw the die. The current score is the result of the die.

As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each time the coin lands heads up, and the score becomes 0 if the coin lands tails up.

The game ends when the score becomes 0 or becomes K or above. Snuke wins if the score is K or above, and loses if the score is 0.

You are given N and K. Find the probability that Snuke wins the game.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the probability that Snuke wins the game. The output is considered correct when the absolute or relative error is at most 10^{-9}.

Sample Input 1

3 10

Sample Output 1

0.145833333333

If the die shows 1, Snuke needs to get four consecutive heads from four coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^4 = \frac{1}{48}.

If the die shows 2, Snuke needs to get three consecutive heads from three coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^3 = \frac{1}{24}.

If the die shows 3, Snuke needs to get two consecutive heads from two coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^2 = \frac{1}{12}.

Thus, the probability that Snuke wins is \frac{1}{48} + \frac{1}{24} + \frac{1}{12} = \frac{7}{48} \simeq 0.1458333333.

Sample Input 2

100000 5

Sample Output 2

0.999973749998


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

solve :: Int -> Int -> Double
solve !n !k = (/ fromIntegral n) $ sum (map (\i -> 1 / (2 ^ funcM i)) [1 .. n])
  where funcM i = head $ dropWhile (\t -> i * 2 ^ t < k) [0 ..]

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

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


import Control.Monad
import Data.List

main = do
    n <- readLn
    ss <- replicateM n getLine
    let ab = sum $ map  (length . (filter ("AB" `isPrefixOf`)) . tails) ss
        a = length $ filter ((=='A') . last) ss
        b = length $ filter ((=='B') . head) ss
    print $ ab + min a b

Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


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

readInt = fst . fromJust . BS.readInt
getInt = readInt <$> BS.getLine

x `mydiv` y = if y /= 0 then x `div` y else 0
x `mymod` y = if y /= 0 then x `mod` y else 1

main = do
  n <- getInt

  let solve i res | i*i >     n    = res
                  | n `mod` i == 0 = let m1 = i - 1
                                         q1 = n `mydiv` m1
                                         r1 = n `mymod` m1

                                         m2 = n `div` i - 1
                                         q2 = n `mydiv` m2
                                         r2 = n `mymod` m2

                                         res' = res
                                           + (if q1 == r1 then m1 else 0)
                                           + (if q2 == r2 then m2 else 0)
                                     in solve (i+1) res'
                  | otherwise      = solve (i+1) res

  print $ solve 1 0

Score : 500 points

Problem Statement

Snuke received a positive integer N from Takahashi.
A positive integer m is called a favorite number when the following condition is satisfied:

The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds.

Find all favorite numbers and print the sum of those.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

8

Sample Output 1

10

There are two favorite numbers: 3 and 7. Print the sum of these, 10.

Sample Input 2

1000000000000

Sample Output 2

2499686339916

Watch out for overflow.


{-# LANGUAGE BangPatterns #-}
import Data.Int
import Data.Char
import Data.Bits
import Data.Monoid
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.ByteString.Char8 as BS
import qualified Data.IntMap.Strict as IntMap

modulo = 10^9+7 :: Int64
addMod, subMod, mulMod :: Int64 -> Int64 -> Int64
addMod !x !y = (x + y) `rem` modulo
subMod !x !y = (x - y) `mod` modulo
mulMod !x !y = (x * y) `rem` modulo

newtype N = N { unwrapN :: Int64 } 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

powMod :: Int64 -> Int64 -> Int64 -> Int64
powMod !_ 0 !_ = 1
powMod !a b !modulo = loop a a (b - 1)
  where
    loop :: Int64 -> Int64 -> Int64 -> Int64
    loop !acc !a 0 = acc
    loop !acc !a 1 = (acc * a) `rem` modulo
    loop !acc !a i = case i `quotRem` 2 of
                       (j,0) -> loop acc ((a * a) `rem` modulo) j
                       (j,_) -> loop ((acc * a) `rem` modulo) ((a * a) `rem` modulo) j

main = do
  n <- readLn
  xs <- U.unfoldrN n (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  let ys = U.scanl xor 0 xs
  let z = U.last ys
  if z /= 0
    then let f ys = let (ys0, ys1) = U.span (== 0) ys
                        (ys', ys'') = U.span (/= 0) ys1
                        l = U.length ys0
                        k = U.length $ U.filter (== z) ys'
                    in if U.null ys''
                       then fromIntegral l
                       else (fromIntegral l * fromIntegral k) * f ys'' + 1
         in print (f ys :: N)
    else let f :: U.Vector Int -> (Int, IntMap.IntMap N, IntMap.IntMap N)
             f ys = let (ys0, ys1) = U.span (== 0) ys
                        (ys', ys'') = U.span (/= 0) ys1
                        l = U.length ys0
                    in if U.null ys1
                       then (l, IntMap.empty, IntMap.empty)
                       else let (l0, s, t) = f ys''
                                tx = IntMap.fromListWith (+) [(a, IntMap.findWithDefault 1 a t) | a <- U.toList ys']
                                s' = IntMap.unionWith (+) s tx
                                t' = IntMap.unionWith (+) (fmap (fromIntegral l *) s') $ IntMap.union t tx
                                !l' = l0 + l
                            in (l', s', t')
             !(ll, ss, tt) = f ys
         in print (2 ^ (ll - 2) + getSum (IntMap.foldMapWithKey (\k v -> Sum v) ss) :: N)

Score : 800 points

Problem Statement

The beauty of a sequence a of length n is defined as a_1 \oplus \cdots \oplus a_n, where \oplus denotes the bitwise exclusive or (XOR).

You are given a sequence A of length N.
Snuke will insert zero or more partitions in A to divide it into some number of non-empty contiguous subsequences.

There are 2^{N-1} possible ways to insert partitions.
How many of them divide A into sequences whose beauties are all equal? Find this count modulo 10^{9}+7.

Constraints

All values in input are integers.

1 \leq N \leq 5 \times 10^5

0 \leq A_i < 2^{20}

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_{N}

Output

Print the answer.

Sample Input 1

3
1 2 3

Sample Output 1

3

Four ways of dividing A shown below satisfy the condition. The condition is not satisfied only if A is divided into (1),(2),(3).

(1,2,3)

(1),(2,3)

(1,2),(3)

Sample Input 2

3
1 2 2

Sample Output 2

1

Sample Input 3

32
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Sample Output 3

147483634

Find the count modulo 10^{9}+7.

Sample Input 4

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

Sample Output 4

292


main = do
  [a,b,t] <- map read . words <$> getLine :: IO [Int]
  print $ t `div` a * b

Score : 100 points

Problem Statement

A biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.

Find the total number of biscuits produced within T + 0.5 seconds after activation.

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

Print the total number of biscuits produced within T + 0.5 seconds after activation.

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


module Main where

import           Control.Monad
import           Data.List
import           Data.Ord
import           Data.List.Split
import           Data.Array.IO
import qualified Data.Vector            as V
import           Data.Maybe
import           Text.Printf

main :: IO ()
main = do
  _ <- getLine
  vs <- map read . words <$> getLine
  cs <- map read . words <$> getLine
  print $ (max 0 . f . sortBy (flip compare) . zipWith (-) vs) cs
  where
    f as = sum $ 0:filter (>= 0) as

Score : 200 points

Problem Statement

There are N gems. The value of the i-th gem is V_i.

You will choose some of these gems, possibly all or none, and get them.

However, you need to pay a cost of C_i to get the i-th gem.

Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

N
V_1 V_2 ... V_N
C_1 C_2 ... C_N

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

If we choose the first and third gems, X = 10 + 5 = 15 and Y = 6 + 4 = 10.
We have X-Y = 5 here, which is the maximum possible value.

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


{-# 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
	n <- readInt
	vs <- readInts
	cs <- readInts
	print $ sum $ filter ( 0 < ) $ zipWith (-) vs cs


import Data.Int

solve :: [Int64] -> Int64
solve rest =
    if f_ then s_ else s_ - m_
    where
        func a (s,m,f) =
            (s + a_, min m a_, (0 <= a) == f)
            where
                a_ = abs a
        (s_,m_,f_) = foldr func (0, maxBound,True) rest

main = interact $ show.solve.tail.map read.words

Score : 400 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.

You can perform the following operation on this integer sequence any number of times:

Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.

Let B_1, B_2, ..., B_N be the integer sequence after your operations.

Find the maximum possible value of B_1 + B_2 + ... + B_N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

-10^9 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value of B_1 + B_2 + ... + B_N.

Sample Input 1

3
-10 5 -4

Sample Output 1

19

If we perform the operation as follows:

Choose 1 as i, which changes the sequence to 10, -5, -4.

Choose 2 as i, which changes the sequence to 10, 5, 4.

we have B_1 = 10, B_2 = 5, B_3 = 4. The sum here, B_1 + B_2 + B_3 = 10 + 5 + 4 = 19, is the maximum possible result.

Sample Input 2

5
10 -4 -8 -11 3

Sample Output 2

30

Sample Input 3

11
-1000000000 1000000000 -1000000000 1000000000 -1000000000 0 1000000000 -1000000000 1000000000 -1000000000 1000000000

Sample Output 3

10000000000

The output may not fit into a 32-bit integer type.


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

import Data.Int

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

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

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

main = getLine >> readIntegers >>= print . solve . map fromIntegral

solve as = runST $ do
	let
		n = length as
	dp <- newArray ( ( 0, 0 ), ( n, 1 ) ) ( minBound `div` 2 :: Int64 ) :: ST s ( STUArray s ( Int, Int ) Int64 )
	writeArray dp ( 0, 0 ) 0
	forM_ ( zip [ 0 .. ] as ) $ \( i, a ) -> do
		forM_ [ 0, 1 ] $ \j -> do
			modifyArray dp ( i + 1, 0 ) =<< max . ( + ( if j == 0 then a else -a ) ) <$> readArray dp ( i, j )
			when ( i + 1 < n ) $ do
				modifyArray dp ( i + 1, 1 ) =<< max . ( + ( if j == 0 then -a else a ) ) <$> readArray dp ( i, j )
	readArray dp ( n, 0 )


import Control.Monad

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

Score : 100 points

Problem Statement

There are three houses on a number line: House 1, 2 and 3, with coordinates A, B and C, respectively.
Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Constraints

0\leq A,B,C\leq 100

A, B and C are distinct integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Sample Input 1

3 8 5

Sample Output 1

Yes

We pass the coordinate 5 on the straight way from the house at coordinate 3 to the house at coordinate 8.

Sample Input 2

7 3 1

Sample Output 2

No

Sample Input 3

10 2 4

Sample Output 3

Yes

Sample Input 4

31 41 59

Sample Output 4

No


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


main :: IO ()
main = do
  n <- readLn :: IO Int
  s <- getLine
  k <- readLn :: IO Int

  let c = s!!(k-1)

  putStrLn $ map (\x -> if x==c then x else '*') s

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters, and an integer K.
Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Constraints

1 \leq K \leq N\leq 10

S is a string of length N consisting of lowercase English letters.

N and K are integers.

Input

Input is given from Standard Input in the following format:

N
S
K

Output

Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Sample Input 1

5
error
2

Sample Output 1

*rr*r

The second character of S is r. When we replace every character in error that differs from r with *, we get the string *rr*r.

Sample Input 2

6
eleven
5

Sample Output 2

e*e*e*

Sample Input 3

9
education
7

Sample Output 3

******i**


toInt :: (String -> Int)
toInt x = read x ::Int

main :: IO ()
main = do
  n <- getLine
  s <- getLine
  k <- getLine
  let put_str = (s !! (toInt k))
      after = map (\x -> if x /= put_str then '*' else x) s
  putStrLn after


import Data.List(findIndex)

main = do
    n <- readLn
    s <- getLine
    let cntB = length $ filter (=='#') s
    let cntW = n - cntB
    let resB = case findIndex (=='#') s of
                Nothing -> 0
                Just preW -> cntW - preW
    let resW = case findIndex (=='.') (reverse s) of
                Nothing -> 0
                Just sufB -> cntB - sufB
    print $ min resB resW

Score : 300 points

Problem Statement

There are N stones arranged in a row. Every stone is painted white or black.
A string S represents the color of the stones. The i-th stone from the left is white if the i-th character of S is ., and the stone is black if the character is #.

Takahashi wants to change the colors of some stones to black or white so that there will be no white stone immediately to the right of a black stone.
Find the minimum number of stones that needs to be recolored.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of stones that needs to be recolored.

Sample Input 1

3
#.#

Sample Output 1

1

It is enough to change the color of the first stone to white.

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0