import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Set as ST
import qualified Data.Map.Strict as MPS
import Data.List
import Data.Tuple
import Control.Monad

type Graph = MPS.Map Int [(Int, Int)]
type Distance = VUM.IOVector Int
type Queue = ST.Set (Int, Int)

makeGraph :: [(Int, [(Int, Int)])] -> Graph
makeGraph xs = MPS.fromListWith (++) xs

dijkstra :: Int -> Int -> Graph -> IO Distance
dijkstra vertex from graph = do
  distance <- VUM.replicate (vertex+1) (10^9) :: IO Distance
  VUM.write distance from 0
  trav graph distance (ST.singleton (0, from))
  where
    trav :: Graph -> Distance -> Queue -> IO Distance
    trav graph distance queue
      | ST.null queue = return distance
      | otherwise = do
          tmp <- VUM.read distance from
          if acc <= tmp
            then update >>= trav graph distance
            else trav graph distance queue'
        where
          ((acc, from), queue') = ST.deleteFindMin queue

          update :: IO Queue
          update =
            case MPS.lookup from graph of
              Just xs -> update' xs queue'
              Nothing -> return queue'
            where
              update' :: [(Int, Int)] -> Queue -> IO Queue
              update' [] q = return q
              update' ((to, cost):xs) q = do
                tmp <- VUM.read distance to
                let acc' = acc + cost
                case compare acc' tmp of
                   LT -> do
                      VUM.write distance to acc'
                      update' xs (ST.insert (acc', to) q)
                   _ ->
                      update' xs q

main = do
  [n,a,b] <- map read . words <$> getLine :: IO [Int]
  let vs = let xs = zip [1..n] [2..n] in (map swap xs) ++ xs :: [(Int, Int)]
  let vs' = [(a,[(b,1)]), (b,[(a,1)])] ++ map (\(f,t) -> (f,[(t,1)])) vs :: [(Int, [(Int, Int)])]
  let graph = makeGraph vs'

  table <- VUM.replicate n 0 :: IO (VUM.IOVector Int)

  forM_ [1..n] $ \i -> do
    dist <- dijkstra n i graph
    dist' <- VU.tail . VU.zip (VU.fromList [0..n]) <$> VU.unsafeFreeze dist
    VU.forM_ dist' $ \(j,d) ->
      when (d /= 10^9 && j > i) $
        VUM.modify table (+1) (d-1)

  table' <- VU.init <$> VU.unsafeFreeze table
  VU.mapM_ print table'


module Main where

import           Debug.Trace
import qualified Data.Vector.Unboxed           as VU
import           Data.List
import qualified Data.ByteString               as BS
import qualified Data.ByteString.Char8         as BSC8
import           Data.Char
import           Data.Maybe

getVUIntFromInputLineAtBSC8 :: IO (VU.Vector Int)
getVUIntFromInputLineAtBSC8 =
    VU.unfoldr (BSC8.readInt . BSC8.dropWhile isSpace) <$> BSC8.getLine
getListIntFromInputLineAtBSC8 =
    unfoldr (BSC8.readInt . BSC8.dropWhile isSpace) <$> BSC8.getLine
readInt = fst . fromJust . BSC8.readInt
readIntList = map readInt . BSC8.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

main :: IO ()
main = do
    s <- getLine
    --[aM,aN] <- getListIntFromInputLineAtBSC8
    --aP                   <- getVUIntFromInputLineAtBSC8
    --aQ                   <- getVUIntFromInputLineAtBSC8
    --aR                   <- getVUIntFromInputLineAtBSC8

    --vP <- VU.fromList . take aX . reverse . sort <$> getIntList
    --vQ <- VU.fromList . take aY . reverse . sort <$> getIntList
    --vR <- VU.fromList . take (aX + aY) . reverse . sort <$> getIntList
    putStrLn $ if isStrongPalindrome s then "Yes" else "No"

isStrongPalindrome :: [Char] -> Bool
isStrongPalindrome s =
    (isPalindrome (take lFront s)) && (isPalindrome (drop (lBack-1) s))
  where
    isEven = even ((length s) - 1)
    lFront = div (length s - 1) 2
    -- + if isEven then 0 else 1
    lBack  = div (length s + 3) 2
    -- + if isEven then 0 else 1

isPalindrome :: [Char] -> Bool
isPalindrome = reverse >>= (==)

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

Score : 200 points

Problem Statement

A string S of an odd length is said to be a strong palindrome if and only if all of the following conditions are satisfied:

S is a palindrome.

Let N be the length of S. The string formed by the 1-st through ((N-1)/2)-th characters of S is a palindrome.

The string consisting of the (N+3)/2-st through N-th characters of S is a palindrome.

Determine whether S is a strong palindrome.

Constraints

S consists of lowercase English letters.

The length of S is an odd number between 3 and 99 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

If S is a strong palindrome, print Yes;
otherwise, print No.

Sample Input 1

akasaka

Sample Output 1

Yes

S is akasaka.

The string formed by the 1-st through the 3-rd characters is aka.

The string formed by the 5-th through the 7-th characters is aka.
All of these are palindromes, so S is a strong palindrome.

Sample Input 2

level

Sample Output 2

No

Sample Input 3

atcoder

Sample Output 3

No

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.


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

main = abc159d

abc159d = do
    [n] <- getIntList
    a <- getIntList
    let dict = genDict a
    mapM (\x -> print $ sumComb dict - (M.!) dict x + 1) a

genDict :: (Integral a) => [a] -> M.Map a a
genDict as = let as' = nub as
                 asMap = M.fromList [(a,a) | a <- as']
              in M.foldl (\acc a -> M.insert a (fromIntegral . length . filter (== a) $ as) acc) M.empty asMap

sumComb :: M.Map Integer Integer -> Integer
sumComb dict = sum $ map comb $ M.elems dict

comb :: Integer -> Integer
comb k
    | k < 2 = 0
    | otherwise = div (k * (fromIntegral k - 1)) 2

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

Score : 400 points

Problem Statement

We have N balls. The i-th ball has an integer A_i written on it.

For each k=1, 2, ..., N, solve the following problem and print the answer.

Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.

Constraints

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

1 \leq A_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

For each k=1,2,...,N, print a line containing the answer.

Sample Input 1

5
1 1 2 1 2

Sample Output 1

2
2
3
2
3

Consider the case k=1 for example. The numbers written on the remaining balls are 1,2,1,2.

From these balls, there are two ways to choose two distinct balls so that the integers written on them are equal.

Thus, the answer for k=1 is 2.

Sample Input 2

4
1 2 3 4

Sample Output 2

0
0
0
0

No two balls have equal numbers written on them.

Sample Input 3

5
3 3 3 3 3

Sample Output 3

6
6
6
6
6

Any two balls have equal numbers written on them.

Sample Input 4

8
1 2 1 4 2 1 4 1

Sample Output 4

5
7
5
7
7
5
7
5


Score : 100 points

Problem Statement

Print the K-th element of the following sequence of length 32:

1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51

Constraints

1 \leq K \leq 32

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the K-th element.

Sample Input 1

6

Sample Output 1

2

The 6-th element is 2.

Sample Input 2

27

Sample Output 2

5

The 27-th element is 5.


import Control.Monad
import Data.Char
import Data.Function

main = do
  n <- readLn
  forM_ (solve n) putStrLn

solve :: Int -> [String]
solve n = go 'a' n
  where
    go :: Char -> Int -> [String]
    go _ 0 = [""]
    go c n = concat [map (c' :) (go d (n-1))|c' <- ['a' .. c], let d = chr $ (max `on` fromEnum) c (succ c')]

Score : 400 points

Problem Statement

In this problem, we only consider strings consisting of lowercase English letters.

Strings s and t are said to be isomorphic when the following conditions are satisfied:

|s| = |t| holds.

For every pair i, j, one of the following holds:

s_i = s_j and t_i = t_j.

s_i \neq s_j and t_i \neq t_j.

For example, abcac and zyxzx are isomorphic, while abcac and ppppp are not.

A string s is said to be in normal form when the following condition is satisfied:

For every string t that is isomorphic to s, s \leq t holds. Here \leq denotes lexicographic comparison.

For example, abcac is in normal form, but zyxzx is not since it is isomorphic to abcac, which is lexicographically smaller than zyxzx.

You are given an integer N.
Print all strings of length N that are in normal form, in lexicographically ascending order.

Constraints

1 \leq N \leq 10

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Assume that there are K strings of length N that are in normal form: w_1, \ldots, w_K in lexicographical order.
Output should be in the following format:

w_1
:
w_K

Sample Input 1

1

Sample Output 1

a

Sample Input 2

2

Sample Output 2

aa
ab


--{-# LANGUAGE BangPatterns #-}
--{-# LANGUAGE ScopedTypeVariables #-}
--{-# LANGUAGE FlexibleContexts #-}
--{-# LANGUAGE ViewPatterns #-}
--{-# LANGUAGE OverloadedStrings #-}
--{-# LANGUAGE Strict #-}
--{-# LANGUAGE NumericUnderscores #-}
--{-# LANGUAGE BlockArguments #-}
{-# 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

#if __GLASGOW_HASKELL__ >= 808
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
#endif

--------------------------------------------------------------------------
solve [_] = False
solve (x:y:xs) = (x=='h' && y=='i') && solve (y:xs)

main = do
   xs <- str
   yesnoL $ solve xs
--------------------------------------------------------------------------

-- 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 -> []

#if __GLASGOW_HASKELL__ >= 808
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

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

Score : 100 points

Problem Statement

A Hitachi string is a concatenation of one or more copies of the string hi.

For example, hi and hihi are Hitachi strings, while ha and hii are not.

Given a string S, determine whether S is a Hitachi string.

Constraints

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

S is a string consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is a Hitachi string, print Yes; otherwise, print No.

Sample Input 1

hihi

Sample Output 1

Yes

hihi is the concatenation of two copies of hi, so it is a Hitachi string.

Sample Input 2

hi

Sample Output 2

Yes

Sample Input 3

ha

Sample Output 3

No


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

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

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

import qualified Data.ByteString.Char8 as B

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

import Debug.Trace
import Text.Printf

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

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

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

main = do
	s <- getLine
	putStrLn $ which "Yes" "No" $ ( s !! 0 ) /= ( s !! 1 ) && ( s !! 0 ) == ( s !! 2 )

Score : 100 points

Problem Statement

In AtCoder City, there are three stations numbered 1, 2, and 3.

Each of these stations is operated by one of the two railway companies, A and B. A string S of length 3 represents which company operates each station. If S_i is A, Company A operates Station i; if S_i is B, Company B operates Station i.

To improve the transportation condition, for each pair of a station operated by Company A and one operated by Company B, there will be a bus service connecting them.

Determine if there is a pair of stations that will be connected by a bus service.

Constraints

Each character of S is A or B.

|S| = 3

Input

Input is given from Standard Input in the following format:

S

Output

If there is a pair of stations that will be connected by a bus service, print Yes; otherwise, print No.

Sample Input 1

ABA

Sample Output 1

Yes

Company A operates Station 1 and 3, while Company B operates Station 2.

There will be a bus service between Station 1 and 2, and between Station 2 and 3, so print Yes.

Sample Input 2

BBA

Sample Output 2

Yes

Company B operates Station 1 and 2, while Company A operates Station 3.

There will be a bus service between Station 1 and 3, and between Station 2 and 3, so print Yes.

Sample Input 3

BBB

Sample Output 3

No

Company B operates all the stations. Thus, there will be no bus service, so print No.


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

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

main = do
    [a, b] <- getIntList
    let minA = fst $ properFraction $ realToFrac a * 12.5
        maxA = fst $ properFraction $ realToFrac (a+1) * 12.5
        minB = b * 10
        maxB = (b+1) * 10 - 1
        minElem = max minA minB
        maxElem = min maxA maxB
        priceSet = if  minElem > maxElem then [] else [minElem..maxElem]
    putStrLn . show $ if length priceSet == 0 then -1 else head priceSet

Score : 300 points

Problem Statement

Find the price of a product before tax such that, when the consumption tax rate is 8 percent and 10 percent, the amount of consumption tax levied on it is A yen and B yen, respectively. (Yen is the currency of Japan.)

Here, the price before tax must be a positive integer, and the amount of consumption tax is rounded down to the nearest integer.

If multiple prices satisfy the condition, print the lowest such price; if no price satisfies the condition, print -1.

Constraints

1 \leq A \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If there is a price that satisfies the condition, print an integer representing the lowest such price; otherwise, print -1.

Sample Input 1

2 2

Sample Output 1

25

If the price of a product before tax is 25 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 25 \times 0.08 \rfloor = \lfloor 2 \rfloor = 2 yen.

When the consumption tax rate is 10 percent: \lfloor 25 \times 0.1 \rfloor = \lfloor 2.5 \rfloor = 2 yen.

Thus, the price of 25 yen satisfies the condition. There are other possible prices, such as 26 yen, but print the minimum such price, 25.

Sample Input 2

8 10

Sample Output 2

100

If the price of a product before tax is 100 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 100 \times 0.08 \rfloor = 8 yen.

When the consumption tax rate is 10 percent: \lfloor 100 \times 0.1 \rfloor = 10 yen.

Sample Input 3

19 99

Sample Output 3

-1

There is no price before tax satisfying this condition, so print -1.


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

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

--------------------------------------------------------------------------
step :: (Int, SQ.Seq Char, SQ.Seq Char) -> [String] -> (Int, SQ.Seq Char, SQ.Seq Char)
step (cnt,ls,rs) xss
    | head xss == "1" = (cnt+1,ls,rs)
    | otherwise = f (tail xss)
    where
        f [bs,cs]
            | even cnt && bs == "1" = (cnt,ls',rs)
            | even cnt && bs == "2" = (cnt,ls, rs')
            | odd cnt && bs == "1" = (cnt,ls, rs')
            | odd cnt && bs == "2" =  (cnt,ls',rs)
            where
                ls' = (strToChr cs) SQ.<| ls
                rs' = rs SQ.|> (strToChr cs)

make :: SQ.Seq Char -> IO ()
make sq =
    case SQ.viewl sq of
        SQ.EmptyL -> return ()
        c SQ.:< sq' -> putChar c >> make sq'

main = do
    xs <- str
    q <- int
    qsss <- (replicateM q $ BC.getLine >>= return . map BC.unpack . BC.words) :: IO [[String]]
    let (cnt,ls,rs) = foldl' step (0,SQ.empty,SQ.empty) qsss
    if even cnt
        then do
            make ls
            putStr xs
            make rs
        else do
            make $ SQ.reverse rs
            putStr $ reverse xs
            make $ SQ.reverse ls
    putStrLn ""
--------------------------------------------------------------------------

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

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

str :: IO String
str = BC.getLine >>= return . BC.unpack

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 = strBS >>= return . map f . BC.words

-- 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 = BC.getLine >>= return . VU.unfoldrN n parseInt

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

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

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

-- 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 x = subtract 1 x

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

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

Score : 400 points

Problem Statement

Takahashi has a string S consisting of lowercase English letters.

Starting with this string, he will produce a new one in the procedure given as follows.

The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following:

If T_i = 1: reverse the string S.

If T_i = 2: An integer F_i and a lowercase English letter C_i are additionally provided.

If F_i = 1 : Add C_i to the beginning of the string S.

If F_i = 2 : Add C_i to the end of the string S.

Help Takahashi by finding the final string that results from the procedure.

Constraints

1 \leq |S| \leq 10^5

S consists of lowercase English letters.

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

T_i = 1 or 2.

F_i = 1 or 2, if provided.

C_i is a lowercase English letter, if provided.

Input

Input is given from Standard Input in the following format:

S
Q
Query_1
:
Query_Q

In the 3-rd through the (Q+2)-th lines, Query_i is one of the following:

1

which means T_i = 1, and:

2 F_i C_i

which means T_i = 2.

Output

Print the resulting string.

Sample Input 1

a
4
2 1 p
1
2 2 c
1

Sample Output 1

cpa

There will be Q = 4 operations. Initially, S is a.

Operation 1: Add p at the beginning of S. S becomes pa.

Operation 2: Reverse S. S becomes ap.

Operation 3: Add c at the end of S. S becomes apc.

Operation 4: Reverse S. S becomes cpa.

Thus, the resulting string is cpa.

Sample Input 2

a
6
2 2 a
2 1 b
1
2 2 c
1
1

Sample Output 2

aabc

There will be Q = 6 operations. Initially, S is a.

Operation 1: S becomes aa.

Operation 2: S becomes baa.

Operation 3: S becomes aab.

Operation 4: S becomes aabc.

Operation 5: S becomes cbaa.

Operation 6: S becomes aabc.

Thus, the resulting string is aabc.

Sample Input 3

y
1
2 1 x

Sample Output 3

xy


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

main = abc158D

abc158D :: IO()
abc158D = do
  s <- BS.getLine
  [q] <- getIntList
  qs <- map BS.words <$> replicateM (fromIntegral q) BS.getLine
  putStrLn . BS.unpack $ operation s True qs

type Query = [BS.ByteString]
operation :: BS.ByteString -> Bool -> [Query] -> BS.ByteString
operation s b [q] = let executed = exec s b $ map BS.unpack q
                    in if snd executed then fst executed else BS.reverse . fst $ executed
operation s b (q:qs) = let executed = exec s b $ map BS.unpack q
                       in operation (fst executed) (snd executed) qs

exec :: BS.ByteString -> Bool -> [String] -> (BS.ByteString, Bool)
exec s b [['1']] = (s,not b)
exec s True [['2'],[x],[c]] = case x of '1' -> (BS.cons c s, True)
                                        '2' -> (BS.reverse $ BS.cons c (BS.reverse s), True)
exec s False [['2'],[x],[c]] = case x of '1' -> (BS.reverse $ BS.cons c (BS.reverse s), False)
                                         '2' -> (BS.cons c s, False)

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


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

main = abc158D

abc158D :: IO()
abc158D = do
    s <- BS.getLine
    [q] <- getIntList
    qs <- replicateM (fromIntegral q) BS.getLine
    putStrLn $ operation (BS.unpack s) (map BS.unpack qs)

type Query = String
operation :: String -> [Query] -> String
operation s [q] = exec s q
operation s (q:qs) = operation (exec s q) qs

exec :: String -> Query -> String
exec s ['1'] = reverse s
exec s ('2':q) = case q!!1 of '1' -> (q!!3):s
                              '2' -> reverse $ (q!!3):reverse s

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


import Control.Monad (replicateM)
import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (unpack)

toString::(Bool,String)->String
toString (True,s) = s
toString (False,s) = reverse s

main = do
  s <- getLine
  q <- readLn
  qn <- replicateM q BS.getLine::IO[BS.ByteString]
  let p = toString $ foldl (\(r, acc) p -> case words (unpack p) of
            ["2","1",c] -> if r then (r,c ++ acc) else (r,acc ++ c)
            ["2","2",c] -> if r then (r,acc ++ c) else (r,c ++ acc)
            _ -> (not r, acc)) (True,s) qn
  putStrLn $ p


import Data.List
import qualified Data.Sequence as Seq
import Data.Foldable

mapOverTail :: ([a] -> b) -> [a] -> [b]
mapOverTail _ [] = []
mapOverTail f xs = (f xs):mapOverTail f (tail xs)

accumulate :: (Int, Int, Int) -> Int -> (Int, Int, Int)
accumulate (prevN, prime, sum) n = (modRes, prime, (if modRes == 0 then 1 else 0) + sum)
  where modRes = (prevN * 10 + n) `mod` prime

third :: (a, a, a) -> a
third (_, _, x) = x

main :: IO ()
main = do
  line <- getLine
  let (_:p:_) = (map (read :: String -> Int) . words) line
  str <- getLine
  let numStr = map (\x -> read [x] :: Int) str
  let noOfDivisibles = sum $ map third $ mapOverTail (foldl accumulate (0, p, 0)) numStr
  putStrLn $ show noOfDivisibles

Score : 500 points

Problem Statement

Takahashi has a string S of length N consisting of digits from 0 through 9.

He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten.

Here substrings starting with a 0 also count, and substrings originated from different positions in S are distinguished, even if they are equal as strings or integers.

Compute this count to help Takahashi.

Constraints

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

S consists of digits.

|S| = N

2 \leq P \leq 10000

P is a prime number.

Input

Input is given from Standard Input in the following format:

N P
S

Output

Print the number of non-empty (contiguous) substrings of S that are divisible by P when regarded as an integer written in base ten.

Sample Input 1

4 3
3543

Sample Output 1

6

Here S = 3543. There are ten non-empty (contiguous) substrings of S:

3: divisible by 3.

35: not divisible by 3.

354: divisible by 3.

3543: divisible by 3.

5: not divisible by 3.

54: divisible by 3.

543: divisible by 3.

4: not divisible by 3.

43: not divisible by 3.

3: divisible by 3.

Six of these are divisible by 3, so print 6.

Sample Input 2

4 2
2020

Sample Output 2

10

Here S = 2020. There are ten non-empty (contiguous) substrings of S, all of which are divisible by 2, so print 10.

Note that substrings beginning with a 0 also count.

Sample Input 3

20 11
33883322005544116655

Sample Output 3

68


{-# LANGUAGE
  ScopedTypeVariables, BangPatterns, TupleSections, ExplicitForAll,
  LambdaCase, MultiWayIf, Unsafe, RecordWildCards, FlexibleContexts, CPP,
  NoMonomorphismRestriction, GADTs, PatternGuards, MagicHash, UnboxedTuples,
  RankNTypes, EmptyDataDecls, EmptyCase, ViewPatterns, PolyKinds,
  TypeFamilies, OverloadedStrings, FlexibleInstances, UndecidableInstances,
  DefaultSignatures, GeneralizedNewtypeDeriving, StandaloneDeriving,
  DeriveGeneric, DeriveFunctor, DeriveDataTypeable, DeriveFoldable,
  DeriveTraversable, DeriveDataTypeable, FlexibleInstances,
  MultiParamTypeClasses #-}
{-# OPTIONS_GHC -O2 #-}

#define PHASE_FUSED [1]
#define PHASE_INNER [0]
#define INLINE_FUSED INLINE PHASE_FUSED
#define INLINE_INNER INLINE PHASE_INNER

import Prelude
import Data.Bits
import Data.List
import Data.Maybe
import Data.Tuple
import Data.Ord
import Data.Int
import Data.Word
import Data.Char
import Data.Ratio
import Data.Function
import Data.STRef
import Data.IORef
import Data.Monoid
import Data.Functor
import Data.Functor.Identity
import Data.Data
import Data.Typeable
import GHC.Generics
import System.IO
import System.IO.Unsafe (unsafeDupablePerformIO, unsafePerformIO)
import Control.Arrow
import Control.Applicative
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.State.Strict
import Control.Monad.ST
import Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)
import qualified Control.Monad.ST.Lazy as STL
-- import Control.Monad.ST.Safe
import Control.DeepSeq
import Data.Coerce
import qualified Data.ByteString as BSW
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as BSLW
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.ByteString.Builder as BSB
import qualified Data.ByteString.Unsafe as BSU
import qualified Data.ByteString.Internal as BSU
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as IMS
import qualified Data.IntMap.Lazy as IML
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Storable.Mutable as VSM
import qualified Data.Vector.Primitive as VP
import qualified Data.Vector.Primitive.Mutable as VPM
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import qualified Data.Vector.Fusion.Bundle.Monadic as VFBM
import qualified Data.Vector.Fusion.Bundle as VFB
import qualified Data.Vector.Fusion.Stream.Monadic as VFSM
import qualified Data.Vector.Fusion.Bundle.Size as VFBS
import qualified Data.Vector.Fusion.Util as VFU
import qualified Data.Attoparsec.ByteString.Char8 as Atto
import qualified Data.Vector.Generic.New as VGN
import Debug.Trace
import Unsafe.Coerce
import Foreign.ForeignPtr
import GHC.Exts (build, Int(..), Int#,
                 (+#), (*#), (-#), (<#), (>=#), (==#), quotRemInt#,
                 remInt#, uncheckedIShiftRL#, andI#, orI#,
                isTrue#, Addr#, Ptr(..))

main :: IO ()
main = do
  [n,p] <- map readInt . words <$> getLine
  s <- getVecULn n $ toW8 . subtract (fromEnum '0') . fromEnum <$> rCharS
  reifyWord32 (fromIntegral p) $ \pxy -> print
    $ if p /= 2 && p /= 5 then query (VU.reverse s) pxy
        else  VU.sum
             $ VU.map (+1)
             $ VU.findIndices ((==0) . (`mod` p) . toInt) s
  return ()

-- assumes 'm' stands for a prime
query :: (HasWord32 m) => VU.Vector Word8 -> Proxy m -> Int
query vec pxy = VU.sum $ VU.map (\(_,n) -> (n *(n-1))`shiftR` 1)
  $ groupCountVec $ sortedAccs
  where
    pow10 = VU.iterateN (VU.length vec) (*10) (remP pxy 1)
    accs = VU.scanl' (+) (remP pxy 0)
      $ VU.zipWith ((*) . fromIntegral) vec pow10
    sortedAccs = VU.create $ do
      accs_ <- VU.thaw $ VU.map unRem accs
      vait_sort accs_
      return accs_

groupCountVec :: (VG.Vector v a, VG.Vector v (a,Int), Eq a) => v a -> v (a,Int)
{-# INLINE groupCountVec #-}
groupCountVec = groupCountVecBy (==)

groupCountVecBy :: (VG.Vector v a, VG.Vector v (a,Int)) =>
  (a -> a -> Bool) -> v a -> v (a,Int)
{-# INLINE groupCountVecBy #-}
groupCountVecBy eq
  = (VG.unstream .) $ (. VG.stream)
  $ VFB.inplace (VFSM.map (\(a,_,_,len) -> (a,len)) . groupIntvsStreamBy eq)
                VFBS.toMax

groupIntvsVecBy :: (VG.Vector v a, VG.Vector v (a,a,Int,Int)) =>
  (a -> a -> Bool) -> v a -> v (a,a,Int,Int)
{-# INLINE groupIntvsVecBy #-}
groupIntvsVecBy eq
  = VG.unstream . VFB.inplace (groupIntvsStreamBy eq) VFBS.toMax . VG.stream

groupIntvsVec :: (VG.Vector v a, VG.Vector v (a,a,Int,Int), Eq a)
  => v a -> v (a,a,Int,Int)
{-# INLINE groupIntvsVec #-}
groupIntvsVec = groupIntvsVecBy (==)

data GroupIntvsState a s = GCSInit s
                         | GCSAcc a a {-# UNPACK #-} !Int {-# UNPACK #-} !Int s
                         | GCSEnd

groupIntvsStreamBy :: Applicative m => (a -> a -> Bool) ->
  VFSM.Stream m a -> VFSM.Stream m (a,a,Int,Int)
{-# INLINE_FUSED groupIntvsStreamBy #-}
groupIntvsStreamBy eq (VFSM.Stream step0 s) = VFSM.Stream step1 $ GCSInit s
  where
    {-# INLINE_INNER step1 #-}
    step1 (GCSInit        s0) = (<$> step0 s0) $ \case
      VFSM.Yield a0 s1 -> VFSM.Skip $ GCSAcc a0 a0 0 1 s1
      VFSM.Skip     s1 -> VFSM.Skip $ GCSInit          s1
      VFSM.Done        -> VFSM.Done
    step1 (GCSAcc a0 a1 i0 len s0) = (<$> step0 s0) $ \case
      VFSM.Yield a2 s1
        | eq a1 a2  -> VFSM.Skip                 $ GCSAcc a0 a2 i0 (len+1) s1
        | otherwise -> VFSM.Yield (a0,a1,i0,len) $ GCSAcc a2 a2 (i0+len) 1 s1
      VFSM.Skip s1  -> VFSM.Skip                 $ GCSAcc a0 a1 1      len s1
      VFSM.Done     -> VFSM.Yield (a0,a1,i0,len)   GCSEnd
    step1 GCSEnd = pure VFSM.Done

mkErr :: String -> Err
{-# NOINLINE mkErr #-}
mkErr s = Err (error s)

newtype Err = Err { unErr :: forall a. a }

condError :: Err -> Bool -> a -> a
{-# INLINE_FUSED condError #-}
condError err test | test      = id
                   | otherwise = const $ unErr err

{-# RULES
"condError/True" forall err. condError err True = id
"condError/Data.Vector.Generic.New.new" forall err test gen.
  condError err test (VG.new gen) = VG.new (condError err test gen)
"condError/Data.Vector.Generic.New.unstream" forall err test bdl.
  condError err test (VGN.unstream bdl)
  = VGN.unstream (condErrorBundle err test bdl)
  #-}

condErrorBundle :: (Applicative m) => Err -> Bool ->
  VFBM.Bundle m v a -> VFBM.Bundle m v a
{-# INLINE_FUSED condErrorBundle #-}
condErrorBundle err test (VFBM.Bundle els chks vec sz)
  = VFBM.Bundle (condErrorStream err test els)
                (condErrorStream err test chks)
                (condError err test vec)
                sz

{-# RULES
"condErrorBundle/True" forall err. condErrorBundle err True = id
  #-}

condErrorStream :: (Applicative m) => Err -> Bool ->
  VFSM.Stream m a -> VFSM.Stream m a
{-# INLINE_FUSED condErrorStream #-}
condErrorStream err test (VFSM.Stream step0 t) = VFSM.Stream step1 Nothing
  where
    {-# INLINE_INNER step1 #-}
    step1 Nothing | test      = pure $ VFSM.Skip $ Just t
                  | otherwise = unErr err
    step1 (Just s0) = (<$> step0 s0) $ \case
      VFSM.Yield x s1 -> VFSM.Yield x $ Just s1
      VFSM.Skip    s1 -> VFSM.Skip    $ Just s1
      VFSM.Done       -> VFSM.Done

{-# RULES
"condErrorStream/True" forall err. condErrorStream err True = id
  #-}

{-
The code below is the modified version of what I borrowed from the modules
Data.Vector.Algorithms.Common/Optimal/Insertion/Heap/Intro
in the package vector-algorithms-0.8.0.1 on Hackage.

The copyright notice follows:

Copyright (c) 2015 Dan Doel
Copyright (c) 2015 Tim Baumann

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. Neither the name of the author nor the names of his contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

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

The code in Data.Array.Vector.Algorithms.Mutable.Optimal is adapted from a C
algorithm for the same purpose. The folowing is the copyright notice for said
C code:

Copyright (c) 2004 Paul Hsieh
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

    Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

    Neither the name of sorttest nor the names of its contributors may be
    used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-}
#define FILTER \
  | len < 2   = return ()\
  | len == 2  = vao_sort2ByOffset cmp a l\
  | len == 3  = vao_sort3ByOffset cmp a l\
  | len == 4  = vao_sort4ByOffset cmp a l
#define FILTERED FILTER | otherwise

-- | Sorts an entire array using the default ordering.
vait_sort :: (PrimMonad m, VGM.MVector v e, Ord e)
  => v (PrimState m) e -> m ()
vait_sort = vait_sortBy compare
{-# INLINABLE vait_sort #-}

-- | Sorts an entire array using a custom ordering.
vait_sortBy :: (PrimMonad m, VGM.MVector v e)
  => Comparison e -> v (PrimState m) e -> m ()
vait_sortBy cmp a = vait_sortByBounds cmp a 0 (VGM.length a)
{-# INLINE vait_sortBy #-}

-- | Sorts a portion of an array [l,u) using a custom ordering
vait_sortByBounds
  :: (PrimMonad m, VGM.MVector v e)
  => Comparison e
  -> v (PrimState m) e
  -> Int -- ^ lower index, l
  -> Int -- ^ upper index, u
  -> m ()
vait_sortByBounds cmp a l u FILTERED
  = vait_introsort cmp a (vait_ilg len) l u
 where len = u - l
{-# INLINE vait_sortByBounds #-}

-- Internal version of the introsort loop which allows partial
-- sort functions to call with a specified bound on iterations.
vait_introsort :: (PrimMonad m, VGM.MVector v e)
   => Comparison e -> v (PrimState m) e -> Int -> Int -> Int -> m ()
vait_introsort cmp a i l u = sort i l u >> vais_sortByBounds cmp a l u
 where
 sort 0 l u = vah_sortByBounds cmp a l u
 sort d l u
   | len < vait_threshold = return ()
   | otherwise = do
       vao_sort3ByIndex cmp a c l (u-1)
        -- sort the median into the lowest position
       p <- VGM.unsafeRead a l
       mid <- vait_partitionBy cmp a p (l+1) u
       VGM.unsafeSwap a l (mid - 1)
       sort (d-1) mid u
       sort (d-1) l   (mid - 1)
  where
    len = u - l
    c   = vac_midPoint u l
{-# INLINE vait_introsort #-}

vait_partitionBy :: forall m v e. (PrimMonad m, VGM.MVector v e)
  => Comparison e -> v (PrimState m) e -> e -> Int -> Int -> m Int
vait_partitionBy cmp a = partUp
 where
 partUp :: e -> Int -> Int -> m Int
 partUp p l u
   | l < u = do
       e <- VGM.unsafeRead a l
       case cmp e p of
         LT -> partUp p (l+1) u
         _  -> partDown p l (u-1)
   | otherwise = return l

 partDown :: e -> Int -> Int -> m Int
 partDown p l u
   | l < u = do
       e <- VGM.unsafeRead a u
       case cmp p e of
         LT -> partDown p l (u-1)
         _  -> VGM.unsafeSwap a l u >> partUp p (l+1) u
   | otherwise = return l
{-# INLINE vait_partitionBy #-}

vait_ilg :: Int -> Int
vait_ilg !m = 2 * (finiteBitSize m - countLeadingZeros m - 1)

vait_threshold :: Int
vait_threshold = 18
{-# INLINE vait_threshold #-}

vah_sortByBounds :: (PrimMonad m, VGM.MVector v e)
  => Comparison e -> v (PrimState m) e -> Int -> Int -> m ()
vah_sortByBounds cmp a l u FILTERED
  = vah_heapify cmp a l u >> vah_sortHeap cmp a l (l+4) u
    >> vao_sort4ByOffset cmp a l
 where len = u - l
{-# INLINE vah_sortByBounds #-}

vah_heapify :: (PrimMonad m, VGM.MVector v e) => Comparison e
  -> v (PrimState m) e -> Int -> Int -> m ()
vah_heapify cmp a l u = loop $ (len - 1) `shiftR` 2
  where
    len = u - l
    loop k | k < 0 = return ()
    loop k = VGM.unsafeRead a (l+k) >>= \e ->
      vah_siftByOffset cmp a e l k len >> loop (k - 1)
{-# INLINE vah_heapify #-}

vah_pop :: (PrimMonad m, VGM.MVector v e)
  => Comparison e -> v (PrimState m) e -> Int -> Int -> m ()
vah_pop cmp a l u = vah_popTo cmp a l u u
{-# INLINE vah_pop #-}

vah_popTo :: (PrimMonad m, VGM.MVector v e) => Comparison e
  -> v (PrimState m) e -> Int -> Int -> Int -> m ()
vah_popTo cmp a l u t = do
  al <- VGM.unsafeRead a l
  at <- VGM.unsafeRead a t
  VGM.unsafeWrite a t al
  vah_siftByOffset cmp a at l 0 (u - l)
{-# INLINE vah_popTo #-}

vah_sortHeap :: (PrimMonad m, VGM.MVector v e) => Comparison e
  -> v (PrimState m) e -> Int -> Int -> Int -> m ()
vah_sortHeap cmp a l m u = loop (u-1) >> VGM.unsafeSwap a l m
 where
 loop k
   | m < k     = vah_pop cmp a l k >> loop (k-1)
   | otherwise = return ()
{-# INLINE vah_sortHeap #-}

vah_siftByOffset :: (PrimMonad m, VGM.MVector v e)
  => Comparison e -> v (PrimState m) e -> e -> Int -> Int -> Int -> m ()
vah_siftByOffset cmp a val off start len = sift val start len
 where
 sift val root len
   | child < len = do
       (child', ac) <- vah_maximumChild cmp a off child len
       case cmp val ac of
         LT -> VGM.unsafeWrite a (root + off) ac >> sift val child' len
         _  -> VGM.unsafeWrite a (root + off) val
   | otherwise = VGM.unsafeWrite a (root + off) val
  where child = root `shiftL` 2 + 1
{-# INLINE vah_siftByOffset #-}

vah_maximumChild :: (PrimMonad m, VGM.MVector v e)
  => Comparison e -> v (PrimState m) e -> Int -> Int -> Int -> m (Int,  e)
vah_maximumChild cmp a off child1 len
  | child4 < len = do
      ac1 <- VGM.unsafeRead a (child1 + off)
      ac2 <- VGM.unsafeRead a (child2 + off)
      ac3 <- VGM.unsafeRead a (child3 + off)
      ac4 <- VGM.unsafeRead a (child4 + off)
      return $ case cmp ac1 ac2 of
        LT -> case cmp ac2 ac3 of
          LT -> case cmp ac3 ac4 of
            LT -> (child4, ac4)
            _  -> (child3, ac3)
          _  -> case cmp ac2 ac4 of
            LT -> (child4, ac4)
            _  -> (child2, ac2)
        _  -> case cmp ac1 ac3 of
          LT -> case cmp ac3 ac4 of
            LT -> (child4, ac4)
            _  -> (child3, ac3)
          _  -> case cmp ac1 ac4 of
            LT -> (child4, ac4)
            _  -> (child1, ac1)
  | child3 < len = do
      ac1 <- VGM.unsafeRead a (child1 + off)
      ac2 <- VGM.unsafeRead a (child2 + off)
      ac3 <- VGM.unsafeRead a (child3 + off)
      return $ case cmp ac1 ac2 of
        LT -> case cmp ac2 ac3 of
          LT -> (child3, ac3)
          _  -> (child2, ac2)
        _  -> case cmp ac1 ac3 of
          LT -> (child3, ac3)
          _  -> (child1, ac1)
  | child2 < len = do
      ac1 <- VGM.unsafeRead a (child1 + off)
      ac2 <- VGM.unsafeRead a (child2 + off)
      return $ case cmp ac1 ac2 of
        LT -> (child2, ac2)
        _  -> (child1, ac1)
  | otherwise    = do
      ac1 <- VGM.unsafeRead a (child1 + off); return (child1, ac1)
 where
 child2 = child1 + 1
 child3 = child1 + 2
 child4 = child1 + 3
{-# INLINE vah_maximumChild #-}

vais_sortByBounds :: (PrimMonad m, VGM.MVector v e)
  => Comparison e -> v (PrimState m) e -> Int -> Int -> m ()
vais_sortByBounds cmp a l u FILTERED
  = vao_sort4ByOffset cmp a l >> vais_sortByBounds' cmp a l (l + 4) u
 where len = u - l
{-# INLINE vais_sortByBounds #-}

vais_sortByBounds' :: (PrimMonad m, VGM.MVector v e)
  => Comparison e -> v (PrimState m) e -> Int -> Int -> Int -> m ()
vais_sortByBounds' cmp a l m u = sort m
 where
 sort i
   | i < u     = do
       v <- VGM.unsafeRead a i
       vais_insert cmp a l v i
       sort (i+1)
   | otherwise = return ()
{-# INLINE vais_sortByBounds' #-}

vais_insert :: (PrimMonad m, VGM.MVector v e)
  => Comparison e -> v (PrimState m) e -> Int -> e -> Int -> m ()
vais_insert cmp a l = loop
 where
 loop val j
   | j <= l    = VGM.unsafeWrite a l val
   | otherwise = do
       e <- VGM.unsafeRead a (j - 1)
       case cmp val e of
         LT -> VGM.unsafeWrite a j e >> loop val (j - 1)
         _  -> VGM.unsafeWrite a j val
{-# INLINE vais_insert #-}

#define vec_writes2(a,v,w)\
  (VGM.unsafeWrite a v >> VGM.unsafeWrite a w)
#define vec_writes3(a,v,w,x)\
  (VGM.unsafeWrite a v >> vec_writes2(a,w,x))
#define vec_writes4(a,v,w,x,y)\
  (VGM.unsafeWrite a v >> vec_writes3(a,w,x,y))

vao_sort2ByOffset :: (PrimMonad m, VGM.MVector v e)
  => Comparison e -> v (PrimState m) e -> Int -> m ()
vao_sort2ByOffset cmp a off = vao_sort2ByIndex cmp a off (off + 1)
{-# INLINABLE vao_sort2ByOffset #-}

vao_sort2ByIndex :: (PrimMonad m, VGM.MVector v e)
  => Comparison e -> v (PrimState m) e -> Int -> Int -> m ()
vao_sort2ByIndex cmp a i j = do
  a0 <- VGM.unsafeRead a i
  a1 <- VGM.unsafeRead a j
  case cmp a0 a1 of
    GT -> vec_writes2(a,i a1,j a0)
    _  -> return ()
{-# INLINABLE vao_sort2ByIndex #-}

vao_sort3ByOffset :: (PrimMonad m, VGM.MVector v e)
  => Comparison e -> v (PrimState m) e -> Int -> m ()
vao_sort3ByOffset cmp a off = vao_sort3ByIndex cmp a off (off + 1) (off + 2)
{-# INLINABLE vao_sort3ByOffset #-}

vao_sort3ByIndex :: (PrimMonad m, VGM.MVector v e)
  => Comparison e -> v (PrimState m) e -> Int -> Int -> Int -> m ()
vao_sort3ByIndex cmp a i j k = do
  a0 <- VGM.unsafeRead a i
  a1 <- VGM.unsafeRead a j
  a2 <- VGM.unsafeRead a k
  case cmp a0 a1 of
    GT -> case cmp a0 a2 of
      GT -> case cmp a2 a1 of
        LT -> vec_writes2(a,i a2,{-j a1-}k a0)
        _  -> vec_writes3(a,i a1,j a2,k a0)
      _  -> vec_writes2(a,i a1,j a0{-k a2-})
    _  -> case cmp a1 a2 of
      GT -> case cmp a0 a2 of
        GT -> vec_writes3(a,i a2,j a0,k a1)
        _  -> vec_writes2(a,{-i a0-}j a2,k a1)
      _  -> return ()
{-# INLINABLE vao_sort3ByIndex #-}

vao_sort4ByOffset :: (PrimMonad m, VGM.MVector v e)
  => Comparison e -> v (PrimState m) e -> Int -> m ()
vao_sort4ByOffset cmp a off
  = vao_sort4ByIndex cmp a off (off + 1) (off + 2) (off + 3)
{-# INLINABLE vao_sort4ByOffset #-}

vao_sort4ByIndex :: (PrimMonad m, VGM.MVector v e)
  => Comparison e -> v (PrimState m) e -> Int -> Int -> Int -> Int -> m ()
vao_sort4ByIndex cmp a i j k l = do
  a0 <- VGM.unsafeRead a i
  a1 <- VGM.unsafeRead a j
  a2 <- VGM.unsafeRead a k
  a3 <- VGM.unsafeRead a l
  case cmp a0 a1 of
    GT -> case cmp a0 a2 of
      GT -> case cmp a1 a2 of
        GT -> case cmp a1 a3 of
          GT -> case cmp a2 a3 of
            GT -> vec_writes4(a,i a3,j a2,k a1,l a0)
            _  -> vec_writes4(a,i a2,j a3,k a1,l a0)
          _  -> case cmp a0 a3 of
            GT -> vec_writes3(a,i a2,{-j a1-}k a3,l a0)
            _  -> vec_writes2(a,i a2,{-j a1-}k a0{-l a3-})
        _ -> case cmp a2 a3 of
          GT -> case cmp a1 a3 of
            GT -> vec_writes2(a,i a3,{-j a1;k a2-}l a0)
            _  -> vec_writes3(a,i a1,j a3,{-k a2-}l a0)
          _  -> case cmp a0 a3 of
            GT -> vec_writes4(a,i a1,j a2,k a3,l a0)
            _  -> vec_writes3(a,i a1,j a2,k a0{-l a3-})
      _  -> case cmp a0 a3 of
        GT -> case cmp a1 a3 of
          GT -> vec_writes3(a,i a3,{-j a1-}k a0,l a2)
          _  -> vec_writes4(a,i a1,j a3,k a0,l a2)
        _  -> case cmp a2 a3 of
          GT -> vec_writes4(a,i a1,j a0,k a3,l a2)
          _  -> vec_writes2(a,i a1,j a0{-k a2;l a3-})
    _  -> case cmp a1 a2 of
      GT -> case cmp a0 a2 of
        GT -> case cmp a0 a3 of
          GT -> case cmp a2 a3 of
            GT -> vec_writes4(a,i a3,j a2,k a0,l a1)
            _  -> vec_writes4(a,i a2,j a3,k a0,l a1)
          _  -> case cmp a1 a3 of
            GT -> vec_writes4(a,i a2,j a0,k a3,l a1)
            _  -> vec_writes3(a,i a2,j a0,k a1{-l a3-})
        _  -> case cmp a2 a3 of
          GT -> case cmp a0 a3 of
            GT -> vec_writes3(a,i a3,j a0,{-k a2-}l a1)
            _  -> vec_writes2(a,{-i a0-}j a3,{-k a2-}l a1)
          _  -> case cmp a1 a3 of
            GT -> vec_writes3(a,{-i a0-}j a2,k a3,l a1)
            _  -> vec_writes2(a,{-i a0-}j a2,k a1{-l a3-})
      _  -> case cmp a1 a3 of
        GT -> case cmp a0 a3 of
          GT -> vec_writes4(a,i a3,j a0,k a1,l a2)
          _  -> vec_writes3(a,{-i a0-}j a3,k a1,l a2)
        _  -> case cmp a2 a3 of
          GT -> vec_writes2(a,{-i a0;j a1-}k a3,l a2)
          _  -> return () {-i a0;j a1;k a2;l a3-}
{-# INLINABLE vao_sort4ByIndex #-}

-- | A type of comparisons between two values of a given type.
type Comparison e = e -> e -> Ordering

vac_midPoint :: Int -> Int -> Int
vac_midPoint a b =
  fromIntegral $ (toWord a + toWord b) `div` 2
  where
    toWord :: Int -> Word
    toWord = fromIntegral
{-# INLINE vac_midPoint #-}

#undef vec_writes2
#undef vec_writes3
#undef vec_writes4
#undef FILTERED
#undef FILTER

{- Borrowed code end -}

data FixedModulus

instance HasWord32 FixedModulus where
  {-# INLINE CONLIKE word32Val #-}
  word32Val = const 1000000007 -- 10^9 + 7

type RemF = Rem FixedModulus

pxyF :: Proxy FixedModulus
pxyF = Proxy
remF :: Word32 -> RemF
{-# INLINE CONLIKE remF #-}
remF = Rem

newtype Magic r = Magic (forall (m :: *). HasWord32 m => Proxy m -> r)

{-# INLINE reifyWord32 #-}
reifyWord32 :: forall a. Word32 ->
  (forall (m :: *). HasWord32 m => Proxy m -> a) -> a
reifyWord32 v f = unsafeCoerce (Magic f :: Magic a) (const v) Proxy

newtype Rem m = Rem {unRem :: Word32} deriving (Eq)

withTypeArgOf :: c a -> d a -> c a
{-# INLINE CONLIKE withTypeArgOf #-}
withTypeArgOf = const

proxyFor :: c a -> Proxy a
{-# INLINE CONLIKE proxyFor #-}
proxyFor = const Proxy

withProxy :: (Proxy m -> c m) -> c m
{-# INLINE withProxy #-}
withProxy f = f Proxy

remP :: Proxy m -> Word32 -> Rem m
{-# INLINE CONLIKE remP #-}
remP = const Rem

{-# INLINE modulus32 #-}
modulus32 :: HasWord32 m => Rem m -> Word32
modulus32 x = word32Val $ proxyFor x

class HasWord32 m where
  word32Val :: Proxy m -> Word32

instance Show (Rem m) where
  {-# INLINE showsPrec #-}
  showsPrec = coerce `asTypeOf` (\f p (Rem v) -> f p v) $ showsPrec

negRem :: HasWord32 m => Rem m -> Rem m
{-# INLINE negRem #-}
negRem x0@(Rem x)
  | x == 0 = Rem 0
  | otherwise = Rem $ modulus32 x0 - x

addRem, subRem, multRem
  :: HasWord32 m => Rem m -> Rem m -> Rem m
{-# INLINE subRem #-}
subRem x0@(Rem x) (Rem y) = Rem $ x-y + if x < y then modulus32 x0 else 0
{-# INLINE addRem #-}
addRem x0@(Rem x) (Rem y) = Rem $ x-negy + if x < negy then m else 0
  where m = modulus32 x0; negy = m-y
{-# INLINE multRem #-}
multRem x0@(Rem x) (Rem y)
  = Rem $ toW32 $ (toW64 x * toW64 y) `rem` toW64 (modulus32 x0)

{-# INLINE fromIntegerRem #-}
fromIntegerRem :: (HasWord32 m) => Integer -> Rem m
fromIntegerRem x = withProxy $ Rem . fromInteger . mod x . toInteger . word32Val

{-# INLINE signumRem #-}
signumRem :: (HasWord32 m) => Rem m -> Rem m
signumRem = (\case True -> Rem 0; False -> Rem 1) . (== Rem 0)

instance HasWord32 m => Num (Rem m) where
  {-# INLINE negate #-}
  negate = negRem
  {-# INLINE (-) #-}
  (-) = subRem
  {-# INLINE (+) #-}
  (+) = addRem
  {-# INLINE (*) #-}
  (*) = multRem
  {-# INLINE fromInteger #-}
  fromInteger = fromIntegerRem
  {-# INLINE abs #-}
  abs = id
  {-# INLINE signum #-}
  signum = signumRem

recipRem :: HasWord32 m => Rem m -> Rem m
{-# INLINE recipRem #-}
recipRem = \x -> x ^ (modulus32 x - 2)

-- works only for primes
instance HasWord32 m => Fractional (Rem m) where
  {-# INLINE recip #-}
  recip = recipRem
  fromRational q = fromInteger (numerator q) / fromInteger (denominator q)

newtype instance VU.Vector (Rem m)
  = VRem { unVRem :: VU.Vector Word32 }
newtype instance VUM.MVector s (Rem m)
  = VMRem { unVMRem :: VUM.MVector s Word32 }
instance VUM.Unbox (Rem m)

instance VGM.MVector VUM.MVector (Rem m) where
  {-# INLINE basicLength #-}
  basicLength = coerce `asTypeOf` (. unVMRem) $ VGM.basicLength
  {-# INLINE basicUnsafeSlice #-}
  basicUnsafeSlice
    = coerce `asTypeOf` (\f x y (VMRem v) -> VMRem $ f x y v)
      $ VGM.basicUnsafeSlice
  {-# INLINE basicOverlaps #-}
  basicOverlaps = coerce `asTypeOf` (`on` unVMRem) $ VGM.basicOverlaps
  {-# INLINE basicUnsafeNew #-}
  basicUnsafeNew = fmap (coerce `asTypeOf` VMRem) . VGM.basicUnsafeNew
  {-# INLINE basicInitialize #-}
  basicInitialize = coerce `asTypeOf` (. unVMRem) $ VGM.basicInitialize
  {-# INLINE basicUnsafeReplicate #-}
  basicUnsafeReplicate !n
    = fmap (coerce `asTypeOf` VMRem) . VGM.basicUnsafeReplicate n
    . unRem
  {-# INLINE basicUnsafeRead #-}
  basicUnsafeRead (VMRem v) i = coerce `asTypeOf` Rem <$>
                                VGM.basicUnsafeRead v i
  {-# INLINE basicUnsafeWrite #-}
  basicUnsafeWrite = coerce `asTypeOf` (\f (VMRem v) n (Rem x) -> f v n x)
                     $ VGM.basicUnsafeWrite
  {-# INLINE basicClear #-}
  basicClear = coerce `asTypeOf` (. unVMRem) $ VGM.basicClear
  {-# INLINE basicSet #-}
  basicSet = coerce `asTypeOf` (\f (VMRem v) (Rem x) -> f v x) $ VGM.basicSet
  {-# INLINE basicUnsafeCopy #-}
  basicUnsafeCopy = coerce `asTypeOf` (`on` unVMRem) $ VGM.basicUnsafeCopy
  {-# INLINE basicUnsafeMove #-}
  basicUnsafeMove = coerce `asTypeOf` (`on` unVMRem) $ VGM.basicUnsafeMove
  {-# INLINE basicUnsafeGrow #-}
  basicUnsafeGrow (VMRem v) !n
    = fmap (coerce `asTypeOf` VMRem) $ VGM.basicUnsafeGrow v n

instance VG.Vector VU.Vector (Rem m) where
  {-# INLINE basicUnsafeFreeze #-}
  basicUnsafeFreeze (VMRem v)
    = (coerce `asTypeOf` VRem) <$> VG.basicUnsafeFreeze v
  {-# INLINE basicUnsafeThaw #-}
  basicUnsafeThaw (VRem v)
    = (coerce `asTypeOf` VMRem) <$> VG.basicUnsafeThaw v
  {-# INLINE basicLength #-}
  basicLength = coerce `asTypeOf` (. unVRem) $ VG.basicLength
  {-# INLINE basicUnsafeSlice #-}
  basicUnsafeSlice
    = coerce `asTypeOf` (\f i l (VRem v) -> VRem $ f i l v)
      $ VG.basicUnsafeSlice
  {-# INLINE basicUnsafeIndexM #-}
  basicUnsafeIndexM (VRem !v) !i = coerce <$> VG.basicUnsafeIndexM v i
  {-# INLINE basicUnsafeCopy #-}
  basicUnsafeCopy
    = coerce `asTypeOf` (\f (VMRem mv) (VRem v) -> f mv v)
      $ VG.basicUnsafeCopy
  {-# INLINE elemseq #-}
  elemseq = const seq

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

IL(putBuilder) = BSB.hPutBuilder stdout

printVecInLines, printVecInSpcSepLn ::
  (VG.Vector v a, ShowAsBuilder a) => v a -> IO ()
IL(printVecInLines) = putBuilder . v2BLines
IL(printVecInSpcSepLn) = putBuilder . v2BSpcSepLn

class ShowAsBuilder a where
  showAsBuilder :: a -> BSB.Builder
  default showAsBuilder :: (Show a) => a -> BSB.Builder
  IL(showAsBuilder) = BSB.string8 . show

-- Inconsistent with show
instance (ShowAsBuilder a, VG.Vector v a) => ShowAsBuilder (v a) where
  IL(showAsBuilder) = v2BSpcSep

#define INS(t,f) instance ShowAsBuilder t where { IL(showAsBuilder)=f }
INS(Int,BSB.intDec)
INS(Int8,BSB.int8Dec)
INS(Int16,BSB.int16Dec)
INS(Int32,BSB.int32Dec)
INS(Int64,BSB.int64Dec)
INS(Word,BSB.wordDec)
INS(Word8,BSB.word8Dec)
INS(Word16,BSB.word16Dec)
INS(Word32,BSB.word32Dec)
INS(Word64,BSB.word64Dec)
INS(Integer,BSB.integerDec)
INS(Float,BSB.floatDec)
INS(Double,BSB.doubleDec)
-- INS(String,BSB.string8) -- Inconsistent with Show
-- INS(BS.ByteString,BSB.byteString) -- Inconsistent with Show
-- INS(BSL.ByteString,BSB.lazyByteString) -- Inconsisitent with Show
#undef INS

-- Inconsistent with Show
instance (ShowAsBuilder a, ShowAsBuilder b) => ShowAsBuilder (a,b) where
  IL(showAsBuilder) = showTupAsBuilder
instance (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c) =>
  ShowAsBuilder (a,b,c) where
  IL(showAsBuilder) = showTup3AsBuilder
instance (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c, ShowAsBuilder d) =>
  ShowAsBuilder (a,b,c,d) where
  IL(showAsBuilder) = showTup4AsBuilder

IL(showTupAsBuilderWith)
  :: (a -> BSB.Builder) -> (b -> BSB.Builder) -> (a,b) -> BSB.Builder
showTupAsBuilderWith showA showB
  = \(a,b) -> (showA a <>) $ BSB.char7 ' ' <> showB b
IL(showTupAsBuilder) :: (ShowAsBuilder a, ShowAsBuilder b)
  => (a,b) -> BSB.Builder
showTupAsBuilder = showTupAsBuilderWith showAsBuilder showAsBuilder

IL(showTup3AsBuilderWith) :: (a -> BSB.Builder) -> (b -> BSB.Builder) ->
  (c -> BSB.Builder) -> (a,b,c) -> BSB.Builder
showTup3AsBuilderWith showA showB showC
  = \(a,b,c) -> (showA a <>) $ (BSB.char7 ' ' <>) $ (showB b <>)
                $ (BSB.char7 ' ' <>) $ showC c
IL(showTup3AsBuilder) :: (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c)
  => (a,b,c) -> BSB.Builder
showTup3AsBuilder
  = showTup3AsBuilderWith showAsBuilder showAsBuilder showAsBuilder

IL(showTup4AsBuilderWith) :: (a -> BSB.Builder) -> (b -> BSB.Builder) ->
  (c -> BSB.Builder) -> (d -> BSB.Builder) -> (a,b,c,d) -> BSB.Builder
showTup4AsBuilderWith showA showB showC showD
  = \(a,b,c,d) -> (showA a <>) $ (BSB.char7 ' ' <>)
                  $ showTup3AsBuilderWith showB showC showD (b,c,d)
IL(showTup4AsBuilder) ::
  (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c, ShowAsBuilder d) =>
  (a,b,c,d) -> BSB.Builder
showTup4AsBuilder = showTup4AsBuilderWith showAsBuilder showAsBuilder
                    showAsBuilder showAsBuilder

v2BSpcSepLn, v2BSpcSep, v2BConcat, v2BLines ::
  (VG.Vector v a, ShowAsBuilder a)
  => v a -> BSB.Builder
IL(v2BSpcSepLn) = v2BSpcSepLnWith showAsBuilder
IL(v2BSpcSep) = v2BSpcSepWith showAsBuilder
IL(v2BConcat) = v2BConcatWith showAsBuilder
IL(v2BLines) = v2BLinesWith showAsBuilder

v2BSpcSepLnWith, v2BSpcSepWith, v2BConcatWith, v2BLinesWith ::
  (VG.Vector v a)
  => (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
IL(v2BSpcSepLnWith) = v2BSpcSepPostfWith $ BS.singleton '\n'
IL(v2BSpcSepWith) = v2BSpcSepPostfWith BS.empty
IL(v2BConcatWith) showFct = VG.foldr ((<>) . showFct) mempty
IL(v2BLinesWith) showFct
  = VG.foldr (\ a -> (showFct a <>) . (BSB.char7 '\n' <>)) mempty

v2BSpcSepPostf :: (VG.Vector v a, ShowAsBuilder a)
  => BS.ByteString -- ^ postfix
  -> v a -> BSB.Builder
IL(v2BSpcSepPostf) = (`v2BSpcSepPostfWith` showAsBuilder)

v2BSpcSepPostfWith :: (VG.Vector v a)
  => BS.ByteString -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
IL(v2BSpcSepPostfWith) = vecToBuilder BS.empty $ BS.singleton ' '

IL(vecToBuilder) :: (VG.Vector v a)
  => BS.ByteString -- ^ prefix
  -> BS.ByteString -- ^ separator
  -> BS.ByteString -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
vecToBuilder !prefix !separator !postfix
  = vecToBuilder_ (BSB.byteString prefix)
                  (BSB.byteString separator)
                  (BSB.byteString postfix)

IL(vecToBuilder_) :: (VG.Vector v a)
  => BSB.Builder -- ^ prefix
  -> BSB.Builder -- ^ separator
  -> BSB.Builder -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
vecToBuilder_ !prefix !separator !postfix showFct = \vec -> prefix <>
  VG.foldr
  (\ a rest !prefx -> prefx <> (showFct a <> rest separator))
  (const postfix) vec mempty

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

IL(readLnWith) :: StateT BS.ByteString Maybe a -> IO a
readLnWith parser = fromJust . evalStateT parser <$> BS.getLine
IL(readContentWith) :: StateT BSL.ByteString Maybe a -> IO a
readContentWith parser = fromJust . evalStateT parser <$> BSL.getContents

IL(getVecGLn) :: (VG.Vector v a) =>
  Int -> StateT BS.ByteString Maybe a -> IO (v a)
getVecGLn n s = VG.unfoldrN n (runStateT s) <$> BS.getLine
IL(getVecGRest) :: (VG.Vector v a) =>
  Int -> StateT BSL.ByteString Maybe a -> IO (v a)
getVecGRest n s = VG.unfoldrN n (runStateT s) <$> BSL.getContents
IL(getVecLn) :: Int -> StateT BS.ByteString Maybe a -> IO (V.Vector a)
getVecLn = getVecGLn
IL(getVecRest) :: Int -> StateT BSL.ByteString Maybe a -> IO (V.Vector a)
getVecRest = getVecGRest
IL(getVecULn) :: (VU.Unbox a) =>
  Int -> StateT BS.ByteString Maybe a -> IO (VU.Vector a)
getVecULn = getVecGLn
IL(getVecURest) :: (VU.Unbox a) =>
  Int -> StateT BSL.ByteString Maybe a -> IO (VU.Vector a)
getVecURest = getVecGRest

IL(rIntL) :: StateT BSL.ByteString Maybe Int
rIntL = skipSpecialL $ StateT BSL.readInt
IL(rIntS) :: StateT BS.ByteString Maybe Int
rIntS = skipSpecialS $ StateT BS.readInt
IL(rStrL) :: (MonadState BSL.ByteString m) => m BS.ByteString
rStrL = skipSpecialL $ BSL.toStrict <$> state (BSL.span (>='!'))
IL(rStrS) :: (MonadState BS.ByteString m) => m BS.ByteString
rStrS = skipSpecialS $ state $ BS.span (>='!')
IL(rCharL) :: StateT BSL.ByteString Maybe Char
rCharL = StateT BSL.uncons
IL(rCharS) :: StateT BS.ByteString Maybe Char
rCharS = StateT BS.uncons
IL(dropSpecialL) :: (MonadState BSL.ByteString m) => m ()
dropSpecialL = modify $ BSL.dropWhile (<'!')
IL(dropSpecialS) :: (MonadState BS.ByteString m) => m ()
dropSpecialS = modify $ BS.dropWhile (<'!')
IL(skipSpecialL) :: (MonadState BSL.ByteString m) => m a -> m a
skipSpecialL = (dropSpecialL *>)
IL(skipSpecialS) :: (MonadState BS.ByteString m) => m a -> m a
skipSpecialS = (dropSpecialS *>)

IL(linToMat) :: (VG.Vector v a) => Int -> Int -> v a -> V.Vector (v a)
linToMat h w lvec = vEvalElemsId $ V.generate h (\i -> VG.slice (i*w) w lvec)

IL(mLinToMat) :: (VGM.MVector v a) => Int -> Int -> v s a -> V.Vector (v s a)
mLinToMat h w lvec = vEvalElemsId $ V.generate h (\i -> VGM.slice (i*w) w lvec)

IL(unsafeAddrToSVec) :: Int -> Addr# -> VS.Vector Word8
unsafeAddrToSVec n addr
  = (`VS.unsafeFromForeignPtr0` n)
    $ unsafeDupablePerformIO
    $ newForeignPtr_ $ Ptr addr

IL(vEvalElemsId) :: (VG.Vector v a) => v a -> v a
vEvalElemsId = vMapFoldl (\ !_ !x -> (x,())) ()

IL(vEvalElems) :: (VG.Vector v a) => v a -> ()
vEvalElems = VG.foldl' (\ !_ !_ -> ()) ()

IL(vMapFoldl) :: (VG.Vector v b, VG.Vector v c) =>
  (a -> b -> (c,a)) -> a -> v b -> v c
vMapFoldl f a
  = VG.unstream . VFB.inplace (streamMapFoldl f a) id . VG.stream

streamMapFoldl :: (Functor m) =>
  (a -> b -> (c,a)) -> a -> VFSM.Stream m b -> VFSM.Stream m c
{-# INLINE_FUSED streamMapFoldl #-}
streamMapFoldl f a (VFSM.Stream step s) = VFSM.Stream step1 (a,s)
  where
    {-# INLINE_INNER step1 #-}
    step1 (a0,s0) =  (<$> step s0) $ \r -> case r of
      VFSM.Yield b s1 -> case f a0 b of (c,a1) -> VFSM.Yield c (a1,s1)
      VFSM.Skip    s1 -> VFSM.Skip (a0,s1)
      VFSM.Done       -> VFSM.Done

IL(svecToBS) :: VS.Vector Word8 -> BS.ByteString
svecToBS vec = BSU.fromForeignPtr ptr 0 len
  where (ptr, len) = VS.unsafeToForeignPtr0 vec

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

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

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

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

#undef IL


main = ceiling.(/ 2) <$> readLn >>= print

Score : 100 points

Problem Statement

Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper.

At least how many sheets of paper does he need?

Constraints

N is an integer.

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

5

Sample Output 1

3

By printing the 1-st, 2-nd pages on the 1-st sheet, 3-rd and 4-th pages on the 2-nd sheet, and 5-th page on the 3-rd sheet, we can print all the data on 3 sheets of paper.

Sample Input 2

2

Sample Output 2

1

Sample Input 3

100

Sample Output 3

50


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

solve :: Int -> Int
solve n = (n + 1) `div` 2


import Control.Monad

main = do

  a <- replicateM 3 $ map read . words <$> getLine

  n <- readLn

  b <- replicateM n readLn

  putStr $ solve a b

solve :: [[Int]] -> [Int] -> String

solve a' b

  | any eval line = "Yes"

  | otherwise = "No"

  where

    a = concat a'

    line = [0, 4, 8] : [2, 4, 6]

         : [[i .. i+2] | i <- [0, 3, 6]]

        ++ [[i, i+3, i+6] | i <- [0 .. 2]]

    eval = all (flip elem b) . map (a !!)

Score : 200 points

Problem Statement

We have a bingo card with a 3\times3 grid. The square at the i-th row from the top and the j-th column from the left contains the number A_{i, j}.

The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet contains some of those numbers, we will mark them on our sheet.

Determine whether we will have a bingo when the N numbers are chosen, that is, the sheet will contain three marked numbers in a row, column, or diagonal.

Constraints

All values in input are integers.

1 \leq A_{i, j} \leq 100

A_{i_1, j_1} \neq A_{i_2, j_2} ((i_1, j_1) \neq (i_2, j_2))

1 \leq N \leq 10

1 \leq b_i \leq 100

b_i \neq b_j (i \neq j)

Input

Input is given from Standard Input in the following format:

A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N

Output

If we will have a bingo, print Yes; otherwise, print No.

Sample Input 1

84 97 66
79 89 11
61 59 7
7
89
7
87
79
24
84
30

Sample Output 1

Yes

We will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal from the top-left to the bottom-right.

Sample Input 2

41 7 46
26 89 2
78 92 8
5
6
45
16
57
17

Sample Output 2

No

We will mark nothing.

Sample Input 3

60 88 34
92 41 43
65 73 48
10
60
43
88
11
48
73
65
41
92
34

Sample Output 3

Yes

We will mark all the squares.


import Data.Graph

main = interact $ put . sub . get

get = fmap (fmap read . words) . lines

put = unwords . fmap show

sub ([n,m,k]:as) = sol n (ps $ take m as) (ps $ drop m as)

ps [] = []
ps ([a,b]:abs) = (a,b):(b,a):ps abs

sol n es bs = length . f <$> vertices g
  where
  g = buildG (1,n) es
  f i = [(i,j) | j <- reachable g i, i/=j, (i,j) `notElem` es, (i,j) `notElem` bs]

Score : 400 points

Problem Statement

An SNS has N users - User 1, User 2, \cdots, User N.

Between these N users, there are some relationships - M friendships and K blockships.

For each i = 1, 2, \cdots, M, there is a bidirectional friendship between User A_i and User B_i.

For each i = 1, 2, \cdots, K, there is a bidirectional blockship between User C_i and User D_i.

We define User a to be a friend candidate for User b when all of the following four conditions are satisfied:

a \neq b.

There is not a friendship between User a and User b.

There is not a blockship between User a and User b.

There exists a sequence c_0, c_1, c_2, \cdots, c_L consisting of integers between 1 and N (inclusive) such that c_0 = a, c_L = b, and there is a friendship between User c_i and c_{i+1} for each i = 0, 1, \cdots, L - 1.

For each user i = 1, 2, ... N, how many friend candidates does it have?

Constraints

All values in input are integers.

2 ≤ N ≤ 10^5

0 \leq M \leq 10^5

0 \leq K \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

1 \leq C_i, D_i \leq N

C_i \neq D_i

(A_i, B_i) \neq (A_j, B_j) (i \neq j)

(A_i, B_i) \neq (B_j, A_j)

(C_i, D_i) \neq (C_j, D_j) (i \neq j)

(C_i, D_i) \neq (D_j, C_j)

(A_i, B_i) \neq (C_j, D_j)

(A_i, B_i) \neq (D_j, C_j)

Input

Input is given from Standard Input in the following format:

N M K
A_1 B_1
\vdots
A_M B_M
C_1 D_1
\vdots
C_K D_K

Output

Print the answers in order, with space in between.

Sample Input 1

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

Sample Output 1

0 1 0 1

There is a friendship between User 2 and 3, and between 3 and 4. Also, there is no friendship or blockship between User 2 and 4. Thus, User 4 is a friend candidate for User 2.

However, neither User 1 or 3 is a friend candidate for User 2, so User 2 has one friend candidate.

Sample Input 2

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

Sample Output 2

0 0 0 0 0

Everyone is a friend of everyone else and has no friend candidate.

Sample Input 3

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

Sample Output 3

1 3 5 4 3 3 3 3 1 0


{-# LANGUAGE BangPatterns #-}

module Main
  ( main
  )
where

import           Control.Applicative
import           Control.Monad
import           Data.Bits
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import           Data.List
import           Data.Maybe
import qualified Data.Vector                   as V
import qualified Data.Vector.Mutable           as MV
import           Control.Monad.ST
import           Data.Ord

parse = fst . fromJust
parseInt = parse . BS.readInt
parseInteger = parse . BS.readInteger
readInt = parseInt <$> BS.getLine
readInteger = parseInteger <$> BS.getLine
readIntList = map parseInt . BS.words <$> BS.getLine
readIntegerList = map parseInteger . BS.words <$> BS.getLine

main = do
  [n, r] <- readIntList
  print $ if n < 10 then r + 100 * (10 - n) else r

Score : 100 points

Problem Statement

Takahashi is a member of a programming competition site, ButCoder.

Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating.

The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inner Rating minus 100 \times (10 - K) when the member has participated in K contests.

Takahashi has participated in N contests, and his Displayed Rating is R. Find his Inner Rating.

Constraints

All values in input are integers.

1 \leq N \leq 100

0 \leq R \leq 4111

Input

Input is given from Standard Input in the following format:

N R

Output

Print his Inner Rating.

Sample Input 1

2 2919

Sample Output 1

3719

Takahashi has participated in 2 contests, which is less than 10, so his Displayed Rating is his Inner Rating minus 100 \times (10 - 2) = 800.

Thus, Takahashi's Inner Rating is 2919 + 800 = 3719.

Sample Input 2

22 3051

Sample Output 2

3051


import Data.List

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

solve n r = if n >= 10 then r else r + 100 * (10 - n)


digitNum n = go 0
  where
    go i 0 = i
    go i x = go (i+1) (x `div` n)

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

Score : 200 points

Problem Statement

Given is an integer N. Find the number of digits that N has in base K.

Notes

For information on base-K representation, see Positional notation - Wikipedia.

Constraints

All values in input are integers.

1 \leq N \leq 10^9

2 \leq K \leq 10

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of digits that N has in base K.

Sample Input 1

11 2

Sample Output 1

4

In binary, 11 is represented as 1011.

Sample Input 2

1010101 10

Sample Output 2

7

Sample Input 3

314159265 3

Sample Output 3

18


{-# LANGUAGE MultiWayIf #-}

module Main where

import           Control.Monad
import qualified Data.Array                    as A
import qualified Data.Array.IO                 as AIO
import qualified Data.Array.Unboxed            as AU
import qualified Data.ByteString               as BS
import qualified Data.ByteString.Char8         as BSC8
import           Data.Char
import           Data.List
import qualified Data.Map.Strict               as M
import           Data.Maybe
import           Data.Ord
import qualified Data.Set                      as S
import qualified Data.Vector                   as V
--import           Data.Vector.Algorithms.Search
import qualified Data.Vector.Mutable           as VM
import qualified Data.Vector.Unboxed           as VU
import qualified Data.Vector.Unboxed.Mutable   as VUM
import           Debug.Trace
--import qualified Data.Heap                     as H
main = do
  [iN, iA, iB] <- getIL
  let pattern = powMod 2 iN

  let cna     = combiMod iN iA
  let cnb     = combiMod iN iB
  let ret     = pattern - cna - cnb - 1
  print [pattern, cna, cnb]
  print ret

p :: Int -> Int
p x = x - 1

getIT2Order :: IO (Int, Int)
getIT2Order =
  getIL >>= \x@[xz, xo] -> if xz > xo then return (xo, xz) else return (xz, xo)

fromJustList :: Maybe [a] -> [a]
fromJustList (Just x) = x
fromJustList Nothing  = []

fromJustInt :: Maybe Int -> Int
fromJustInt (Just x) = x
fromJustInt Nothing  = 0

getVUI :: IO (VU.Vector Int)
getVUI = VU.unfoldr (BSC8.readInt . BSC8.dropWhile isSpace) <$> BSC8.getLine

getRepVUI :: Int -> IO (VU.Vector Int)
getRepVUI n =
  VU.unfoldr (BSC8.readInt . BSC8.dropWhile isSpace)
    .   BSC8.unlines
    <$> replicateM n BSC8.getLine

getVS :: IO (V.Vector Char)
getVS = V.fromList <$> getLine

getVUS :: IO (VU.Vector Char)
getVUS = VU.fromList <$> getLine

readI :: BSC8.ByteString -> Int
readI = fst . fromJust . BSC8.readInt

readIL :: BSC8.ByteString -> [Int]
readIL = map readI . BSC8.words

readIT2 :: BSC8.ByteString -> (Int, Int)
readIT2 bs =
  let words = BSC8.words bs in (readI $ head words, readI $ last words)

getI :: IO Int
getI = readI <$> BSC8.getLine

getIL :: IO [Int]
getIL = readIL <$> BSC8.getLine

get2IT :: IO (Int, Int)
get2IT = readIT2 <$> BSC8.getLine

getNIS :: Int -> IO [(Int, BSC8.ByteString)]
getNIS 0 = return []
getNIS n = do
  [aFst, aSnd] <- BSC8.words <$> BSC8.getLine
  next         <- getNIS (n - 1)
  return ((readI aFst, aSnd) : next)

il2Words :: [Int] -> String
il2Words = unwords . map show

il2Lines :: [Int] -> String
il2Lines = unlines . map show

--modNum = 10 ^ 9 + 7
modulus = 1000000007

newtype MInt = M Int

instance Num MInt where
  (M a) + (M b) = M $ mod (a + b) modulus

  (M a) - (M b) = M (a - b)

  (M a) * (M b) = M $ mod (a * b) modulus

  fromInteger a = M $ mod (fromInteger a) modulus

  abs (M a) = M $ abs a

  signum (M a) = M $ signum a

instance Show MInt where
  show (M a) = show (mod a modulus)

int2MInt :: Int -> MInt
int2MInt a = M (mod a modulus)

mInt2Int :: MInt -> Int
mInt2Int (M a) = a

{-
factsMod :: V.Vector MInt
factsMod = V.scanl (\acc x -> M x * acc) 1 $ V.generate 2000000 (+ 1)

factMod :: Int -> MInt
factMod = (factsMod V.!)
-}

factMod :: Int -> MInt
factMod n | n == 0    = 1
          | n == 1    = 1
          | otherwise = M n * (factMod (n - 1))

factDivMod :: Int -> Int -> MInt
factDivMod n k | n == k    = M 1
               | otherwise = M n * (factDivMod (n - 1) k)

powMod :: MInt -> Int -> MInt
powMod n k | k == 0       = M 1
           | k == 1       = n
           | mod k 2 == 0 = powMod (n ^ 2) (div k 2)
           | otherwise    = n * powMod (n ^ 2) (div k 2)

invMod :: MInt -> MInt
invMod (M 0) = error "inverse of 0"
invMod x     = powMod x (modulus - 2)

{-
combiMod :: Int -> Int -> MInt
combiMod n k
  | n < 0 || k < 0 || k > n = 0
  | otherwise = factMod n * invMod (factMod (n - k)) * invMod (factMod k)
-}
combiMod :: Int -> Int -> MInt
combiMod n k | n < 0 || k < 0 || k > n = 0
             | k > n - k = factDivMod n k * invMod (factMod (n - k))
             | otherwise = factDivMod n (n - k) * invMod (factMod k)

combi :: Int -> Int -> Int
combi n k | n < 0 || k < 0 || k > n = 0
          | k == n                  = 1
          | otherwise               = div (div (fact n) (fact (n - k))) (fact k)

primes :: V.Vector MInt
primes = V.scanl (\acc x -> M x * acc) 1 $ V.generate 200000 (+ 1)

fact :: Int -> Int
fact 0         = 1
fact n | n > 0 = n * fact (n - 1)

knappsackMaxVal
  :: AIO.IOArray (Int, Int) Int
  -> VU.Vector Int
  -> VU.Vector Int
  -> Int
  -> IO Int
knappsackMaxVal dp volumeVec valueVec dpSize = do
  mapM_
    (\i -> mapM_
      (\v -> do
        let volume = volumeVec VU.! i
            value  = valueVec VU.! i
        newdp <- if v < volume
          then AIO.readArray dp (i, v)
          else do
            dpIVm <- AIO.readArray dp (i, v - volume)
            dpIV  <- AIO.readArray dp (i, v)
            return (max (dpIVm + value) dpIV)
        AIO.writeArray dp (i + 1, v) newdp
      )
      [0 .. dpSize]
    )
    [0 .. VU.length volumeVec - 1]
  AIO.readArray dp (VU.length volumeVec, dpSize)

knappsackMinVol
  :: AIO.IOArray (Int, Int) Int
  -> VU.Vector Int
  -> VU.Vector Int
  -> Int
  -> Int
  -> IO Int
knappsackMinVol dp volumeVec valueVec dpSize maxVolume = do
  mapM_
    (\i -> mapM_
      (\v -> do
        let volume = volumeVec VU.! i
            value  = valueVec VU.! i
        newdp <- if (v + value) > dpSize
          then AIO.readArray dp (i, v)
          else do
            dpIVm <- AIO.readArray dp (i, v + value)
            dpIV  <- AIO.readArray dp (i, v)
            return (min (dpIVm - volume) dpIV)
        AIO.writeArray dp (i + 1, v) newdp
      )
      (reverse [0 .. dpSize])
    )
    [0 .. VU.length valueVec - 1]
  foldM
    (\acc x -> do
      num <- AIO.readArray dp (VU.length volumeVec, x)
      return $ if num <= maxVolume then x else acc
    )
    0
    [0 .. dpSize]

{-
hMaxPoint :: Int
hMaxPoint = 100
hMaximum :: H.Heap Int -> Int
hMaximum h = hMaxPoint - (H.minimum h)
hInsertMax :: Int -> H.Heap Int -> H.Heap Int
hInsertMax x = H.insert (hMaxPoint - x)
hDeleteMax :: H.Heap Int -> H.Heap Int
hDeleteMax = H.deleteMin
-}

myFilter :: (a -> Bool) -> [a] -> ([a], [a])
myFilter _pred [] = ([], [])
myFilter pred (x : xs)
  | pred x    = let (l, r) = myFilter pred xs in (x : l, r)
  | otherwise = let (l, r) = myFilter pred xs in (l, x : r)

--UnionFindデータ構造
type UF = (VUM.IOVector Int, VUM.IOVector Int)
uf_makeSet :: Int -> IO UF
uf_makeSet n = do
  parent <- VU.thaw $ VU.generate n id
  rank   <- VUM.replicate n 0
  return (parent, rank)
uf_union :: UF -> Int -> Int -> IO ()
uf_union unionFind@(parents, ranks) x y = do
  xRoot     <- uf_find unionFind x
  yRoot     <- uf_find unionFind y
  xRootRank <- VUM.read ranks x
  yRootRank <- VUM.read ranks y
  if
    | xRootRank > yRootRank -> VUM.write parents yRoot xRoot
    | xRootRank < yRootRank -> VUM.write parents yRoot xRoot
    | xRoot /= yRoot -> do
      VUM.write parents yRoot xRoot
      VUM.write ranks xRoot (xRootRank + 1)
    | otherwise -> return ()
uf_find :: UF -> Int -> IO Int
uf_find unionFind@(parents, ranks) x = do
  xParent <- VUM.read parents x
  if xParent == x
    then return x
    else do
      xRootParent <- uf_find unionFind xParent
      VUM.write parents x xRootParent
      return xRootParent

--UnDirectedGraph(無向グラフ)データ構造
type UDG = M.Map Int [Int]
list2UDG :: [(Int, Int)] -> M.Map Int [Int]
list2UDG = foldl
  (\acc x ->
    let lr = M.insertWith (++) (fst x) [snd x] acc
    in  M.insertWith (++) (snd x) [fst x] lr
  )
  M.empty

Score : 400 points

Problem Statement

Akari has n kinds of flowers, one of each kind.

She is going to choose one or more of these flowers to make a bouquet.

However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b.

How many different bouquets are there that Akari can make?

Find the count modulo (10^9 + 7).

Here, two bouquets are considered different when there is a flower that is used in one of the bouquets but not in the other bouquet.

Constraints

All values in input are integers.

2 \leq n \leq 10^9

1 \leq a < b \leq \textrm{min}(n, 2 \times 10^5)

Input

Input is given from Standard Input in the following format:

n a b

Output

Print the number of bouquets that Akari can make, modulo (10^9 + 7). (If there are no such bouquets, print 0.)

Sample Input 1

4 1 3

Sample Output 1

7

In this case, Akari can choose 2 or 4 flowers to make the bouquet.

There are 6 ways to choose 2 out of the 4 flowers, and 1 way to choose 4, so there are a total of 7 different bouquets that Akari can make.

Sample Input 2

1000000000 141421 173205

Sample Output 2

34076506

Print the count modulo (10^9 + 7).


module Main where

import Data.List
import Data.Char (digitToInt)
import Control.Monad
import Debug.Trace
import qualified Data.ByteString.Char8 as BC
import Data.Maybe (fromJust)
import qualified Data.Map.Strict as M
import qualified Data.Vector.Unboxed as V

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

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

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

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

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

fastPowerMod :: Int -> Int -> Int -> Int
fastPowerMod b 0 _ = 1
fastPowerMod b 1 modnum = b `mod` modnum
fastPowerMod b n modnum
            | even n = (fastPowerMod b (n `div` 2) modnum ^ 2) `mod` modnum
            | otherwise = (fastPowerMod b (n - 1) modnum * b) `mod` modnum

modInverse :: Int -> Int -> Int
modInverse n modnum = fastPowerMod n (modnum - 2) modnum

combinationM :: Int -> Int -> Int -> Int
combinationM  _ 0 _ = 1
combinationM  n 1 _ = n
combinationM  n k modnum
            | n < k = 0
            | k > (n - k) = combinationM  n (n - k) modnum
            | otherwise = upper * kfinv `mod` modnum where
                upper = prodMod [n,(n-1)..(n - k+1)] modnum
                kfinv = modInverse (prodMod [1..k] modnum) modnum

solve :: [Int] -> Int
solve xs = snd $ head $ sortOn snd $ fmap addV [1..100] where
    addV n = (n, sum $ fmap (\x -> (x - n) ^ 2 ) xs)

prodMod :: [Int] -> Int -> Int
prodMod xs modnum = foldl' (\b a -> b * a `mod` modnum) 1 xs

modSub :: Int -> Int -> Int -> Int
modSub mod a b
            | a < b = a - b + mod
            | otherwise = a - b

main = do
    (n, a, b) <- readTuple3
    let modnum = 1000000007
    let modSuba = modSub modnum
    print $ fastPowerMod 2 n modnum `modSuba` combinationM n a modnum `modSuba` combinationM n b modnum - 1


main=do
 [k,q]<-map read.words<$>getLine
 d<-map read.words<$>getLine
 putStr.unlines.map(show.(\[n,x,m]->n-1-div(x`mod`m+sum[(m-(-e)`mod`m)*div(n-i+k)k|(e,i)<-zip d[2..]])m).map read.words).lines<$>getContents

Score : 600 points

Problem Statement

We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.

Process the following q queries in order:

The i-th query contains three integers n_i, x_i, and m_i.
Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray}
Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).

Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).

Constraints

All values in input are integers.

1 \leq k, q \leq 5000

0 \leq d_i \leq 10^9

2 \leq n_i \leq 10^9

0 \leq x_i \leq 10^9

2 \leq m_i \leq 10^9

Input

Input is given from Standard Input in the following format:

k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q

Output

Print q lines.

The i-th line should contain the response to the i-th query.

Sample Input 1

3 1
3 1 4
5 3 2

Sample Output 1

1

For the first query, the sequence {a_j} will be 3,6,7,11,14.

(a_0~\textrm{mod}~2) > (a_1~\textrm{mod}~2)

(a_1~\textrm{mod}~2) < (a_2~\textrm{mod}~2)

(a_2~\textrm{mod}~2) = (a_3~\textrm{mod}~2)

(a_3~\textrm{mod}~2) > (a_4~\textrm{mod}~2)

Thus, the response to this query should be 1.

Sample Input 2

7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12

Sample Output 2

224489796
214285714
559523809


{-# LANGUAGE
  ScopedTypeVariables, BangPatterns, TupleSections, ExplicitForAll,
  LambdaCase, MultiWayIf, Unsafe, RecordWildCards, FlexibleContexts, CPP,
  NoMonomorphismRestriction, GADTs, PatternGuards, MagicHash, UnboxedTuples,
  RankNTypes, EmptyDataDecls, EmptyCase, ViewPatterns, PolyKinds,
  TypeFamilies, OverloadedStrings, FlexibleInstances, UndecidableInstances,
  DefaultSignatures, GeneralizedNewtypeDeriving, StandaloneDeriving,
  DeriveGeneric, DeriveFunctor, DeriveDataTypeable, DeriveFoldable,
  DeriveTraversable, DeriveDataTypeable, FlexibleInstances,
  MultiParamTypeClasses #-}
{-# OPTIONS_GHC -O2 #-}

import Prelude
import System.IO
import Control.Applicative
import Control.Monad.State.Strict
import Data.Monoid
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.ByteString.Builder as BSB
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Generic as VG

main :: IO ()
main = do
  [k,q] <- map readInt . words <$> getLine
  !ds <- getVecULn k rIntS
  printVecInLines =<< getVecURest q (liftA3 (query ds) rIntL rIntL rIntL)

query :: VU.Vector Int -> Int -> Int -> Int -> Int
query !ds !n !x !m = VU.ifoldr
      (\ !i !dj cont !cnt0 !tot ->
         let !cnt = if i < offCycle then numCycles+1 else numCycles
         in if dj == 0 then (cont $! cnt0 + cnt) tot
                       else cont cnt0 $! tot + dj * cnt)
      (\ !cnt0 !aLast -> (n-1) - (cnt0 + aLast `quot` m - a0 `quot` m))
      dsModded 0 x
  where
    dsModded = VU.map (`rem` m) ds
    !a0 = x
    !(!numCycles,!offCycle) = divMod (n-1) (VU.length ds)

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

printVecInLines ::
  (VG.Vector v a, ShowAsBuilder a) => v a -> IO ()
IL(printVecInLines) = BSB.hPutBuilder stdout . v2BLines

class ShowAsBuilder a where
  showAsBuilder :: a -> BSB.Builder

#define INS(t,f) instance ShowAsBuilder t where { IL(showAsBuilder)=f }
INS(Int,BSB.intDec)
#undef INS

v2BLines ::
  (VG.Vector v a, ShowAsBuilder a)
  => v a -> BSB.Builder
IL(v2BLines) = v2BLinesWith showAsBuilder

v2BLinesWith ::
  (VG.Vector v a)
  => (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
IL(v2BLinesWith) showFct
  = VG.foldr (\ a -> (showFct a <>) . (BSB.char7 '\n' <>)) mempty

IL(getVecGLn) :: (VG.Vector v a) =>
  Int -> StateT BS.ByteString Maybe a -> IO (v a)
getVecGLn n s = VG.unfoldrN n (runStateT s) <$> BS.getLine
IL(getVecGRest) :: (VG.Vector v a) =>
  Int -> StateT BSL.ByteString Maybe a -> IO (v a)
getVecGRest n s = VG.unfoldrN n (runStateT s) <$> BSL.getContents
IL(getVecULn) :: (VU.Unbox a) =>
  Int -> StateT BS.ByteString Maybe a -> IO (VU.Vector a)
getVecULn = getVecGLn
IL(getVecURest) :: (VU.Unbox a) =>
  Int -> StateT BSL.ByteString Maybe a -> IO (VU.Vector a)
getVecURest = getVecGRest

IL(rIntL) :: StateT BSL.ByteString Maybe Int
rIntL = skipSpecialL $ StateT BSL.readInt
IL(rIntS) :: StateT BS.ByteString Maybe Int
rIntS = skipSpecialS $ StateT BS.readInt
IL(dropSpecialL) :: (MonadState BSL.ByteString m) => m ()
dropSpecialL = modify $ BSL.dropWhile (<'!')
IL(dropSpecialS) :: (MonadState BS.ByteString m) => m ()
dropSpecialS = modify $ BS.dropWhile (<'!')
IL(skipSpecialL) :: (MonadState BSL.ByteString m) => m a -> m a
skipSpecialL = (dropSpecialL *>)
IL(skipSpecialS) :: (MonadState BS.ByteString m) => m a -> m a
skipSpecialS = (dropSpecialS *>)

readInt :: String -> Int
{-# INLINE readInt #-}
readInt = read


poor :: Int -> Int -> Int -> Bool
poor a b c
 | a == b && a /= c  = True
 | a == c && a /= b  = True
 | b == c && a /= b  = True
 | otherwise         = False

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

Score: 100 points

Problem Statement

A triple of numbers is said to be poor when two of those numbers are equal but the other number is different from those two numbers.

You will be given three integers A, B, and C. If this triple is poor, print Yes; otherwise, print No.

Constraints

A, B, and C are all integers between 1 and 9 (inclusive).

Input

Input is given from Standard Input in the following format:

A B C

Output

If the given triple is poor, print Yes; otherwise, print No.

Sample Input 1

5 7 5

Sample Output 1

Yes

A and C are equal, but B is different from those two numbers, so this triple is poor.

Sample Input 2

4 4 4

Sample Output 2

No

A, B, and C are all equal, so this triple is not poor.

Sample Input 3

4 9 6

Sample Output 3

No

Sample Input 4

3 3 4

Sample Output 4

Yes


answer :: [String] -> String
answer [a,b,c] | a == b && b == c && a == c = "No"
               | a /= b && b /= c && a /= c = "No"
               | otherwise = "Yes"
main = do
  list <- words <$> getLine
  print $ answer list


main = do
  getLine
  an <- map read . words <$> getLine
  print $ if all (\y -> y `mod` 3 == 0 || y `mod` 5 == 0) [x | x <- an, even x] then "APPROVED" else "DENIED"

Score: 200 points

Problem Statement

You are an immigration officer in the Kingdom of AtCoder. The document carried by an immigrant has some number of integers written on it, and you need to check whether they meet certain criteria.

According to the regulation, the immigrant should be allowed entry to the kingdom if and only if the following condition is satisfied:

All even numbers written on the document are divisible by 3 or 5.

If the immigrant should be allowed entry according to the regulation, output APPROVED; otherwise, print DENIED.

Notes

The condition in the statement can be rephrased as "If x is an even number written on the document, x is divisible by 3 or 5".
Here "if" and "or" are logical terms.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

If the immigrant should be allowed entry according to the regulation, print APPROVED; otherwise, print DENIED.

Sample Input 1

5
6 7 9 10 31

Sample Output 1

APPROVED

The even numbers written on the document are 6 and 10.

All of them are divisible by 3 or 5, so the immigrant should be allowed entry.

Sample Input 2

3
28 27 24

Sample Output 2

DENIED

28 violates the condition, so the immigrant should not be allowed entry.


main :: IO ()
main = do
  getLine
  as <- map read . words <$> getLine
  putStrLn $ if solve as then "APPROVED" else "DENIED"

solve :: [Int] -> Bool
solve as = all p as
  where
    p x = or [ odd x, x `mod` 3 == 0, x `mod` 5 == 0]


import Control.Applicative
import Data.Bool (bool)

main :: IO ()
main = getLine >> solve <$> f >>= putStrLn
  where
    f = map read <$> words <$> getLine

solve :: [Int] -> String
solve = bool "DENIED" "APPROVED" . all f
  where
    f x = odd x || x `mod` 3 == 0 || x `mod` 5 == 0


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

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

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

main = do
  n <- getInt
  a <- getIntList
  putStrLn $ solve a

solve :: [Int] -> String
solve a = do
  let s = filter (\n -> n `mod` 2 == 0) a
      b = filter (\n -> n `mod` 3 /= 0) (filter (\n -> n `mod` 5 /= 0) s)
      n = length b
      in if n == 0 then "APPROVED" else "DENIED"


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

readString = map BS.unpack . BS.words <$> BS.getLine
readStrings n = replicateM n $ BS.unpack <$> BS.getLine
toPair [x, y] = (x, y)

main = do
  n <- read <$> getLine
  a <- map read . words <$> getLine
  putStrLn $ solve a n

solve :: [Int] -> Int -> String
solve a n | all f a'  = "APPROVED"
          | otherwise = "DENIED"
 where
  a' = filter even a
  f x = or [x `mod` 3 == 0, x `mod` 5 == 0]