import qualified Data.Vector.Unboxed as V
import Data.Array.IArray (listArray, accumArray, (!))
import Data.Array.MArray
import Data.Array.ST (STUArray, runSTUArray)
import Data.Array.Unboxed (UArray)
import Data.List (sortOn, sortBy, unfoldr, partition)
import Data.Char (isSpace)
import Control.Monad.ST (ST)
import Control.Monad.Trans.State (StateT(..))
import qualified Data.ByteString.Char8 as B

-- utility functions

--   Input functions
readInt = B.readInt . B.dropWhile isSpace

readInts :: Int -> B.ByteString -> [Int]
readInts n = take n . unfoldr readInt

readIntsV :: Int -> B.ByteString -> V.Vector Int
readIntsV n = V.unfoldrN n readInt

readIntsA :: Int -> B.ByteString -> UArray Int Int
readIntsA n bs = runSTUArray $ do
  arr <- newArray_ (0,n-1)
  go arr 0 bs
  return arr
  where
    go :: STUArray s Int Int -> Int -> B.ByteString -> ST s ()
    go arr i bs
      | i==n = return ()
      | otherwise = do
        let Just (x,bs') = readInt bs
        writeArray arr i x
        go arr (i+1) bs'

readTsV :: Int -> B.ByteString -> V.Vector (Int,Int)
readTsV n = V.unfoldrN n $ runStateT ((,) <$> StateT readInt <*> StateT readInt)

readTs :: Int -> B.ByteString -> [(Int,Int)]
readTs n = take n . unfoldr readT where
  readT = runStateT ((,) <$> StateT readInt <*> StateT readInt)

-- main

solv n s
  | null s' = 0
  | otherwise = minimum $ go 0 bnum s'
  where
    s' = reverse . dropWhile (=='.') $ s
    go wn bn [] = [wn]
    go wn bn ('.':xs) = bn + (wn+1) : (go (wn+1) bn xs)
    go wn bn ('#':xs) = (bn-1) + wn : (go wn (bn-1) xs)
    bnum = length . filter (=='#') $ s'

main = do
  n <- read <$> getLine :: IO Int
  s <- getLine
  print $ solv n s


import Data.List
main = do
  [a, b] <- map read . words <$> getLine
  putStrLn . show . sum . take 2 . reverse $ sort [a, b, a-1, b-1]

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

Score : 100 points

Problem Statement

There are two buttons, one of size A and one of size B.

When you press a button of size X, you get X coins and the size of that button decreases by 1.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12

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.


main = do
    [a,b] <- fmap read . words <$> getLine :: IO [Int]
    let x1 = max a b
    if x1 == a
        then print $ x1 + max (a-1) b
        else print $ x1 + max a (b-1)


main = do
  [a,b] <- map read . words <$> getLine
  print $ maximum [a+b,2*a-1,2*b-1]


import Data.List (tails)

main :: IO ()
main = getLine >> readInts >>= print . solve . reverse

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

solve :: [Int] -> Int
solve = length . filter headHighest . init . tails

headHighest :: [Int] -> Bool
headHighest (h:hs) = all (h >=) hs

Score : 200 points

Problem Statement

There are N mountains ranging from east to west, and an ocean to the west.

At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.

The height of the i-th mountain from the west is H_i.

You can certainly see the ocean from the inn at the top of the westmost mountain.

For the inn at the top of the i-th mountain from the west (i = 2, 3, ..., N), you can see the ocean if and only if H_1 \leq H_i, H_2 \leq H_i, ..., and H_{i-1} \leq H_i.

From how many of these N inns can you see the ocean?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq H_i \leq 100

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the number of inns from which you can see the ocean.

Sample Input 1

4
6 5 6 8

Sample Output 1

3

You can see the ocean from the first, third and fourth inns from the west.

Sample Input 2

5
4 5 3 5 4

Sample Output 2

3

Sample Input 3

5
9 5 6 8 4

Sample Output 3

1


{-# LANGUAGE BangPatterns #-}

solve :: [Int] -> Int
solve = f 0  0
  where
    f !m !n []     = n
    f !m !n (x:xs) = if x >= m then f x (n + 1) xs else f m n xs

main = print . solve . map read . words =<< (getLine >> getLine)


main :: IO()
main = do
    s <- getLine
    let b = take (length s) $ cycle ['0', '1']
    let answer' = length . filter (\(x, y) -> x == y) $ zip s b
    let answer = if length b - answer' > answer' then answer' else length b - answer'
    print answer

Score : 300 points

Problem Statement

N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.

The i-th tile from the left is painted black if the i-th character of S is 0, and painted white if that character is 1.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Sample Input 1

000

Sample Output 1

1

The condition can be satisfied by repainting the middle tile white.

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


import Data.Char
main=do
 s<-map digitToInt<$>getLine
 let p=concat$take (length s) (repeat [0,1])
 let q=concat$take (length s) (repeat [1,0])
 print$length$filter(odd)(zipWith (+) s (if head s==0 then p else q))


--{-# LANGUAGE BangPatterns #-}
--{-# LANGUAGE ScopedTypeVariables #-}
--{-# LANGUAGE FlexibleContexts #-}
--{-# LANGUAGE ViewPatterns #-}
--{-# LANGUAGE OverloadedStrings #-}
--{-# LANGUAGE Strict #-}
--{-# LANGUAGE NumericUnderscores #-}
--{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE CPP #-}

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.Strict as MPS
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 Control.Monad.State.Strict
import Debug.Trace
import qualified Data.OrdPSQ as PSQ
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

data OrdQ = Ascending | Descending

---------------------------------------------------------------------------
f :: [(Char,Int)] -> Char -> [(Char,Int)]
f [] c
    | c=='0' = [('0',1)]
    | c=='1' = [('1',1),('0',0)]
f a@((d,cnt):xs) c
    | c==d = (d,cnt+1):xs
    | c/=d = (c,1):a

makeTable :: VU.Vector Char -> VU.Vector Int
makeTable xs = table
    where
        table = VU.scanl' (+) 0 $ VU.fromList $ reverse $ map snd base'
        base = VU.foldl' f [] xs
        base' =
            let (c,_) = head base
            in if c=='0' then base else ('0',0):base

g :: VU.Vector Int -> Int -> Int -> Int
g table k i
    | right+1 <= n = (table VU.! (right+1)) - (table VU.! i)
    | otherwise = (table VU.! right) - (table VU.! i)
    where
        n = VU.length table - 1
        right = 2*(k-1)+1

main = do
    [n,k] <- sLineToIntL
    xs <- VU.fromList <$> str
    let table = makeTable xs
    print table
    print $ maximum [g table k i | i<-[0,2..VU.length table-1]]
--------------------------------------------------------------------------

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

double :: IO Double
double = bsToDouble <$> BC.getLine

str :: IO String
str = BC.unpack <$> BC.getLine

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

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

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

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

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

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

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

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

sLineToDoubleL :: IO [Double]
sLineToDoubleL = fromSLineL bsToDouble

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

m1 :: Int -> Int
m1 = subtract 1

toDouble :: Int -> Double
toDouble = fromIntegral

toInt :: Double -> Int
toInt = floor

sqToList :: SQ.Seq a -> [a]
sqToList sq =
    case SQ.viewl sq of
        l SQ.:< sq' -> l : sqToList sq'
        SQ.EmptyL -> []

sortV :: (Ord a, VU.Unbox a) => VU.Vector a -> VU.Vector a
sortV v = VU.create $ do
    w <- VU.thaw v
    VAM.sort w
    return w

sortVR :: (Ord a, VU.Unbox a) => VU.Vector a -> VU.Vector a
sortVR v = VU.create $ do
    w <- VU.thaw v
    VAM.sortBy (flip compare) w
    return w

buildPQL :: Ord a => OrdQ -> [a] -> PSQ.OrdPSQ Int Int a
buildPQL oq xs =
    case oq of
        Ascending -> f $ zip3 [1..l] [1..l] $ sort xs
        Descending -> f $ zip3  [1..l] (map negate [1..l]) $ sort xs
    where
        l = length xs
        f = foldl' g PSQ.empty
        g acc (k,p,v) = PSQ.insert k p v acc

buildPQV :: (Ord a, VU.Unbox a) => OrdQ -> VU.Vector a -> PSQ.OrdPSQ Int Int a
buildPQV oq xs =
    case oq of
        Ascending -> f $ VU.zip3 (VU.generate l (+1)) (VU.generate l (+1)) $ sortV xs
        Descending -> f $ VU.zip3  (VU.generate l (+1)) (VU.generate l $ negate . (+1)) $ sortV xs
    where
        l = VU.length xs
        f = VU.foldl' g PSQ.empty
        g acc (k,p,v) = PSQ.insert k p v acc

Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


import Control.Monad
import Data.Char
import qualified Data.Sequence as S

main = do
    [n, k] <- map read <$> words <$> getLine
    s      <- getLine
    putStrLn $ show $ solve n k s

solve :: Int -> Int -> String -> Int
solve n k s = doit (S.fromList $ replicate k 0) 0 ('0' : s)
  where
    doit :: (S.Seq Int) -> Int -> String -> Int
    doit start pos []              = n - S.index start 0
    doit start pos ('0' : '1' : t) =                               doit (start S.|> pos) (pos + 1) ('1' : t)
    doit start pos ('1' : '0' : t) = max (pos - S.index start 0) $ doit (S.drop 1 start) (pos + 1) ('0' : t)
    doit start pos ( _        : t) =                               doit  start           (pos + 1) t


import Control.Monad
import Data.Char

main = do
    [n, k] <- map read <$> words <$> getLine
    s      <- getLine
    putStrLn $ show $ solve n k s

solve :: Int -> Int -> String -> Int
solve n k s = doit 1 (replicate (k * 2 + 1) 0) 0 s
  where
    doit d l p []        = length s - head l
    doit 0 l p ('1' : t) = max (p - head l) (doit 1 (l        ++ [p]) (p + 1) t)
    doit 1 l p ('0' : t) = max (p - head l) (doit 0 (drop 2 l ++ [p]) (p + 1) t)
    doit d l p ( _  : t) = doit d l (p + 1) t


import Data.Bool

main = putStrLn . solve . map read . words =<< getContents

solve :: [Int] -> String
solve xs = bool ":(" "Yay!" $ abs(n-m) <= k
    where
        (k:ns) = reverse xs
        n = head ns
        m = last ns

Score: 100 points

Problem Statement

In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively.

Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k.

Determine if there exists a pair of antennas that cannot communicate directly.

Here, assume that the distance between two antennas at coordinates p and q (p < q) is q - p.

Constraints

a, b, c, d, e and k are integers between 0 and 123 (inclusive).

a < b < c < d < e

Input

Input is given from Standard Input in the following format:

a
b
c
d
e
k

Output

Print :( if there exists a pair of antennas that cannot communicate directly, and print Yay! if there is no such pair.

Sample Input 1

1
2
4
8
9
15

Sample Output 1

Yay!

In this case, there is no pair of antennas that cannot communicate directly, because:

the distance between A and B is 2 - 1 = 1

the distance between A and C is 4 - 1 = 3

the distance between A and D is 8 - 1 = 7

the distance between A and E is 9 - 1 = 8

the distance between B and C is 4 - 2 = 2

the distance between B and D is 8 - 2 = 6

the distance between B and E is 9 - 2 = 7

the distance between C and D is 8 - 4 = 4

the distance between C and E is 9 - 4 = 5

the distance between D and E is 9 - 8 = 1

and none of them is greater than 15. Thus, the correct output is Yay!.

Sample Input 2

15
18
26
35
36
18

Sample Output 2

:(

In this case, the distance between antennas A and D is 35 - 15 = 20 and exceeds 18, so they cannot communicate directly.
Thus, the correct output is :(.


module Main (main) where

import Control.Monad
import qualified Data.ByteString.Char8 as C8
import Data.Bool
import Data.Maybe

main :: IO ()
main =
  replicateM 6 readInts >>= print . showAnswer . solve . concat

type Input  = [Int]
type Output = Bool

solve :: Input -> Output
solve [a,b,c,d,e,k] = all ((==k).abs) $ zipWith (-) xs (tail xs)
  where
    xs = [a,b,c,d,e]

showAnswer :: Output -> Answer
showAnswer = String . bool "Yay!" ":("

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

data Answer
  = YesNo Bool
  | YESNO Bool
  | AB Bool
  | Number Int
  | String String
  | Compare Ordering
  | Compare2 Ordering

instance Show Answer where
  show (YesNo b)    = bool "No" "Yes"  b
  show (YESNO b)    = bool "NO" "YES"  b
  show (AB b)       = bool "B"  "A"    b
  show (Number i)   = show i
  show (String s)   = s
  show (Compare o)  = ordering "<" "=" ">" o
  show (Compare2 o) = ordering "Right" "Balanced" "Left" o

ordering :: a -> a -> a -> Ordering -> a
ordering lt eq gt o = case o of
  LT -> lt
  EQ -> eq
  GT -> gt


main = do
       xs<-getContents
       let ys=map read (lines xs)::[Int]
           e=last $ take 5 ys
           a=head ys
           d=last ys
       putStrLn$ if (e-a)<=d then "Yay!" else ":("


import Control.Monad
import Data.List

solve :: [Int] -> Int
solve (x:xs) = x + sum (map conv xs)
  where conv x = 10 * ceiling (fromIntegral x / 10)

compareItems :: Int -> Int -> Ordering
compareItems i1 i2
  | c1 == c2 = EQ
  | c1 < c2 = LT
  | otherwise = GT
  where conv x = if x `mod` 10 == 0 then 10 else x `mod` 10
        c1 = conv i1
        c2 = conv i2

main :: IO ()
main = do
  items <- replicateM 5 readLn
  print . solve $ sortBy compareItems items

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes A minutes to serve.

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

ATC Hanbagu (hamburger patty): takes E minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time 0.

Constraints

A, B, C, D and E are integers between 1 and 123 (inclusive).

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time 0, which will be delivered at time 29.

Order ARC Curry at time 30, which will be delivered at time 50.

Order AGC Pasta at time 50, which will be delivered at time 57.

Order ATC Hanbagu at time 60, which will be delivered at time 180.

Order APC Ramen at time 180, which will be delivered at time 215.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time 0, which will be delivered at time 119.

Order ARC Curry at time 120, which will be delivered at time 206.

Order ATC Hanbagu at time 210, which will be delivered at time 267.

Order APC Ramen at time 270, which will be delivered at time 378.

Order ABC Don at time 380, which will be delivered at time 481.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


main=do
 (a:l)<-map read.lines<$>getContents
 print$4+(div a (minimum l)+(if mod a (minimum l)==0 then 0 else 1))

Score: 300 points

Problem Statement

In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!

There are five means of transport in this empire:

Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.

Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.

Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.

Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.

Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.

For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).

There is a group of N people at City 1, and they all want to go to City 6.

At least how long does it take for all of them to reach there?
You can ignore the time needed to transfer.

Constraints

1 \leq N, A, B, C, D, E \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

Print the minimum time required for all of the people to reach City 6, in minutes.

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

One possible way to travel is as follows.
First, there are N = 5 people at City 1, as shown in the following image:

In the first minute, three people travels from City 1 to City 2 by train. Note that a train can only occupy at most three people.

In the second minute, the remaining two people travels from City 1 to City 2 by train, and two of the three people who were already at City 2 travels to City 3 by bus. Note that a bus can only occupy at most two people.

In the third minute, two people travels from City 2 to City 3 by train, and another two people travels from City 3 to City 4 by taxi.

From then on, if they continue traveling without stopping until they reach City 6, all of them can reach there in seven minutes.

There is no way for them to reach City 6 in 6 minutes or less.

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

All kinds of vehicles can occupy N = 10 people at a time.
Thus, if they continue traveling without stopping until they reach City 6, all of them can reach there in five minutes.

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

Note that the input or output may not fit into a 32-bit integer type.


module Main where

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

  main :: IO ()
  main = do
    n <- readLn :: IO Int64
    as <- replicateM 5 readLn :: IO [Int64]
    let m = minimum as :: Int64
        (d,md) = n `divMod` m
        a = 5 + (d - 1) + (if md == 0 then 0 else 1) :: Int64
    print a


module Main where

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

main :: IO ()
main = do
  [x,y,z,k] <- map read . words <$> getLine
  [as, bs, cs] <- replicateM 3 $ map read . words <$> getLine

  let ab  = take k . sortOn Down $ [a + b | a <- as, b <- bs]
      abc = take k . sortOn Down $ [a + c | a <- ab, c <- cs]
  mapM_ print abc

Score: 400 points

Problem Statement

The Patisserie AtCoder sells cakes with number-shaped candles.
There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively.
Each cake has an integer value called deliciousness, as follows:

The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X.

The deliciousness of the cakes with 2-shaped candles are B_1, B_2, ..., B_Y.

The deliciousness of the cakes with 3-shaped candles are C_1, C_2, ..., C_Z.

Takahashi decides to buy three cakes, one for each of the three shapes of the candles, to celebrate ABC 123.

There are X \times Y \times Z such ways to choose three cakes.

We will arrange these X \times Y \times Z ways in descending order of the sum of the deliciousness of the cakes.

Print the sums of the deliciousness of the cakes for the first, second, ..., K-th ways in this list.

Constraints

1 \leq X \leq 1 \ 000

1 \leq Y \leq 1 \ 000

1 \leq Z \leq 1 \ 000

1 \leq K \leq \min(3 \ 000, X \times Y \times Z)

1 \leq A_i \leq 10 \ 000 \ 000 \ 000

1 \leq B_i \leq 10 \ 000 \ 000 \ 000

1 \leq C_i \leq 10 \ 000 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y Z K
A_1 \ A_2 \ A_3 \ ... \ A_X
B_1 \ B_2 \ B_3 \ ... \ B_Y
C_1 \ C_2 \ C_3 \ ... \ C_Z

Output

Print K lines. The i-th line should contain the i-th value stated in the problem statement.

Sample Input 1

2 2 2 8
4 6
1 5
3 8

Sample Output 1

19
17
15
14
13
12
10
8

There are 2 \times 2 \times 2 = 8 ways to choose three cakes, as shown below in descending order of the sum of the deliciousness of the cakes:

(A_2, B_2, C_2): 6 + 5 + 8 = 19

(A_1, B_2, C_2): 4 + 5 + 8 = 17

(A_2, B_1, C_2): 6 + 1 + 8 = 15

(A_2, B_2, C_1): 6 + 5 + 3 = 14

(A_1, B_1, C_2): 4 + 1 + 8 = 13

(A_1, B_2, C_1): 4 + 5 + 3 = 12

(A_2, B_1, C_1): 6 + 1 + 3 = 10

(A_1, B_1, C_1): 4 + 1 + 3 = 8

Sample Input 2

3 3 3 5
1 10 100
2 20 200
1 10 100

Sample Output 2

400
310
310
301
301

There may be multiple combinations of cakes with the same sum of the deliciousness. For example, in this test case, the sum of A_1, B_3, C_3 and the sum of A_3, B_3, C_1 are both 301.
However, they are different ways of choosing cakes, so 301 occurs twice in the output.

Sample Input 3

10 10 10 20
7467038376 5724769290 292794712 2843504496 3381970101 8402252870 249131806 6310293640 6690322794 6082257488
1873977926 2576529623 1144842195 1379118507 6003234687 4925540914 3902539811 3326692703 484657758 2877436338
4975681328 8974383988 2882263257 7690203955 514305523 6679823484 4263279310 585966808 3752282379 620585736

Sample Output 3

23379871545
22444657051
22302177772
22095691512
21667941469
21366963278
21287912315
21279176669
21160477018
21085311041
21059876163
21017997739
20703329561
20702387965
20590247696
20383761436
20343962175
20254073196
20210218542
20150096547

Note that the input or output may not fit into a 32-bit integer type.


import Data.List

main = do
  [x,y,z,k] <- map read.words<$>getLine
  as <- map read.words<$>getLine
  bs <- map read.words<$>getLine
  cs <- map read.words<$>getLine
  putStr $ solve x y z k as bs cs

solve x y z k as' bs' cs' = unlines.map show$take k ans
  where
  ans = sortBy (flip compare)
    [ as!!(a-1) + bs!!(b-1) + cs!!(c-1)
    | a <- [1..min k x]
    , b <- [1..min (div k a) y]
    , c <- [1..min (div k (a*b)) z] ]
  [as,bs,cs] = map (sortBy $ flip compare) [as',bs',cs']


{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
import Control.Monad
import Data.Int (Int64)
import Data.List
import qualified Data.Vector.Unboxed as U
import qualified Data.ByteString.Char8 as BS
import Data.Ord
import Data.Coerce

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

mergeTwo :: [(Int64, Int)] -> [(Int64, Int)] -> [(Int64, Int)]
mergeTwo xs@(x@(xv,xn):xss) ys@(y@(yv,yn):yss) = case compare xv yv of
  LT -> y : mergeTwo xs yss
  EQ -> let !zn = xn + yn in (xv, zn) : mergeTwo xss yss
  GT -> x : mergeTwo xss ys
mergeTwo [] ys = ys
mergeTwo xs [] = xs

-- replicate' n x ys = replicate n x ++ ys
replicate' :: Int -> a -> [a] -> [a]
replicate' 0 x ys = ys
replicate' n x ys = x : replicate' (n - 1) x ys

undup :: [(Int64, Int)] -> [Int64]
undup ((xv,xn):xs) = replicate' xn xv $ undup xs
undup [] = []

mergeLists :: [[(Int64, Int)]] -> [(Int64, Int)]
mergeLists [] = []
mergeLists (xs:sss) = doMerge' xs sss
  where
    doMerge' xs (ys:sss) = doMerge xs ys sss
    doMerge' xs [] = xs
    doMerge xs (y:yss) sss = innerLoop xs y yss sss
      where innerLoop xs@(x@(xv,xn):xss) !y@(!yv,!yn) yss sss = case compare xv yv of
              LT -> y : doMerge' (mergeTwo xs yss) sss
              EQ -> let !zn = xn + yn in (xv, zn) : doMerge' (mergeTwo xss yss) sss
              GT -> x : innerLoop xss y yss sss
            innerLoop [] !y yss sss = y : doMerge' yss sss
    doMerge [] ys [] = ys
    doMerge [] ys (zs:sss) = doMerge ys zs sss
    doMerge xs [] (ys:sss) = doMerge xs ys sss
    doMerge xs [] [] = xs

mergeDup :: [Int64] -> [(Int64, Int)]
mergeDup (x:xs) = loop 1 x xs
  where loop !i !x ys@(y:yss) | x == y = loop (i+1) x yss
                              | otherwise = (x,i) : mergeDup ys
        loop !i !x [] = [(x,i)]
mergeDup [] = []

mergeDup2 :: [(Int64, Int)] -> [(Int64, Int)]
mergeDup2 ((x,n):xs) = loop n x xs
  where loop !i !x ys@((y,m):yss) | x == y = loop (i+m) x yss
                                  | otherwise = (x,i) : mergeDup2 ys
        loop !i !x [] = [(x,i)]
mergeDup2 [] = []

sumList :: U.Vector (Int64, Int) -> U.Vector (Int64, Int) -> [(Int64, Int)]
sumList as bs = let !n = U.length as
                    !m = U.length bs
                in mergeLists
                   [ mergeDup2 $ sortDown
                     [ (s, nn)
                     | i <- [max 0 (t-m+1) .. min t (n - 1)]
                     , let !j = t - i
                           (a,an) = as U.! i
                           (b,bn) = bs U.! j
                           !s = a + b
                           !nn = an * bn
                     -- i + j = t
                     ]
                   | t <- [0 .. n + m - 2]
                   ]

main = do
  [x,y,z,k] :: [Int] <- map (read . BS.unpack) . BS.words <$> BS.getLine
  -- x,y,z <= 1000
  -- k <= min 3000 (x*y*z)
  as :: U.Vector (Int64, Int) <- U.fromListN x . mergeDup . sortDown . map (read . BS.unpack) . BS.words <$> BS.getLine
  bs :: U.Vector (Int64, Int) <- U.fromListN y . mergeDup . sortDown . map (read . BS.unpack) . BS.words <$> BS.getLine
  cs :: U.Vector (Int64, Int) <- U.fromListN z . mergeDup . sortDown . map (read . BS.unpack) . BS.words <$> BS.getLine
  -- ai,bi,ci <= 10^10, length as == x, length bs == y, length cs == z
  let a_and_b = U.fromListN (min (U.length as * U.length bs) k) $ take k $ sumList as bs
      result = take k $ undup $ sumList a_and_b cs
  mapM_ print result


{-# 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
	s <- getLine
	let
		r = length $ filter ( == 'R' ) s
		b = n - r
	putStrLn $ which "Yes" "No" $ r > b

Score : 200 points

Problem Statement

There are N people numbered 1 to N. Each person wears a red hat or a blue hat.

You are given a string s representing the colors of the people. Person i wears a red hat if s_i is R, and a blue hat if s_i is B.

Determine if there are more people wearing a red hat than people wearing a blue hat.

Constraints

1 \leq N \leq 100

|s| = N

s_i is R or B.

Input

Input is given from Standard Input in the following format:

N
s

Output

If there are more people wearing a red hat than there are people wearing a blue hat, print Yes; otherwise, print No.

Sample Input 1

4
RRBR

Sample Output 1

Yes

There are three people wearing a red hat, and one person wearing a blue hat.

Since there are more people wearing a red hat than people wearing a blue hat, the answer is Yes.

Sample Input 2

4
BRBR

Sample Output 2

No

There are two people wearing a red hat, and two people wearing a blue hat.

Since there are as many people wearing a red hat as people wearing a blue hat, the answer is No.


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

solve :: Int -> Int -> B.ByteString -> VU.Vector (Char, Char) -> Int
solve !n !q !s !tds = (\(l, r) -> r - l - 1) $ simulate
 where
  goRight t k = if k < n - 1 && t == B.index s (k + 1) then k + 1 else k
  goLeft t k = if k > 0 && t == B.index s (k - 1) then k - 1 else k

  simulate = VU.foldr'
    (\(!t, !d) (!l, !r) ->
      if d == 'L' then (goRight t l, r) else (l, goLeft t r)
    )
    (-1, n)
    tds

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

  (n, q) <-
    (\vec -> (vec VU.! 0, vec VU.! 1)) . VU.unfoldrN 2 readInt <$> B.getLine
  s   <- B.getLine
  tds <-
    VU.replicateM q
    $   ((\[x, y] -> (B.head x, B.head y)) . B.words)
    <$> B.getLine
  print $ solve n q s tds

Score : 500 points

Problem Statement

There are N squares numbered 1 to N from left to right.
Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.

Snuke cast Q spells to move the golems.

The i-th spell consisted of two characters t_i and d_i, where d_i is L or R.
When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is L, and moved to the square adjacent to the right if d_i is R.

However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.

Find the number of golems remaining after Snuke cast the Q spells.

Constraints

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

|s| = N

s_i and t_i are uppercase English letters.

d_i is L or R.

Input

Input is given from Standard Input in the following format:

N Q
s
t_1 d_1
\vdots
t_{Q} d_Q

Output

Print the answer.

Sample Input 1

3 4
ABC
A L
B L
B R
A R

Sample Output 1

2

Initially, there is one golem on each square.

In the first spell, the golem on Square 1 tries to move left and disappears.

In the second spell, the golem on Square 2 moves left.

In the third spell, no golem moves.

In the fourth spell, the golem on Square 1 moves right.

After the four spells are cast, there is one golem on Square 2 and one golem on Square 3, for a total of two golems remaining.

Sample Input 2

8 3
AABCBDBA
A L
B R
A R

Sample Output 2

5

After the three spells are cast, there is one golem on Square 2, two golems on Square 4 and two golems on Square 6, for a total of five golems remaining.

Note that a single spell may move multiple golems.

Sample Input 3

10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L

Sample Output 3

3


{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Data.Maybe
import Debug.Trace
import Data.List
import qualified Data.Map.Strict as Map
import qualified Data.IntMap.Strict as IntMap
import qualified Data.Set as Set
import qualified Data.IntSet as IntSet
import Data.Functor
import Data.Array
-- import Data.Array.Unboxed
import Control.Monad.ST
import Data.Array.ST

main :: IO ()
main = do
  (n:q:_) <- map read . words <$> getLine :: IO [Int]
  s <- getLine :: IO String
  tds <- replicateM q $ (\(a:b:_) -> (head a, head b)) . words <$> getLine :: IO [(Char, Char)]
  print $ solve n s tds

solve n s tds = rbound - lbound - 1
  where
    rbound = if vanishRight n
             then lowerBound vanishRight (1, n)
             else n + 1
    lbound = if vanishLeft 1
             then upperBound vanishLeft (1, n)
             else n - 1

    sarr = listArray (1, n) s
    vanishRight i = go i tds
      where
        go :: Int -> [(Char, Char)] -> Bool
        go i tds
          | i > n = True
          | i < 1 = False
          | null tds = False
          | otherwise = if sarr ! i == t
                        then if d == 'R'
                            then go (i+1) $ tail tds
                            else go (i-1) $ tail tds
                        else go i $ tail tds
            where (t, d) = head tds

    vanishLeft i = go i tds
      where
        go :: Int -> [(Char, Char)] -> Bool
        go i tds
          | i < 1 = True
          | i > n = False
          | null tds = False
          | otherwise = if sarr ! i == t
                        then if d == 'R'
                            then go (i+1) $ tail tds
                            else go (i-1) $ tail tds
                        else go i $ tail tds
            where (t, d) = head tds

lowerBound :: (Int -> Bool) -> (Int, Int) -> Int
lowerBound predicate bounds = go bounds
  where
    go (l, h) | l + 1 == h = h
              | predicate m = go (l, m)
              | otherwise = go (m, h)
      where m = (l + h) `div` 2

upperBound :: (Int -> Bool) -> (Int, Int) -> Int
upperBound predicate bounds = go bounds
  where
    go (l, h) | l + 1 == h = l
              | predicate m = go (m, h)
              | otherwise = go (l, m)
      where m = (l + h) `div` 2


-- https://github.com/minoki/my-atcoder-solutions
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}
import Control.Monad
import Data.Char (isSpace)
import Data.Int (Int64)
import Data.List
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import qualified Data.ByteString.Char8 as BS
import Control.Monad.ST
import Data.Array.ST
import Control.Monad.Reader
--
import Data.Coerce
import qualified Data.Vector.Generic
import qualified Data.Vector.Generic.Mutable
import qualified Data.Array.Base
import qualified Unsafe.Coerce

type Memo s a = ReaderT (STUArray s (Int,Int) N) (ST s) a

runMemo :: Int -> Int -> (forall s. Memo s a) -> a
runMemo x n action = runST $ do
  arr <- newArray ((0,0),(x,n)) invalidN
  runReaderT action arr

solve :: Int -> Int -> [Int] -> N -> Memo s N
solve !x 0 [] !c = pure $ c * fromIntegral x
solve !x !n ss !c = do
  arr <- ask
  val <- lift $ readArray arr (x,n)
  if val == invalidN
    then do val <- doCalc x n ss
            lift $ writeArray arr (x,n) val
            return $ c * val
    else return $ c * val
  where
    doCalc !x !n ss = case span (> x) ss of
      (ss0,[]) -> pure $ factV U.! n * fromIntegral x
      (ss0,ss1) -> do
        let !m = length ss0
            !q = factV U.! n / factV U.! (n-m)
        s <- sumM [ solve (x `rem` t) (n - k - 1) ts (factV U.! (n-m-1) / factV U.! (n-k-1))
                  | (k, t:ts) <- zip [m..] $ tails ss1
                    -- k + length ts + 1 == n
                    -- k : t より大きいやつ
                  ]
        return (q * s)
-- n == length ss

main = do
  [n,x] <- unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  -- n <= 200, x <= 10^5
  ss <- U.toList . mergeSortBy (\x y -> compare y x) . U.unfoldrN n (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  -- si <= 10^5
  print $ runMemo x n $ solve x n ss 1

factV :: U.Vector N
factV = U.scanl' (*) 1 (U.enumFromN 1 200)

sumM :: (Monad m, Num a) => [m a] -> m a
sumM = foldM (\s a -> (s +) <$> a) 0

---

modulo :: Int64
modulo = 10^9+7
addMod, subMod, mulMod :: Int64 -> Int64 -> Int64
addMod !x !y | x + y >= modulo = x + y - modulo
             | otherwise = x + y
subMod !x !y | x >= y = x - y
             | otherwise = x - y + 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
  (+) = coerce addMod
  (-) = coerce subMod
  (*) = coerce mulMod
  fromInteger n = N (fromInteger (n `mod` fromIntegral modulo))
  abs = undefined; signum = undefined

invalidN :: N
invalidN = N (-1)

{-# RULES
"^9/Int" forall x. x ^ (9 :: Int) = let u = x; v = u * u * u in v * v * v
"^9/Integer" forall x. x ^ (9 :: Integer) = let u = x; v = u * u * u in v * v * v
 #-}

---

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

recipM :: Int64 -> Int64
recipM !x = case exEuclid x modulo of
             (1,a,_) -> a `mod` modulo
             (-1,a,_) -> (-a) `mod` modulo
divM :: Int64 -> Int64 -> Int64
divM !x !y = x `mulMod` recipM y

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

---

mergeSortBy :: (U.Unbox a) => (a -> a -> Ordering) -> U.Vector a -> U.Vector a
mergeSortBy !cmp !vec = doSort vec
  where
    doSort vec | U.length vec <= 1 = vec
               | otherwise = let (xs, ys) = U.splitAt (U.length vec `quot` 2) vec
                             in merge (doSort xs) (doSort ys)
    merge xs ys = U.create $ do
      let !n = U.length xs
          !m = U.length ys
      result <- UM.new (n + m)
      let loop !i !j
            | i == n = U.copy (UM.drop (i + j) result) (U.drop j ys)
            | j == m = U.copy (UM.drop (i + j) result) (U.drop i xs)
            | otherwise = let !x = xs U.! i
                              !y = ys U.! j
                          in case cmp x y of
                               LT -> do UM.write result (i + j) x
                                        loop (i + 1) j
                               EQ -> do UM.write result (i + j) x
                                        UM.write result (i + j + 1) y
                                        loop (i + 1) (j + 1)
                               GT -> do UM.write result (i + j) y
                                        loop i (j + 1)
      loop 0 0
      return result

---

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

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

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

instance U.Unbox N

--- STUArray s i N

unsafeCoerce_STUArray_N_Int :: STUArray s i N -> STUArray s i Int64
unsafeCoerce_STUArray_N_Int = Unsafe.Coerce.unsafeCoerce
unsafeCoerce_STUArray_Int_N :: STUArray s i Int64 -> STUArray s i N
unsafeCoerce_STUArray_Int_N = Unsafe.Coerce.unsafeCoerce

instance Data.Array.Base.MArray (STUArray s) N (ST s) where
  getBounds arr = Data.Array.Base.getBounds (unsafeCoerce_STUArray_N_Int arr)
  getNumElements arr = Data.Array.Base.getNumElements (unsafeCoerce_STUArray_N_Int arr)
  newArray lu e = unsafeCoerce_STUArray_Int_N <$> Data.Array.Base.newArray lu (coerce e)
  newArray_ lu = unsafeCoerce_STUArray_Int_N <$> Data.Array.Base.newArray_ lu
  unsafeNewArray_ lu = unsafeCoerce_STUArray_Int_N <$> Data.Array.Base.unsafeNewArray_ lu
  unsafeRead arr i = coerce <$> Data.Array.Base.unsafeRead (unsafeCoerce_STUArray_N_Int arr) i
  unsafeWrite arr i e = Data.Array.Base.unsafeWrite (unsafeCoerce_STUArray_N_Int arr) i (coerce e)

Score : 600 points

Problem Statement

Snuke has a blackboard and a set S consisting of N integers.
The i-th element in S is S_i.

He wrote an integer X on the blackboard, then performed the following operation N times:

Choose one element from S and remove it.

Let x be the number written on the blackboard now, and y be the integer removed from S. Replace the number on the blackboard with x \bmod {y}.

There are N! possible orders in which the elements are removed from S.
For each of them, find the number that would be written on the blackboard after the N operations, and compute the sum of all those N! numbers modulo 10^{9}+7.

Constraints

All values in input are integers.

1 \leq N \leq 200

1 \leq S_i, X \leq 10^{5}

S_i are pairwise distinct.

Input

Input is given from Standard Input in the following format:

N X
S_1 S_2 \ldots S_{N}

Output

Print the answer.

Sample Input 1

2 19
3 7

Sample Output 1

3

There are two possible orders in which we remove the numbers from S.

If we remove 3 and 7 in this order, the number on the blackboard changes as follows: 19 \rightarrow 1 \rightarrow 1.

If we remove 7 and 3 in this order, the number on the blackboard changes as follows: 19 \rightarrow 5 \rightarrow 2.

The output should be the sum of these: 3.

Sample Input 2

5 82
22 11 6 5 13

Sample Output 2

288

Sample Input 3

10 100000
50000 50001 50002 50003 50004 50005 50006 50007 50008 50009

Sample Output 3

279669259

Be sure to compute the sum modulo 10^{9}+7.


{-# LANGUAGE TypeFamilies, BangPatterns, FlexibleContexts #-}
import Data.Array
import Data.Array.Unboxed
import Data.Array.IO
import Data.Array.Unsafe
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import qualified Data.Vector.Unboxed as U
import Data.Int
import Control.Monad.State.Strict
import qualified Data.ByteString.Char8 as B
import Data.ByteString(ByteString)
import Data.Char

type Scanner a = StateT ByteString IO a
type family Freeze a where
  Freeze (IOUArray i v) = UArray i v
  Freeze (IOArray i v) = Array i v

foldM :: Monad m => (b -> a -> m b) -> b -> [a] -> m b
foldM f z0 xs = foldr c return xs z0
    where c x k = \z -> f z x >>= k
          {-# INLINE c #-}

scan :: Read a => Scanner a
scan = state $ \s ->
    let (s1, s2) = B.span (not . isSpace) s
        !v = read (B.unpack s1)
    in (v, B.dropWhile isSpace s2)

scanInt :: Scanner Int
scanInt = scan

scanString :: Scanner B.ByteString
scanString = state $ \s ->
    let (s1, s2) = B.span (not . isSpace) s in
    (s1, B.dropWhile isSpace s2)

scanReal :: Scanner Double
scanReal = scan

newtype M = M Int
    deriving Show

modulo = 1000000007

instance Num M where
    M a + M b = M $ (a + b) `mod` modulo
    M a - M b = M $ (a - b) `mod` modulo
    M a * M b = M $ (a * b) `mod` modulo
    fromInteger x = M $ fromInteger x `mod` modulo
    abs = id
    signum _ = M 1

instance Fractional M where
    recip (M x) = M (recipM x modulo)

data EGCD = EGCD !Int !Int !Int

{-# NOINLINE recipM #-}
recipM :: Int -> Int -> Int
recipM x m | g /= 1 = error $ "No inverse for " ++ show x ++ " % " ++ show m
           | s <  0 = s + m
           | otherwise = s
    where
    EGCD s _ g = extgcd x m

extgcd :: Int -> Int -> EGCD
extgcd = go
    where
    go a 0 = EGCD 1 0 a
    go a b = EGCD t (s - q * t) g
        where
        (q, r) = quotRem a b
        EGCD s t g = go b r

main :: IO ()
main = B.getContents >>= \content -> flip evalStateT content $ do
    vB <- scanInt
    vW <- scanInt
    liftIO $ solve vB vW

solve :: Int -> Int -> IO ()
solve vB vW = do
    let n = vB + vW
    let factTbl = U.unfoldrN (n + 1) factGen (1,1)
        factGen :: (M, Int) -> Maybe (Int, (M, Int))
        factGen (M m, i) = Just (m, (M m * M i, i + 1))
        fact :: Int -> M
        fact n = M (factTbl U.! n )
        comb :: Int -> Int -> M
        comb x y = fact x / (fact y * fact (x - y))
    let go !i !p !q = when (i < n) $ do
            let M z = p + (1 / 2) * ( 1 - p - q)
                p' | i + 1 < vW = 0
                   | otherwise = p + (1 / 2)^(i + 1) * comb i (vW-1)
                q' | i + 1 < vB = 0
                   | otherwise = q + (1 / 2)^(i + 1) * comb i (vB-1)
            print z
            go (i + 1) p' q'
    go 0 0 0

Score : 700 points

Problem Statement

Today, Snuke will eat B pieces of black chocolate and W pieces of white chocolate for an afternoon snack.

He will repeat the following procedure until there is no piece left:

Choose black or white with equal probability, and eat a piece of that color if it exists.

For each integer i from 1 to B+W (inclusive), find the probability that the color of the i-th piece to be eaten is black.
It can be shown that these probabilities are rational, and we ask you to print them modulo 10^9 + 7, as described in Notes.

Notes

When you print a rational number, first write it as a fraction \frac{y}{x}, where x, y are integers and x is not divisible by 10^9 + 7
(under the constraints of the problem, such representation is always possible).
Then, you need to print the only integer z between 0 and 10^9 + 6, inclusive, that satisfies xz \equiv y \pmod{10^9 + 7}.

Constraints

All values in input are integers.

1 \leq B,W \leq 10^{5}

Input

Input is given from Standard Input in the following format:

B W

Output

Print the answers in B+W lines. In the i-th line, print the probability that the color of the i-th piece to be eaten is black, modulo 10^{9}+7.

Sample Input 1

2 1

Sample Output 1

500000004
750000006
750000006

There are three possible orders in which Snuke eats the pieces:

white, black, black

black, white, black

black, black, white

with probabilities \frac{1}{2}, \frac{1}{4}, \frac{1}{4}, respectively. Thus, the probabilities of eating a black piece first, second and third are \frac{1}{2},\frac{3}{4} and \frac{3}{4}, respectively.

Sample Input 2

3 2

Sample Output 2

500000004
500000004
625000005
187500002
187500002

They are \frac{1}{2},\frac{1}{2},\frac{5}{8},\frac{11}{16} and \frac{11}{16}, respectively.

Sample Input 3

6 9

Sample Output 3

500000004
500000004
500000004
500000004
500000004
500000004
929687507
218750002
224609377
303710940
633300786
694091802
172485353
411682132
411682132


{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Data.Int
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import qualified Data.ByteString.Char8 as BS
import Data.Array.IO

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

modulo = 10^9+7 :: Int64
addMod, subMod, mulMod, divM :: Int64 -> Int64 -> Int64
addMod x y = (x + y) `rem` modulo
subMod x y = (x - y) `mod` modulo
mulMod x y = (x * y) `rem` modulo
recipM :: Int64 -> Int64
recipM x = case exEuclid x modulo of
             (1,a,_) -> a `mod` modulo
             (-1,a,_) -> (-a) `mod` modulo
divM x y = x `mulMod` recipM y

newtype N = N Int64 deriving (Eq, Show)
instance Num N where
  N x + N y = N ((x + y) `rem` modulo)
  N x - N y = N ((x - y) `mod` modulo)
  N x * N y = N ((x * y) `rem` modulo)
  fromInteger n = N (fromInteger (n `mod` fromIntegral modulo))
  abs = undefined; signum = undefined

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

main = do
  [b,w] <- map (read . BS.unpack) . BS.words <$> BS.getLine
  let half = 1 / 2 :: N
  arr <- newArray ((0,0),(b+1,w+1)) 0 :: IO (IOUArray (Int,Int) Int64)
  writeArray arr (b,w) 1
  vec <- UM.new (b+w) :: IO (UM.IOVector Int64)
  forM_ [b+w-1,b+w-2..0] $ \i -> do
    forM_ [max 0 (i - w)..min b i] $ \j -> do
      let k = i - j
      -- j + k == i
      -- 0 <= j <= b, 0 <= k <= w
      u <- readArray arr (j+1,k)
      v <- readArray arr (j,k+1)
      let N uu | k == 0 = N u
               | otherwise = half * N u
      let N vv | j == 0 = N v
               | otherwise = half * N v
      UM.modify vec (`addMod` uu) i
      writeArray arr (j,k) (uu `addMod` vv)
  {-
  forM_ [0..b] $ \j -> do
    r <- forM [0..w] $ \k -> readArray arr (j,k)
    print r
  -}
  forM_ [b+w-1,b+w-2..0] $ \i -> do
    print =<< UM.read vec i


{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Data.Int
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import qualified Data.ByteString.Char8 as BS
import Data.Array.IO

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

modulo = 10^9+7 :: Int64
addMod, subMod, mulMod, divM :: Int64 -> Int64 -> Int64
addMod x y = (x + y) `rem` modulo
subMod x y = (x - y) `mod` modulo
mulMod x y = (x * y) `rem` modulo
recipM :: Int64 -> Int64
recipM x = case exEuclid x modulo of
             (1,a,_) -> a `mod` modulo
             (-1,a,_) -> (-a) `mod` modulo
divM x y = x `mulMod` recipM y

newtype N = N Int64 deriving (Eq, Show)
instance Num N where
  N x + N y = N ((x + y) `rem` modulo)
  N x - N y = N ((x - y) `mod` modulo)
  N x * N y = N ((x * y) `rem` modulo)
  fromInteger n = N (fromInteger (n `mod` fromIntegral modulo))
  abs = undefined; signum = undefined

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

main = do
  [b,w] <- map (read . BS.unpack) . BS.words <$> BS.getLine
  let half = 1 / 2 :: N
  arr <- newArray ((0,0),(b+1,w+1)) 0 :: IO (IOUArray (Int,Int) Int64)
  writeArray arr (b,w) 1
  vec <- UM.new (b+w) :: IO (UM.IOVector Int64)
  forM_ [b+w-1,b+w-2..0] $ \i -> do
    forM_ [max 0 (i - w)..min b i] $ \j -> do
      let k = i - j
      -- j + k == i
      -- 1 <= j <= b, 1 <= k <= w
      u <- readArray arr (j+1,k)
      v <- readArray arr (j,k+1)
      let N uu | k == 0 = N u
               | otherwise = half * N u
      let N vv | j == 0 = N v
               | otherwise = half * N v
      when (j >= 0) $ UM.modify vec (`addMod` uu) i
      writeArray arr (j,k) (uu `addMod` vv)
  forM_ [b+w-1,b+w-2..0] $ \i -> do
    print =<< UM.read vec i


Score : 100 points

Problem Statement

On the Planet AtCoder, there are four types of bases: A, C, G and T. A bonds with T, and C bonds with G.

You are given a letter b as input, which is A, C, G or T. Write a program that prints the letter representing the base that bonds with the base b.

Constraints

b is one of the letters A, C, G and T.

Input

Input is given from Standard Input in the following format:

b

Output

Print the letter representing the base that bonds with the base b.

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C


ac :: String -> String
ac x
 |x == "A" = "T"
 |x == "T" = "A"
 |x == "G" = "C"
 |otherwise = "G"
main=do
n<-getLine
putStrLn$ac n


main = getLine >>= print . solve 0 0

solve ans _ [] = ans
solve ans cnt (c:cs) = if c `elem` "ACGT"
  then solve (max ans (cnt + 1)) (cnt + 1) cs
  else solve ans 0 cs

Score : 200 points

Problem Statement

You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

S is a string of length between 1 and 10 (inclusive).

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest ACGT string that is a substring of S.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is (the empty string).


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

readPair :: IO (Int,Int)
readPair = do
    [a,b] <- map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine
    return (a,b)

main = do
    (n,q) <- readPair :: IO (Int,Int)
    s <- listArray (1,n) . accumACIndices 0 <$> getLine
    r <- replicateM q $ solve s
    mapM_ print r

accumACIndices :: Int -> String -> [Int]
accumACIndices _ []           = []
accumACIndices c ('A':'C':ls) = let c'=c+1 in c':c':(accumACIndices c' ls)
accumACIndices c (_:ls)       = c:accumACIndices c ls

solve :: Array Int Int -> IO Int
solve arr = do
    (l,r) <- readPair
    let l' = if l > 1 then arr!(l-1) else 0
    return (arr!(r-1) - l')

Score : 300 points

Problem Statement

You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:

Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.

Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.

Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.


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

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.Function
import Data.STRef
import Data.IORef
import System.IO
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 qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
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.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

main :: IO ()
main = do
  [n,q] <- map readInt . words <$> getLine
  str <- BS.getLine
  let vec = VU.map fst
            $ VU.scanl' (\(!tot,!prev) !this ->
                         (if prev == 'A' && this == 'C' then tot+1 else tot,
                         this)) (0::Int,'T')
            $ VU.unfoldrN n BS.uncons str
  queries <- VU.unfoldrN q (runStateT $ (,) <$> rInt <*> rInt)
             <$> BSL.getContents
  let ans = VU.map (\(l,r) -> vec VU.! r -
                     vec VU.! if BS.index str (l-1) == 'C' then l else (l-1))
            queries
  VU.mapM_ print ans

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

#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read
#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;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

{-# INLINE wrA #-}
wrA = A.writeArray
{-# INLINE rdA #-}
rdA = A.readArray
{-# INLINE mdA #-}
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)
{-# INLINE swapA #-}
swapA arr i j = do
  ai <- rdA arr i
  wrA arr i =<< rdA arr j
  wrA arr j ai

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


module Main where

import Control.Monad
import Data.List
import Data.List.Split
import Data.Array.IO
import qualified Data.Vector as V

main :: IO ()
main = do
  [n,q] <- map read . words <$> getLine
  s <- getLine
  lrs <- replicateM q $ map read . words <$> getLine :: IO [[Int]]

  let mi = minimum $ map (\(l:_) -> l) lrs
      ma = maximum $ map (\(_:m:_) -> m) lrs
      as = getS mi ma s

  mapM_ (\(l:r:_) -> (print . length . filter (\i -> i >= l && i < r)) as) lrs

solve (l:r:_) = getS l r

getS l r s = f (drop (l - 1) (take r s)) l []
  where
    f [] _ c = c
    f [_] _ c = c
    f (s1:s2:ss) i c | s1 == 'A' && s2 == 'C' = f ss (i + 2) (c ++ [i])
                     | otherwise = f (s2:ss) (i + 1) c


{-# LANGUAGE OverloadedStrings #-}
module Main where

import Data.List
import Control.Monad
import Debug.Trace
import qualified Data.Text as T

createACMap :: T.Text -> Int -> [Int]
createACMap t len = filter (\i -> T.isPrefixOf "AC" $ T.drop (i-1) t) [1..len-1]

solve :: [Int] -> (Int, Int) -> Int
solve acMap (from, to) = length $ takeWhile (\pos -> pos < to) $ dropWhile (\pos -> pos < from) acMap

main = do
    (len, lines) <- readTuple :: IO (Int, Int)
    s <- T.pack <$> getLine
    let acMap = createACMap s len
    replicateM lines (readTuple >>= print . solve acMap)

readLs :: Read a => IO [a]
readLs = fmap read . words <$> getLine

readTuple :: Read a  => IO (a, a)
readTuple = do
    [f, s] <- readLs
    pure (f, s)


{-# LANGUAGE OverloadedStrings #-}
module Main where

import Data.List
import Control.Monad
import Debug.Trace
import qualified Data.Text as T

createACMap :: T.Text -> Int -> [Int]
createACMap t len = filter (\i -> T.isPrefixOf "AC" $ T.drop (i-1) t) [1..len-1]

solve :: [Int] -> (Int, Int) -> Int
solve acMap (from, to) = length $ filter (\pos -> pos >= from && pos < to) acMap

main = do
    (len, lines) <- readTuple :: IO (Int, Int)
    s <- T.pack <$> getLine
    let acMap = traceShowId $ createACMap s len
    replicateM lines (readTuple >>= print . solve acMap)

readLs :: Read a => IO [a]
readLs = fmap read . words <$> getLine

readTuple :: Read a  => IO (a, a)
readTuple = do
    [f, s] <- readLs
    pure (f, s)


--{-# LANGUAGE OverloadedStrings #-}
--{-# LANGUAGE OverloadedLists   #-}
{-# LANGUAGE BangPatterns      #-} --引数に!
{-# LANGUAGE MultiWayIf        #-}
{-# LANGUAGE TupleSections     #-}

import Data.List
import Data.Tree
import Data.Array  --変数衝突
import Data.Array.MArray
import Data.Array.ST
import Data.Graph
--import Data.Vector as V　--変数衝突
import qualified Data.Vector.Unboxed as V
import Control.Monad
import Control.Monad.State
import Control.Monad.ST
import Debug.Trace

type D s = STUArray s Int Int

loop :: Int -> Int -> D s -> [(Int,Int)] -> ST s ()
loop n m arr [] = return ()
loop n m arr ((a,b):es) = do
  readArray arr a >>= writeArray arr a .(+1)
  readArray arr b >>= writeArray arr b .(+1)
  loop n m arr es

solve :: Int -> Int -> [(Int,Int)] -> ST s Bool
solve n m es = do
  arr <- newArray (1,n) 0
  loop n m arr es
  ds <- forM [1..n] $ readArray arr
  if any (\e -> e`mod`2 == 1) ds then return False
    else if length (filter (== 6) ds) == 1 || length (filter (==4) ds) == 2 || length (filter (==4) ds) == 3 then return True
      else return False

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

mod0 :: Int -> Int
mod0 n = if n < 1000000007 then n else mod n 1000000007

Score : 800 points

Problem Statement

You are given a simple connected undirected graph consisting of N vertices and M edges.
The vertices are numbered 1 to N, and the edges are numbered 1 to M.

Edge i connects Vertex a_i and b_i bidirectionally.

Determine if three circuits (see Notes) can be formed using each of the edges exactly once.

Notes

A circuit is a cycle allowing repetitions of vertices but not edges.

Constraints

All values in input are integers.

1 \leq N,M \leq 10^{5}

1 \leq a_i, b_i \leq N

The given graph is simple and connected.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

If three circuits can be formed using each of the edges exactly once, print Yes; if they cannot, print No.

Sample Input 1

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

Sample Output 1

Yes

Three circuits can be formed using each of the edges exactly once, as follows:

Sample Input 2

3 3
1 2
2 3
3 1

Sample Output 2

No

Three circuits are needed.

Sample Input 3

18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15

Sample Output 3

Yes


main=do
 getLine
 s<-getLine
 print$subtract 1$foldl1(\a b->a*b`mod`(10^9+7))[(1+)$length$filter(==c)s|c<-['a'..'z']]

Score : 200 points

Problem Statement

You are given a string S of length N.
Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings.

Here, a subsequence of a string is a concatenation of one or more characters from the string without changing the order.

Constraints

1 \leq N \leq 100000

S consists of lowercase English letters.

|S|=N

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of the subsequences such that all characters are different, modulo 10^9+7.

Sample Input 1

4
abcd

Sample Output 1

15

Since all characters in S itself are different, all its subsequences satisfy the condition.

Sample Input 2

3
baa

Sample Output 2

5

The answer is five: b, two occurrences of a, two occurrences of ba. Note that we do not count baa, since it contains two as.

Sample Input 3

5
abcab

Sample Output 3

17


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

solve :: Int -> String -> Int
solve n s = (VU.foldl' (*) 1 cnts) - 1
  where
  cnts = VU.create $ do
    vec <- VUM.replicate 26 1
    forM_ s $ \c -> do
      let i = ord c - ord 'a'
      VUM.modify vec (+ 1) i
    return vec

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

tmain :: B.ByteString -> Int
tmain cont =
  let remLines0 = map B.words (B.lines cont)
      [bs_n]:remLines1 = remLines0
      n = readBInt bs_n
      [bs_s]:remLines2 = remLines1
      s = B.unpack bs_s
  in solve n s

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

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

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

inp1 = "4\nabcd\n"
inp2 = "3\nbaa\n"
inp3 = "5\nabcab\n"
tv1 = tmain $ B.pack inp1
tv2 = tmain $ B.pack inp2
tv3 = tmain $ B.pack inp3
test1 = tv1 == 15
test2 = tv2 == 5
test3 = tv3 == 17
alltest = test1 && test2 && test3


import Data.List
import Control.Monad

solver::[Char]->Int
solver [] = 1
solver (c:rest) = solver rest + sum (map solver (fun c rest))
                  where fun d re = let drpd = (dropWhile (d/=) re) in
                                        if [] == drpd
                                          then []
                                          else (tail drpd):(fun d (tail drpd))

press::[Char]->[Char]
press=map head.group

main::IO()
main=do
  n<-return.read=<<getLine
  dat<-forM [1..n] (\_->getLine)
  (print.solver.press) (concat dat)

Score : 700 points

Problem Statement

There are N stones arranged in a row. The i-th stone from the left is painted in the color C_i.

Snuke will perform the following operation zero or more times:

Choose two stones painted in the same color. Repaint all the stones between them, with the color of the chosen stones.

Find the number of possible final sequences of colors of the stones, modulo 10^9+7.

Constraints

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

1 \leq C_i \leq 2\times 10^5(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
C_1
:
C_N

Output

Print the number of possible final sequences of colors of the stones, modulo 10^9+7.

Sample Input 1

5
1
2
1
2
2

Sample Output 1

3

We can make three sequences of colors of stones, as follows:

(1,2,1,2,2), by doing nothing.

(1,1,1,2,2), by choosing the first and third stones to perform the operation.

(1,2,2,2,2), by choosing the second and fourth stones to perform the operation.

Sample Input 2

6
4
2
5
4
2
4

Sample Output 2

5

Sample Input 3

7
1
3
1
2
3
3
2

Sample Output 3

5


import Data.Bits
import qualified Data.Vector.Unboxed as V
import Data.List
import Data.Monoid

path :: Int -> [Int] -> V.Vector Int
path 1 [k] = V.fromList [0,2^k]
path n (k:ks) = let v = path (n - 1) ks
                    (v0,v1) = V.splitAt (2^(n-2)) v
                    y = V.last v0 `xor` (2^k)
                in v0 <> V.map (`xor` y) (V.reverse v0) <> V.map (`xor` y) (V.reverse v1) <> v1

parseInts :: String -> [Int]
parseInts s = case reads s of
                [(x,t)] -> x : parseInts t
                _ -> []

main = do
  [n,a,b] <- parseInts <$> getLine
  let c = a `xor` b
  if popCount c == 1
    then do putStrLn "YES"
            let k = countTrailingZeros c
            putStrLn $ intercalate " " $ map (show . xor a) $ V.toList $ path n (filter (/= k) [0..n-1] ++ [k])
    else putStrLn "NO"

Score : 800 points

Problem Statement

You are given integers N,\ A and B.
Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.

P_0=A

P_{2^N-1}=B

For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.

Constraints

1 \leq N \leq 17

0 \leq A \leq 2^N-1

0 \leq B \leq 2^N-1

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

If there is no permutation that satisfies the conditions, print NO.

If there is such a permutation, print YES in the first line.
Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between.
If there are multiple solutions, any of them is accepted.

Sample Input 1

2 1 3

Sample Output 1

YES
1 0 2 3

The binary representation of P=(1,0,2,3) is (01,00,10,11), where any two adjacent elements differ by exactly one bit.

Sample Input 2

3 2 1

Sample Output 2

NO


{-# LANGUAGE
  ScopedTypeVariables, BangPatterns, TupleSections, ExplicitForAll,
  LambdaCase, MultiWayIf, Unsafe, RecordWildCards, FlexibleContexts, CPP,
  NoMonomorphismRestriction, GADTs, ImplicitParams,
  RankNTypes, EmptyDataDecls, EmptyCase, ViewPatterns #-}

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.Function
import Data.STRef
import Data.IORef
import Data.Monoid
import qualified Data.Foldable as F
import System.IO
import Control.Applicative
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.State.Strict
import Control.Monad.ST
-- import Control.Monad.ST.Safe
import Control.DeepSeq
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Builder as BSB
import qualified Data.ByteString.Lazy.Char8 as BSL
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.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 Control.Monad.ST.Unsafe

main :: IO ()
main = do
  [n,k] <- map readInt . words <$> getLine
  [p,q] <- replicateM 2 $ VU.map (subtract 1)
    . VU.unfoldrN n (runStateT $ rIntS) <$> BS.getLine
  let ?n = n
  let (kd6, km6) = (k-1) `divMod` 6
      actor_main = sympow (conjinv q p `comp` p) kd6
      ans = (!! km6)
        [conj actor_main p,
         conj actor_main q,
         conj actor_main (f p q),
         conjinv (actor_main `comp` q) p,
         conjinv (comp actor_main q `g` p) q,
         conj (comp actor_main q `g` comp q p) (g p q)]
  BSB.hPutBuilder stdout
    $ F.fold
    $ V.imap (\i -> if i > 0 then (BSB.char7 ' ' <>) else id)
    $ V.map BSB.intDec $ V.convert $ VU.map (+1) ans

-- Aut_Set({0,..,n-1})
-- To be used under the constraint (?n :: Int)
-- INVARIANT : VU.length x == ?n for x :: Perm
-- INVARIANT : VU.all (uncurry (==)) $ VU.indexed $ sort x for x :: Perm
type Perm = VU.Vector Int

idperm :: (?n :: Int) => Perm
{-# INLINE idperm #-}
idperm = VU.generate ?n id

inv :: (?n :: Int) => Perm -> Perm
{-# INLINE inv #-}
inv = g idperm

comp :: Perm -> Perm -> Perm
{-# INLINE comp #-}
comp = VU.map . (VU.!)

-- f p q = qp^{-1}
f :: (?n :: Int) => Perm -> Perm -> Perm
{-# INLINE f #-}
f = VU.update_ (VU.replicate ?n (-1))

-- g p q = pq^{-1}
g :: (?n :: Int) => Perm -> Perm -> Perm
{-# INLINE g #-}
g = flip f

-- conj p x = pxp^{-1}
conj :: (?n :: Int) => Perm -> Perm -> Perm
{-# INLINE conj #-}
conj p x = g (comp p x) p

-- conjinv p x = px^{-1}p^{-1}
conjinv :: (?n :: Int) => Perm -> Perm -> Perm
{-# INLINE conjinv #-}
conjinv p x = g p (comp p x)

sympow :: (?n :: Int) => Perm -> Int -> Perm
sympow p 0 = idperm
sympow p k = VU.create $ do
  vec <- VU.thaw idperm
  let loop !p !k = do
        when (testBit k 0) $ forM_ [0 .. ?n-1] $ VUM.modify vec (p VU.!)
        let k1 = shiftR k 1
        when (k1 > 0) $ loop (comp p p) k1
  if k >= 0 then loop p k else loop (inv p) (-k)
  return vec

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

#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read
#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;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

{-# INLINE wrA #-}
wrA = A.writeArray
{-# INLINE rdA #-}
rdA = A.readArray
{-# INLINE mdA #-}
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)
{-# INLINE swapA #-}
swapA arr i j = do
  ai <- rdA arr i
  wrA arr i =<< rdA arr j
  wrA arr j ai

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

Score : 1000 points

Problem Statement

For two permutations p and q of the integers from 1 through N, let f(p,q) be the permutation that satisfies the following:

The p_i-th element (1 \leq i \leq N) in f(p,q) is q_i.
Here, p_i and q_i respectively denote the i-th element in p and q.

You are given two permutations p and q of the integers from 1 through N.
We will now define a sequence {a_n} of permutations of the integers from 1 through N, as follows:

a_1=p, a_2=q

a_{n+2}=f(a_n,a_{n+1}) ( n \geq 1 )

Given a positive integer K, find a_K.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq 10^9

p and q are permutations of the integers from 1 through N.

Input

Input is given from Standard Input in the following format:

N K
p_1 ... p_N
q_1 ... q_N

Output

Print N integers, with spaces in between.
The i-th integer (1 \leq i \leq N) should be the i-th element in a_K.

Sample Input 1

3 3
1 2 3
3 2 1

Sample Output 1

3 2 1

Since a_3=f(p,q), we just need to find f(p,q).
We have p_i=i here, so f(p,q)=q.

Sample Input 2

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

Sample Output 2

4 3 2 1 5

Sample Input 3

10 1000000000
7 10 6 5 4 2 9 1 3 8
4 1 9 2 3 7 8 10 6 5

Sample Output 3

7 9 4 8 2 5 1 6 10 3


{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Data.List
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as VM

infixl 7 <.>

newtype Perm = Perm (V.Vector Int) deriving Eq

permFromIntList :: Int -> [Int] -> Perm
permFromIntList n xs = Perm $ V.fromListN n $ map (subtract 1) xs

identPerm :: Int -> Perm
identPerm n = Perm $ V.fromListN n [0..n-1]

compPerm :: Perm -> Perm -> Perm
compPerm (Perm f) (Perm g)
  = let n = V.length f -- = V.length g
    in Perm $ V.generate n $ \i -> f V.! (g V.! i)

(<.>) :: Perm -> Perm -> Perm
(<.>) = compPerm

invPerm :: Perm -> Perm
invPerm (Perm p) = Perm $ V.create $ do
  let n = V.length p
  q <- VM.new n
  forM_ [0..n-1] $ \i -> do
    VM.write q (p V.! i) i
  return q

powPerm :: Int -> Perm -> Int -> Perm
powPerm n _ 0 = identPerm n
powPerm _ p i = loop (i-1) p p
  where loop 0 !p !acc = acc
        loop 1 p acc = p `compPerm` acc
        loop i p acc = case quotRem i 2 of
                         (j,0) -> loop j (p `compPerm` p) acc
                         (j,_) -> loop j (p `compPerm` p) (acc `compPerm` p)

showPerm :: Perm -> String
showPerm (Perm p) = intercalate " " $ map (show . (+ 1)) $ V.toList p

parseInts :: String -> [Int]
parseInts s = case reads s of
                [(x,t)] -> x : parseInts t
                _ -> []

main = do
  [n,k] <- parseInts <$> getLine
  ps <- parseInts <$> getLine
  qs <- parseInts <$> getLine
  let p = permFromIntList n ps
      q = permFromIntList n qs
      f p q = q `compPerm` invPerm p

  {-
  let as = p : q : zipWith f as (tail as)
      a_k = as !! (k - 1)
  putStrLn $ showPerm a_k
  -}
  {-
  let loop i p q | i == 0 = p
                 | otherwise = loop (i - 1) q (f p q)
  putStrLn $ showPerm $ loop (k - 1) p q
  -}

  let m = (k + 1) `quot` 2
      r = (q <.> invPerm p) <.> (invPerm q <.> p)
      b = case m `quotRem` 3 of
            (l,0) -> powPerm n r (l-1) <.> q <.> invPerm p
            (l,1) -> powPerm n r l
            (l,_) -> powPerm n r l <.> q
      c = case k `rem` 6 of
            0 -> invPerm q <.> p
            1 -> p
            2 -> q
            3 -> invPerm p <.> q
            4 -> invPerm p
            _ -> invPerm q
      a_k' = b <.> c <.> invPerm b
  putStrLn $ showPerm a_k'


{-# LANGUAGE CPP #-}
module Main where

import qualified Data.Vector as V
import qualified Data.Map.Strict as M
import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.Maybe

dump :: (Show a) => a -> IO()
#if __GLASGOW_HASKELL__ >= 850
dump x = print x
#else
dump _ = pure ()
#endif

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

readvec :: IO [Int]
readvec = (fmap (read . BS.unpack) . BS.words) <$> BS.getLine

newtype UF a = UF (M.Map a a) deriving (Show) -- Map node parent

makeuf :: Int -> UF Int
makeuf n = let m = M.fromList $ zip [0..n] [0..n]
                in UF m

union :: (Eq a, Ord a) => a -> a -> UF a -> UF a
union l r uf@(UF m) = let lp = find l uf
                          rp = find r uf
                      in if lp == rp
                         then uf
                         else if size l uf < size r uf
                              then UF $ M.update (const $ Just rp) lp m
                              else UF $ M.update (const $ Just lp) rp m

find :: (Eq a, Ord a) => a -> UF a -> a
find x uf@(UF m) = let px = m M.! x
                in if px == x
                   then px
                   else find px uf -- TODO 貼り直し

size :: (Eq a, Ord a) => a -> UF a -> Int
size x (UF m) = M.size $ M.filter (\par -> par==x) m

main :: IO()
main = do
  [h, w] <- readvec
  [h', w'] <- readvec
  print $ (h - h') * (w - w')

Score : 100 points

Problem Statement

There are H rows and W columns of white square cells.

You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns.

How many white cells will remain?

It can be proved that this count does not depend on what rows and columns are chosen.

Constraints

All values in input are integers.

1 \leq H, W \leq 20

1 \leq h \leq H

1 \leq w \leq W

Input

Input is given from Standard Input in the following format:

H W
h w

Output

Print the number of white cells that will remain.

Sample Input 1

3 2
2 1

Sample Output 1

1

There are 3 rows and 2 columns of cells. When two rows and one column are chosen and painted in black, there is always one white cell that remains.

Sample Input 2

5 5
2 3

Sample Output 2

6

Sample Input 3

2 4
2 4

Sample Output 3

0


main :: IO ()
main = do
    a1 <- map toInt . words <$> getLine
    a2 <- map toInt . words <$> getLine
    print $ a1 !! 0 * a1 !! 1 - a2 !! 0 * a1 !! 1 - a2 !! 1 * (a1 !! 0 - a2 !! 0)

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


import Control.Monad (replicateM)
main = do
  [n,m,c] <- map read . words <$> getLine
  bn <- map read .words <$> getLine
  anm <- replicateM n $ map read . words <$> getLine::IO[[Int]]
  print $ length $ filter (>0) [foldl (\acc (a, b) -> acc + a * b) c $ zip am bn |am <- anm]

Score : 200 points

Problem Statement

There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}.

Additionally, you are given integers B_1, B_2, ..., B_M and C.

The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0.

Among the N codes, find the number of codes that correctly solve this problem.

Constraints

All values in input are integers.

1 \leq N, M \leq 20

-100 \leq A_{ij} \leq 100

-100 \leq B_i \leq 100

-100 \leq C \leq 100

Input

Input is given from Standard Input in the following format:

N M C
B_1 B_2 ... B_M
A_{11} A_{12} ... A_{1M}
A_{21} A_{22} ... A_{2M}
\vdots
A_{N1} A_{N2} ... A_{NM}

Output

Print the number of codes among the given N codes that correctly solve this problem.

Sample Input 1

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

Sample Output 1

1

Only the second code correctly solves this problem, as follows:

Since 3 \times 1 + 2 \times 2 + 1 \times 3 + (-10) = 0 \leq 0, the first code does not solve this problem.

1 \times 1 + 2 \times 2 + 2 \times 3 + (-10) = 1 > 0, the second code solves this problem.

Sample Input 2

5 2 -4
-2 5
100 41
100 40
-3 0
-6 -2
18 -13

Sample Output 2

2

Sample Input 3

3 3 0
100 -100 0
0 100 100
100 100 100
-100 100 100

Sample Output 3

0

All of them are Wrong Answer. Except yours.


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

getInts :: IO [Int]
getInts = fmap (map (fst . fromJust . C8.readInt) . C8.words) C8.getLine

main :: IO ()
main = do
    [n, m] <- getInts
    cs     <- replicateM n $ getInts
    print . purchase m $ sortOn fst . map (\[a, b] -> (a, b)) $ cs

purchase :: Int -> [(Int, Int)] -> Int
purchase m ((a, b) : cs) | m <= b    = m * a
                         | otherwise = a * b + purchase (m - b) cs
purchase _ [] = 0

Score : 300 points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.

There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy M cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the minimum amount of money with which Takahashi can buy M cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

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


{-# LANGUAGE BangPatterns #-}

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

type Pair = (Int, Int)

main :: IO ()
main = do
  [n,m] <- readInts
  ps <- sortOn fst <$> replicateM n readPair
  print $ solve m ps

solve :: Int -> [Pair] -> Int
solve m = fst . foldl' f e
  where
    e = (0,0)
    f (!s,!n) (a,b)
      | n == m = (s,n)
      | c > m = until ((m==).snd) (\(!s,!n) -> (s+a,n+1)) (s,n)
      | otherwise = (s+a*b, c)
      where
        c = n+b

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

readPair :: IO Pair
readPair = do
  [x,y] <- readInts
  return (x,y)


import qualified Data.ByteString.Char8 as BS

main = do
  [a,b,k] <- map (read . BS.unpack) . BS.words <$> BS.getLine
  let d = gcd a b
  print $ [i | i <- [d,d-1..1], a `rem` i == 0, b `rem` i == 0] !! (k - 1)

Score : 200 points

Problem Statement

You are given positive integers A and B.

Find the K-th largest positive integer that divides both A and B.

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

The K-th largest positive integer that divides both A and B exists.

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the K-th largest positive integer that divides both A and B.

Sample Input 1

8 12 2

Sample Output 1

2

Three positive integers divides both 8 and 12: 1, 2 and 4.
Among them, the second largest is 2.

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


main = do
  [a,b,k] <- map read.words <$> getLine
  putStrLn.show $ (gcd' a b) !! (k-1)

gcd' a b = filter (\v -> mod a v == 0 && mod b v == 0) [min a b , (min a b)-1.. 1]


-- 2 variables
main = do
  (x:y:k:xs) <- map read . words <$> getLine
  putStrLn . show $ solve x y k (min x y)

solve :: Int -> Int -> Int -> Int -> Int
solve x y k p
  | x `mod` p == 0 && y `mod` p == 0 =
      if k == 1 then
        p
      else
        solve x y (k-1) (p-1)
  | otherwise = solve x y k (p-1)


{-# LANGUAGE BangPatterns #-}
module Main where

solve :: Int -> String -> String -> Int
solve !n _ [] = n
solve !n (x : xs) (y : ys)
  | x /= y = solve (n + 2) xs ys
solve !n xs (y : ys) = solve n (y : xs) ys

main = getLine >>= print . solve 0 []

Score : 300 points

Problem Statement

There are N cubes stacked vertically on a desk.

You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is 0, and blue if that character is 1.

You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent, and remove them. Here, the cubes that were stacked on the removed cubes will fall down onto the object below them.

At most how many cubes can be removed?

Constraints

1 \leq N \leq 10^5

|S| = N

Each character in S is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of cubes that can be removed.

Sample Input 1

0011

Sample Output 1

4

All four cubes can be removed, by performing the operation as follows:

Remove the second and third cubes from the bottom. Then, the fourth cube drops onto the first cube.

Remove the first and second cubes from the bottom.

Sample Input 2

11011010001011

Sample Output 2

12

Sample Input 3

0

Sample Output 3

0


{-# LANGUAGE BangPatterns #-}
import Control.Arrow (second)
import Control.Monad
import Control.Monad.Fix
import Data.Foldable (foldl')
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.ByteString.Char8 as B
import Data.ByteString.Internal (accursedUnutterablePerformIO)
import Debug.Trace

uread :: VUM.Unbox a => Int -> VUM.IOVector a -> a
uread i v = accursedUnutterablePerformIO $ VUM.unsafeRead v i

uwrite :: VUM.Unbox a => Int -> a -> VUM.IOVector a -> VUM.IOVector a
uwrite i a v = accursedUnutterablePerformIO $ VUM.unsafeWrite v i a >> return v

uswap :: VUM.Unbox a => Int -> Int -> VUM.IOVector a -> VUM.IOVector a
uswap i j v = accursedUnutterablePerformIO $ VUM.unsafeSwap v i j >> return v

ufreeze :: VUM.Unbox a => VUM.IOVector a -> VU.Vector a
ufreeze v = accursedUnutterablePerformIO $ VU.unsafeFreeze v

uthaw :: VUM.Unbox a => VU.Vector a -> VUM.IOVector a
uthaw v = accursedUnutterablePerformIO $ VU.unsafeThaw v

newtype UnionFind = UnionFind (VUM.IOVector Int, VUM.IOVector Int)

new :: Int -> UnionFind
new n = UnionFind
  ( uthaw $! VU.fromList [0 .. n - 1]
  , accursedUnutterablePerformIO $! VUM.replicate n 1
  )

findUF :: UnionFind -> Int -> Int
findUF (UnionFind (elems, _)) k = fix
  ( \f (elems, k, path) -> case uread k elems of
    n | n == k -> foldl' (\acc p -> uwrite p n acc) elems path `seq` n
    n          -> f (elems, n, n : path)
  )
  (elems, k, [k])

sizeUF :: UnionFind -> Int -> Int
sizeUF uf@(UnionFind (_, sizes)) i =
  let j = findUF uf i in j `seq` uread j sizes

unionUF :: UnionFind -> Int -> Int -> UnionFind
unionUF uf@(UnionFind (elem, sizes)) i j =
  let pi = findUF uf i
      pj = findUF uf j
      si = uread pi sizes
      sj = uread pj sizes
  in  if pi == pj
        then uf
        else
          let (t1, t2) = if si < sj then (pi, pj) else (pj, pi)
          in  UnionFind (uwrite t1 t2 elem, uwrite t2 (si + sj) sizes)

solve :: Int -> Int -> VU.Vector (Int, Int) -> VU.Vector Int
solve n m !abs = VU.empty {- VU.init $ ufreeze $ (\(_, _, _, acc) -> acc) $ VU.foldr'
  go
  ( new n
  , m - 1
  , nC2
  , uwrite m nC2 $ accursedUnutterablePerformIO $ VUM.unsafeNew (m + 1)
  )
  abs -}
 where
  go (a, b) (uf, k, prev, acc) =
    let ga  = findUF uf a
        gb  = findUF uf b
        n1  = sizeUF uf a
        n2  = sizeUF uf b
        res = prev - (if ga == gb then 0 else n1 * n2)
    in  (unionUF uf a b, k - 1, res, uwrite k prev acc)

  nC2 = n * (n - 1) `div` 2

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

  (n, m) <-
    (\vec -> (vec VU.! 0, vec VU.! 1)) . VU.unfoldrN 2 readInt <$> B.getLine
  abs <- VU.replicateM
    m
    (   (\vec -> (vec VU.! 0 - 1, vec VU.! 1 - 1))
    .   VU.unfoldrN 2 readInt
    <$> B.getLine
    )

  VU.mapM_ print $ solve n m abs

Score : 400 points

Problem Statement

There are N islands and M bridges.

The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.

Initially, we can travel between any two islands using some of these bridges.

However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.

Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.

For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 1

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

Sample Output 1

0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

Sample Input 2

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

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1