import qualified Data.Vector as V
import qualified Data.ByteString.Char8 as B
import Data.List
import qualified Data.Map as M
import Control.Monad

solve :: M.Map Int [B.ByteString] -> B.ByteString -> Int -> M.Map Int [B.ByteString]
solve m b i =
    case M.lookup i m of
        Just bs ->
            if b `elem` bs
                then solve m b (i+1)
                else M.adjust (b:) i m
        Nothing -> M.insert i [b] m

main = do
    n <- readLn :: IO Int
    strs <- V.replicateM n B.getLine
    let m = V.foldl' (\m s -> solve m s 1) M.empty strs
    let ((_, bs), _) = M.deleteFindMax m
    forM_ (sort bs) $ \b -> putStrLn $ B.unpack b

Score: 300 points

Problem Statement

We have N voting papers. The i-th vote (1 \leq i \leq N) has the string S_i written on it.

Print all strings that are written on the most number of votes, in lexicographical order.

Constraints

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

S_i (1 \leq i \leq N) are strings consisting of lowercase English letters.

The length of S_i (1 \leq i \leq N) is between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

Print all strings in question in lexicographical order.

Sample Input 1

7
beat
vet
beet
bed
vet
bet
beet

Sample Output 1

beet
vet

beet and vet are written on two sheets each, while beat, bed, and bet are written on one vote each. Thus, we should print the strings beet and vet.

Sample Input 2

8
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo

Sample Output 2

buffalo

Sample Input 3

7
bass
bass
kick
kick
bass
kick
kick

Sample Output 3

kick

Sample Input 4

4
ushi
tapu
nichia
kun

Sample Output 4

kun
nichia
tapu
ushi


import Data.List
main=do
 s<-group.sort.tail.lines<$>getContents
 let m=maximum$map length s
 putStr$unlines$sort[head c|c<-s,m==length c]

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

Submitted source-code file size, in bytes.

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

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


main = do
 [s,t] <- words <$> getLine
 [a,b] <- map read . words <$> getLine :: IO[Int]
 putStr =<< unwords . map show . (\x -> if x == s then [a - 1, b] else [a, b - 1]) <$> getLine

Score : 100 points

Problem Statement

We have A balls with the string S written on each of them and B balls with the string T written on each of them.

From these balls, Takahashi chooses one with the string U written on it and throws it away.

Find the number of balls with the string S and balls with the string T that we have now.

Constraints

S, T, and U are strings consisting of lowercase English letters.

The lengths of S and T are each between 1 and 10 (inclusive).

S \not= T

S=U or T=U.

1 \leq A,B \leq 10

A and B are integers.

Input

Input is given from Standard Input in the following format:

S T
A B
U

Output

Print the answer, with space in between.

Sample Input 1

red blue
3 4
red

Sample Output 1

2 4

Takahashi chose a ball with red written on it and threw it away.
Now we have two balls with the string S and four balls with the string T.

Sample Input 2

red blue
5 5
blue

Sample Output 2

5 4

Takahashi chose a ball with blue written on it and threw it away.
Now we have five balls with the string S and four balls with the string T.


import Control.Applicative

main :: IO ()
main = solve <$> getLine >>= putStrLn

solve :: String -> String
solve = map (const 'x')

Score : 200 points

Problem Statement

Given is a string S. Replace every character in S with x and print the result.

Constraints

S is a string consisting of lowercase English letters.

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

Input

Input is given from Standard Input in the following format:

S

Output

Replace every character in S with x and print the result.

Sample Input 1

sardine

Sample Output 1

xxxxxxx

Replacing every character in S with x results in xxxxxxx.

Sample Input 2

xxxx

Sample Output 2

xxxx

Sample Input 3

gone

Sample Output 3

xxxx


import Data.List

main::IO()
main = do
    _ <- getLine
    s <- words <$> getLine
    putStrLn $ if (length s) == (length (nub s)) then "YES" else "NO"

Score : 300 points

Problem Statement

Given is a sequence of integers A_1, A_2, ..., A_N.
If its elements are pairwise distinct, print YES; otherwise, print NO.

Constraints

2 ≤ N ≤ 200000

1 ≤ A_i ≤ 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

If the elements of the sequence are pairwise distinct, print YES; otherwise, print NO.

Sample Input 1

5
2 6 1 4 5

Sample Output 1

YES

The elements are pairwise distinct.

Sample Input 2

6
4 1 3 1 6 2

Sample Output 2

NO

The second and fourth elements are identical.

Sample Input 3

2
10000000 10000000

Sample Output 3

NO


import           Data.Set (empty, member, insert)

nub' :: (Ord a) => [a] -> [a]
nub' l = nub'' l empty
  where
    nub'' [] _ = []
    nub'' (x:xs) s
      | x `member` s = nub'' xs s
      | otherwise = x:nub'' xs (x `insert` s)

main = do
  getLine
  a <- map (read :: String -> Int) . words <$> getLine
  putStrLn
    $ if length a == (length . nub') a
      then "YES"
      else "NO"


-- Your code here!
import Data.List
import qualified Data.ByteString.Char8 as BC

main = do
    _ <- BC.getLine
    nums <- BC.words <$> BC.getLine
    putStrLn $ if length nums == (length . nub $ nums) then "YES" else "NO"


import Data.List
main=do
 getLine
 a<-words<$>getLine
 putStrLn$if f a then"YES"else"NO"
f(a:b:s)=a/=b&&f(b:s)
f s=True


import Data.List
import Text.Printf
main :: IO ()
main = do
  [_, pickupDice] <- getInts
  dices <- getInts
  printf "%.6f\n" $ getMaxMean pickupDice 0 dices

-- | 最大の平均値を取得する
--
-- >>> getMaxMean 4 0 [17,13,13,12,15,20,10,13,17,11]
-- 32.0
getMaxMean :: Int -> Float -> [Int] -> Float
getMaxMean _ currentMax [] = currentMax
getMaxMean pickupDice currentMax (x:xs)
  | length xs < pickupDice - 1 = currentMax
  | otherwise = getMaxMean pickupDice newMax xs
  where
    currentMean = sum $ map calcMean $ take pickupDice xs
    newMax = if currentMax > currentMean then currentMax else currentMean

-- | ダイスの平均値を出す
--
-- >>> calcMean 1
-- 1.0
-- >>> calcMean 2
-- 1.5
-- >>> calcMean 3
-- 2.0
-- >>> calcMean 5
-- 3.0
-- >>> calcMean 6
-- 3.5
calcMean :: Int -> Float
calcMean 1 = realToFrac 1 :: Float
calcMean x = (realToFrac(x) / 2) + 0.5 :: Float

isUniq :: [String] -> String
isUniq [] = "YES"
isUniq (x:xs)
  | x `elem` xs  = "NO"
  | otherwise = isUniq xs

getInts = do
  x <- getLine
  let y = (map $ read) $ words x :: [Int]
  return y

Score : 400 points

Problem Statement

We have N dice arranged in a line from left to right. The i-th die from the left shows p_i numbers from 1 to p_i with equal probability when thrown.

We will choose K adjacent dice, throw each of them independently, and compute the sum of the numbers shown. Find the maximum possible value of the expected value of this sum.

Constraints

1 ≤ K ≤ N ≤ 200000

1 ≤ p_i ≤ 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
p_1 ... p_N

Output

Print the maximum possible value of the expected value of the sum of the numbers shown.

Your output will be considered correct when its absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

5 3
1 2 2 4 5

Sample Output 1

7.000000000000

When we throw the third, fourth, and fifth dice from the left, the expected value of the sum of the numbers shown is 7. This is the maximum value we can achieve.

Sample Input 2

4 1
6 6 6 6

Sample Output 2

3.500000000000

Regardless of which die we choose, the expected value of the number shown is 3.5.

Sample Input 3

10 4
17 13 13 12 15 20 10 13 17 11

Sample Output 3

32.000000000000


fact 0 = 1
fact x = x * fact (x - 1)
main = do
 [o,p,q,s] <- map read . words <$> getLine
 print $ (sum [(fact (r+c)) `div` ((fact r)*(fact c)) | r <- [o..q], c <- [p..s]]) `mod` (10^9 + 7)

Score : 600 points

Problem Statement

Snuke is standing on a two-dimensional plane. In one operation, he can move by 1 in the positive x-direction, or move by 1 in the positive y-direction.

Let us define a function f(r, c) as follows:

f(r,c) := (The number of paths from the point (0, 0) to the point (r, c) that Snuke can trace by repeating the operation above)

Given are integers r_1, r_2, c_1, and c_2.
Find the sum of f(i, j) over all pair of integers (i, j) such that r_1 ≤ i ≤ r_2 and c_1 ≤ j ≤ c_2, and compute this value modulo (10^9+7).

Constraints

1 ≤ r_1 ≤ r_2 ≤ 10^6

1 ≤ c_1 ≤ c_2 ≤ 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r_1 c_1 r_2 c_2

Output

Print the sum of f(i, j) modulo (10^9+7).

Sample Input 1

1 1 2 2

Sample Output 1

14

For example, there are two paths from the point (0, 0) to the point (1, 1): (0,0) → (0,1) → (1,1) and (0,0) → (1,0) → (1,1), so f(1,1)=2.

Similarly, f(1,2)=3, f(2,1)=3, and f(2,2)=6. Thus, the sum is 14.

Sample Input 2

314 159 2653 589

Sample Output 2

602215194


module Main where

import Data.List
import qualified Data.Map.Strict as Map
import Control.Monad
import Data.Ord

main = do
    print =<< solve <$> readInts

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

solve :: [Int] -> Int
solve [h, a] = div (h + a - 1) a

Score : 100 points

Problem Statement

Serval is fighting with a monster.

The health of the monster is H.

In one attack, Serval can decrease the monster's health by A.
There is no other way to decrease the monster's health.

Serval wins when the monster's health becomes 0 or below.

Find the number of attacks Serval needs to make before winning.

Constraints

1 \leq H \leq 10^4

1 \leq A \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H A

Output

Print the number of attacks Serval needs to make before winning.

Sample Input 1

10 4

Sample Output 1

3

After one attack, the monster's health will be 6.

After two attacks, the monster's health will be 2.

After three attacks, the monster's health will be -2.

Thus, Serval needs to make three attacks to win.

Sample Input 2

1 10000

Sample Output 2

1

Sample Input 3

10000 1

Sample Output 3

10000


import           Control.Monad.ST            (ST)
import           Data.Bits                   (shiftR)
import qualified Data.ByteString.Char8       as B
import           Data.Maybe                  (fromJust)
import qualified Data.Vector.Unboxed         as V
import qualified Data.Vector.Unboxed.Mutable as VM

readInts :: B.ByteString -> [Int]
readInts = map (fst . fromJust . B.readInt) . B.words

getInts :: IO [Int]
getInts = readInts <$> B.getLine

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

solve :: Int -> Int -> [Int] -> Int
solve n k hs = V.sum $ kill n k hs' where
  hs' = sort' $ V.fromList hs

kill :: Int -> Int -> V.Vector Int -> V.Vector Int
kill n k = V.take (n - k)

sort' :: (V.Unbox a, Ord a) => V.Vector a -> V.Vector a
sort' = V.modify (\v -> quicksort v 0 (VM.length v))

-- https://github.com/as-capabl/haskell-qsort-pfm/blob/master/src/UV.hs
quicksort :: (V.Unbox a, Ord a) => VM.STVector s a -> Int -> Int -> ST s ()
quicksort work iStart iEnd
    | iEnd - iStart <= 1 = return ()
    | otherwise = do
        pivot <- VM.unsafeRead work (((iEnd - iStart) `shiftR` 1) + iStart)
        med <- divide pivot iStart (iEnd - 1)
        quicksort work iStart med
        quicksort work med iEnd
  where
    divide pivot iS' iE'
        | iS' > iE' = return iS'
        | otherwise = do
            lower <- shrinkLower pivot iS' iE'
            higher <- shrinkHigher pivot lower iE'
            if lower >= higher
              then do
                return lower
              else do
                swapWork lower higher
                divide pivot (lower + 1) (higher - 1)

    shrinkLower pivot iS' iE'
        | iS' > iE' = return iS'
        | otherwise = do
            x <- VM.unsafeRead work iS'
            if x >= pivot
              then
                return iS'
              else
                shrinkLower pivot (iS' + 1) iE'

    shrinkHigher pivot iS' iE'
        | iS' > iE' = return iE'
        | otherwise = do
            x <- VM.unsafeRead work iE'
            if x <= pivot
              then
                return iE'
              else
                shrinkHigher pivot iS' (iE' - 1)

    swapWork i j = VM.unsafeSwap work i j

Score : 300 points

Problem Statement

Fennec is fighting with N monsters.

The health of the i-th monster is H_i.

Fennec can do the following two actions:

Attack: Fennec chooses one monster. That monster's health will decrease by 1.

Special Move: Fennec chooses one monster. That monster's health will become 0.

There is no way other than Attack and Special Move to decrease the monsters' health.

Fennec wins when all the monsters' healths become 0 or below.

Find the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning when she can use Special Move at most K times.

Constraints

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

0 \leq K \leq 2 \times 10^5

1 \leq H_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
H_1 ... H_N

Output

Print the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning.

Sample Input 1

3 1
4 1 5

Sample Output 1

5

By using Special Move on the third monster, and doing Attack four times on the first monster and once on the second monster, Fennec can win with five Attacks.

Sample Input 2

8 9
7 9 3 2 3 8 4 6

Sample Output 2

0

She can use Special Move on all the monsters.

Sample Input 3

3 0
1000000000 1000000000 1000000000

Sample Output 3

3000000000

Watch out for overflow.


import Data.List
main = do
 [a,b] <- map read . words <$> getLine
 a_s <- map read . words <$> getLine
 print $ sum(take (a-b) (sort a_s))


main = do
    h <- readLn
    print $ attack 0 h

attack :: Integer -> Integer -> Integer
attack x 1 = x + 1
attack x y = (x + 1) + 2 * attack 0 (div y 2)

Score : 400 points

Problem Statement

Caracal is fighting with a monster.

The health of the monster is H.

Caracal can attack by choosing one monster. When a monster is attacked, depending on that monster's health, the following happens:

If the monster's health is 1, it drops to 0.

If the monster's health, X, is greater than 1, that monster disappears. Then, two new monsters appear, each with the health of \lfloor X/2 \rfloor.

(\lfloor r \rfloor denotes the greatest integer not exceeding r.)

Caracal wins when the healths of all existing monsters become 0 or below.

Find the minimum number of attacks Caracal needs to make before winning.

Constraints

1 \leq H \leq 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H

Output

Find the minimum number of attacks Caracal needs to make before winning.

Sample Input 1

2

Sample Output 1

3

When Caracal attacks the initial monster, it disappears, and two monsters appear, each with the health of 1.

Then, Caracal can attack each of these new monsters once and win with a total of three attacks.

Sample Input 2

4

Sample Output 2

7

Sample Input 3

1000000000000

Sample Output 3

1099511627775


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

main :: IO ()
main = do
  (h : _) <- map unsafeSignedDecimal . T.words <$> T.getLine :: IO [Int]
  print . f $ h

f :: Int -> Int
f 1 = 1
f h = 1 + 2 * f (h `div` 2)

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


main = interact $ show . calc . read

calc :: Int -> Int
calc 1 = 1
calc x = 2 * calc (x `div` 2) + 1


{-# 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
  [iH, iN] <- getIL
  ab       <- VU.fromList <$> replicateM iN getIT2
  let (a, b)   = VU.unzip ab
  let dpSize   = iH + VU.maximum a
  let maxValue = 10 ^ 8 * iN + 1
  dp       <- AIO.newArray ((0, 0), (iN, dpSize)) maxValue
  minValue <- dupKnappsackMinVal dp a b dpSize iH maxValue
  print minValue

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

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

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

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

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]

dupKnappsackMinVal
  :: AIO.IOArray (Int, Int) Int
  -> VU.Vector Int
  -> VU.Vector Int
  -> Int
  -> Int
  -> Int
  -> IO Int
dupKnappsackMinVal dp volumeVec valueVec dpSize maxVolume maxValue = do
  AIO.writeArray dp (0, 0) 0
  minimum . concat <$> 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 + 1, v - volume)
            dpIV  <- AIO.readArray dp (i, v)
            return (min (dpIVm + value) dpIV)
        AIO.writeArray dp (i + 1, v) newdp
        if v >= maxVolume then return newdp else return maxValue
      )
      [0 .. dpSize]
    )
    [0 .. VU.length volumeVec - 1]
{-
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 : 500 points

Problem Statement

Ibis is fighting with a monster.

The health of the monster is H.

Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.

The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.

Ibis wins when the health of the monster becomes 0 or below.

Find the minimum total Magic Points that have to be consumed before winning.

Constraints

1 \leq H \leq 10^4

1 \leq N \leq 10^3

1 \leq A_i \leq 10^4

1 \leq B_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H N
A_1 B_1
:
A_N B_N

Output

Print the minimum total Magic Points that have to be consumed before winning.

Sample Input 1

9 3
8 3
4 2
2 1

Sample Output 1

4

First, let us cast the first spell to decrease the monster's health by 8, at the cost of 3 Magic Points. The monster's health is now 1.

Then, cast the third spell to decrease the monster's health by 2, at the cost of 1 Magic Point. The monster's health is now -1.

In this way, we can win at the total cost of 4 Magic Points.

Sample Input 2

100 6
1 1
2 3
3 9
4 27
5 81
6 243

Sample Output 2

100

It is optimal to cast the first spell 100 times.

Sample Input 3

9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461

Sample Output 3

139815


import qualified Data.ByteString.Char8 as B
import qualified Data.Vector.Unboxed as VU
import Data.Char

solve :: Int ->  VU.Vector (Int,Int) -> VU.Vector Int
solve h abs = VU.foldl' step (VU.singleton 0) (VU.generate h $ \ i -> i + 1)
    where
        step :: VU.Vector Int -> Int -> VU.Vector Int
        step v i =
            let
                m = VU.foldl' (\x (a,b) -> let y = if i >= a then b + (v VU.! (i-a)) else (10^9) in min x y) (10^9) abs
            in
                VU.generate (i+1) $ \j -> if j == i then m else v VU.! j

main = do
    [h, n] <- map  read . words <$> getLine :: IO [Int]
    abs <- VU.replicateM n $ do
        s <- B.getLine
        let Just (a, s') = B.readInt s
        let Just (b, _) = B.readInt $ B.dropWhile isSpace s'
        return (a,b)
    print $ VU.last $ solve h abs


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

main = do
  li <- BS.getLine
  let [n,d,a] = map (read . BS.unpack) $ BS.words li
  co <- BS.getContents
  let xhs = map (map ((\(Just (x,_)) -> x) . BS.readInt)) $ map BS.words $ BS.lines co
  let ans = compute n d a xhs
  print ans

compute :: Int -> Int -> Int -> [[Int]] -> Int
compute n d a xhs = loop 0 [] (sort xhs)
  where
    d2 = d * 2
    loop n _ [] = n
    loop n ybs ([x,h]:xhs)
      | h1 <= 0 = loop n ybs1 xhs
      | True    = loop (n+k) ((x+d2, a*k):ybs1) xhs
      where
        ybs1 = filter ((x <=).fst) ybs
        h1 = h - sum (map snd ybs1)
        k = (h1 + a - 1) `div` a

Score : 600 points

Problem Statement

Silver Fox is fighting with N monsters.

The monsters are standing in a row, and we can assume them to be standing on a number line. The i-th monster, standing at the coordinate X_i, has the health of H_i.

Silver Fox can use bombs to attack the monsters.
Using a bomb at the coordinate x decreases the healths of all monsters between the coordinates x-D and x+D (inclusive) by A.
There is no way other than bombs to decrease the monster's health.

Silver Fox wins when all the monsters' healths become 0 or below.

Find the minimum number of bombs needed to win.

Constraints

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

0 \leq D \leq 10^9

1 \leq A \leq 10^9

0 \leq X_i \leq 10^9

1 \leq H_i \leq 10^9

X_i are distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N D A
X_1 H_1
:
X_N H_N

Output

Print the minimum number of bombs needed to win.

Sample Input 1

3 3 2
1 2
5 4
9 2

Sample Output 1

2

First, let us use a bomb at the coordinate 4 to decrease the first and second monsters' health by 2.

Then, use a bomb at the coordinate 6 to decrease the second and third monsters' health by 2.

Now, all the monsters' healths are 0.
We cannot make all the monsters' health drop to 0 or below with just one bomb.

Sample Input 2

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

Sample Output 2

5

We should use five bombs at the coordinate 5.

Sample Input 3

3 0 1
300000000 1000000000
100000000 1000000000
200000000 1000000000

Sample Output 3

3000000000

Watch out for overflow.


{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE BangPatterns #-}

-- Default Imports

import Control.Monad
import Control.Monad.ST
import Control.Monad.Trans.Class

import qualified Control.Monad.Reader as Reader
import Control.Monad.Reader (Reader, ReaderT, runReader, runReaderT)

import qualified Data.Array.MArray as MArray
import qualified Data.Array.ST as STArray
import Data.Array.ST (STArray, STUArray, runSTArray, runSTUArray)
import Data.Ix (Ix)

import qualified Data.Bits as Bits
import Data.Bits ((.&.), (.|.))

import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (ByteString)

import qualified Data.Char as Char
import qualified Data.List as List
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Maybe as Maybe
import qualified Data.Set as Set
import Data.Set (Set)

import qualified Data.Vector as Vector
import qualified Data.Vector.Generic as GVector
import qualified Data.Vector.Mutable as MVector
import Data.Vector.Mutable (STVector)
import qualified Data.Vector.Unboxed as UVector

import Numeric

import Debug.Trace
-- ----------

-- Custom Import Here

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

-- Default Definitions

type Vector = Vector.Vector
-- type GVector = GVector.Vector
type UVector = UVector.Vector

readIntToList :: ByteString -> [Int]
readIntToList = List.unfoldr (fmap (second $ BS.dropWhile Char.isSpace) . BS.readInt)

readToList :: Read a => ByteString -> [a]
readToList = List.unfoldr $ fmap (mapTaken . mapRemain) . span' (not . Char.isSpace)
	where
		mapTaken  = first $ read . BS.unpack
		mapRemain = second $ BS.dropWhile Char.isSpace
		span' pred s
			| BS.null taken = Nothing
			| otherwise     = Just (taken, remain')
			where
				(taken, remain) = BS.span pred s
				remain' = BS.dropWhile Char.isSpace remain

readToListN :: Read a => Int -> ByteString -> [a]
readToListN n = take n . readToList

readIntToVector :: ByteString -> Vector Int
readIntToVector = Vector.unfoldr (fmap stripRemain . BS.readInt)
	where stripRemain = second $ BS.dropWhile Char.isSpace

readIntToUVector :: ByteString -> UVector.Vector Int
readIntToUVector = UVector.unfoldr (fmap stripRemain . BS.readInt)
	where stripRemain = second $ BS.dropWhile Char.isSpace

readIntToVectorN :: Int -> ByteString -> Vector.Vector Int
readIntToVectorN n = Vector.unfoldrN n (fmap stripRemain . BS.readInt)
	where stripRemain = second $ BS.dropWhile Char.isSpace

readIntToUVectorN :: Int -> ByteString -> UVector.Vector Int
readIntToUVectorN n = UVector.unfoldrN n (fmap stripRemain . BS.readInt)
	where stripRemain = second $ BS.dropWhile Char.isSpace

first :: (a -> a') -> (a, b) -> (a', b)
first f (a, b) = (f a, b)

second :: (b -> b') -> (a, b) -> (a, b')
second f (a, b) = (a, f b)

average :: Fractional a => [a] -> a
average xs = sum xs / (fromIntegral . length) xs

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

main :: IO ()
main = do
	[a, b] <- readIntToList <$> BS.getLine
	putStrLn $ if a == b then "Yes" else "No"

Score : 100 points

Problem Statement

Takahashi is participating in a programming contest, AXC001. He has just submitted his code to Problem A.

The problem has N test cases, all of which must be passed to get an AC verdict.

Takahashi's submission has passed M cases out of the N test cases.

Determine whether Takahashi's submission gets an AC.

Constraints

1 \leq N \leq 100

0 \leq M \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

If Takahashi's submission gets an AC, print Yes; otherwise, print No.

Sample Input 1

3 3

Sample Output 1

Yes

All three test cases have been passed, so his submission gets an AC.

Sample Input 2

3 2

Sample Output 2

No

Only two out of the three test cases have been passed, so his submission does not get an AC.

Sample Input 3

1 1

Sample Output 3

Yes


{-# 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
import qualified Data.Vector.Unboxed           as UV

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
  [a, b] <- readIntList
  putStrLn $ if a < b then [intToDigit a | i <- [1..b]] else [intToDigit b | i <- [1..a]]

Score : 200 points

Problem Statement

Given are 1-digit positive integers a and b. Consider these two strings: the concatenation of b copies of the digit a, and the concatenation of a copies of the digit b. Which of these is lexicographically smaller?

Constraints

1 \leq a \leq 9

1 \leq b \leq 9

a and b are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

Print the lexicographically smaller of the two strings. (If the two strings are equal, print one of them.)

Sample Input 1

4 3

Sample Output 1

3333

We have two strings 444 and 3333. Between them, 3333 is the lexicographically smaller.

Sample Input 2

7 7

Sample Output 2

7777777


import Data.List

main = do
  str <- getLine
  let [a, b] = words str
  if a < b
    then putStrLn $ mkStr b a
    else putStrLn $ mkStr a b
      where mkStr x y = intercalate "" $ take (read x ::Int) $ repeat y


f (n,m) x = if x < m then (n+1,x) else (n,m)
main = do
  n <- readLn :: IO Int
  ps <- (return . map (read::String->Int) . words) =<< getLine
  print $ fst $ foldl f (0,n+1) ps

Score : 300 points

Problem Statement

Given is a permutation P_1, \ldots, P_N of 1, \ldots, N.
Find the number of integers i (1 \leq i \leq N) that satisfy the following condition:

For any integer j (1 \leq j \leq i), P_i \leq P_j.

Constraints

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

P_1, \ldots, P_N is a permutation of 1, \ldots, N.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 ... P_N

Output

Print the number of integers i that satisfy the condition.

Sample Input 1

5
4 2 5 1 3

Sample Output 1

3

i=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j holds for j = 1.

Similarly, i=5 does not satisfy the condition, either. Thus, there are three integers that satisfy the condition.

Sample Input 2

4
4 3 2 1

Sample Output 2

4

All integers i (1 \leq i \leq N) satisfy the condition.

Sample Input 3

6
1 2 3 4 5 6

Sample Output 3

1

Only i=1 satisfies the condition.

Sample Input 4

8
5 7 4 2 6 8 1 3

Sample Output 4

4

Sample Input 5

1
1

Sample Output 5

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.Strict as MPS
import qualified Data.Map as MP
import qualified Data.Set as ST
import qualified Data.Sequence as SQ
import Data.Array
-- import Data.Array.Unboxed
import Data.Array.ST
import Data.Array.IO
import Data.Maybe
import Data.Ord
import Data.Ratio
import Data.Char
import Data.Bits
import Data.List
import Data.Tuple
import Data.Functor
import Data.IORef
import Data.STRef
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Control.Monad.State.Strict
import Debug.Trace
-- import qualified Data.OrdPSQ as PSQ
-- import qualified Data.Vector.Algorithms.Merge as VAM
-- import qualified Data.Heap as HP
-- import Numeric.Extra
-- import Data.Tuple.Extra
-- import Data.List.Extra

-- data OrdQ = Ascending | Descending

--------------------------------------------------------------------------
solve :: Int -> Int
solve n =
    runST $ do
        table <- newArray ((1, 1), (9, 9)) 0 :: ST s (STUArray s (Int, Int) Int)

        forM_ [1..n] $ \i -> do
            let i' = show i
                h = digitToInt $! head i'
                l = digitToInt $! last i'
            when (h /= 0 && l /= 0) $ do
                readArray table (h, l) >>= \r -> writeArray table (h, l) $! r + 1

        table' <- freeze table
        flip evalStateT 0 $! do
            forM_ [1..9] $ \i ->
                forM_ [1..9] $ \j -> do
                    let
                        a = table' ! (i, j)
                        b = table' ! (j, i)
                    modify' (\x -> x + a * b)
            get

main = do
    n <- int
    print $ solve n
--------------------------------------------------------------------------

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

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

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

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

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

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

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

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

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

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

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

sLineToDoubleL :: IO [Double]
sLineToDoubleL = fromSLineL bsToDouble

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

m1 :: Int -> Int
m1 = subtract 1

toDouble :: Int -> Double
toDouble = fromIntegral

toInt :: Double -> Int
toInt = floor

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

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

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

Score : 400 points

Problem Statement

Given is a positive integer N.

Find the number of pairs (A, B) of positive integers not greater than N that satisfy the following condition:

When A and B are written in base ten without leading zeros, the last digit of A is equal to the first digit of B, and the first digit of A is equal to the last digit of B.

Constraints

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

25

Sample Output 1

17

The following 17 pairs satisfy the condition: (1,1), (1,11), (2,2), (2,22), (3,3), (4,4), (5,5), (6,6), (7,7), (8,8), (9,9), (11,1), (11,11), (12,21), (21,12), (22,2), and (22,22).

Sample Input 2

1

Sample Output 2

1

Sample Input 3

100

Sample Output 3

108

Sample Input 4

2020

Sample Output 4

40812

Sample Input 5

200000

Sample Output 5

400000008


import qualified Data.Map as M
import Data.Maybe (fromJust)
import Data.Char (intToDigit)

pair::[Char]->(Char,Char)
pair x = (head x,last x)

solve::Int->Int->M.Map (Char,Char) Int->Int
solve i j m = case M.lookup (intToDigit i,intToDigit j) m of
              Just x -> x
              Nothing -> 0

main = do
  n <- readLn
  let hash = M.fromListWith (+) $ map (\x -> (pair x,1)) $ map show [1..n]
  print $ sum [(solve i j hash)*(solve j i hash) | i <- [1..9], j <- [1..9]]


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

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

main = do
    n <- getInt
    print $ solve n

solve n = 2 * (solve'' n) - (solve' n)
solve'' n = length [() | a <- [1..n], b <- [1..a], check a b, check b a]
solve' n = length [() | a <- [1..n] , check a a]

check :: Int -> Int -> Bool
check a b = head (show a) == last (show b)


{-# LANGUAGE BangPatterns #-}
import           Control.Monad
import qualified Data.ByteString.Char8 as BS
import           Data.Char
import           Data.Maybe
import qualified Data.Vector           as V

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

getIntVec n = V.unfoldrN n (BS.readInteger . BS.dropWhile isSpace) <$> BS.getLine

main = do
  n <- getInt
  as <- getIntVec n
  let m = V.foldr' lcm 1 as
      as' = V.map (\ !i -> m `div` i) as
  print $ (sum as') `mod` 1000000007

Score : 500 points

Problem Statement

Given are N positive integers A_1,...,A_N.

Consider positive integers B_1, ..., B_N that satisfy the following condition.

Condition: For any i, j such that 1 \leq i < j \leq N, A_i B_i = A_j B_j holds.

Find the minimum possible value of B_1 + ... + B_N for such B_1,...,B_N.

Since the answer can be enormous, print the sum modulo (10^9 +7).

Constraints

1 \leq N \leq 10^4

1 \leq A_i \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

Print the minimum possible value of B_1 + ... + B_N for B_1,...,B_N that satisfy the condition, modulo (10^9 +7).

Sample Input 1

3
2 3 4

Sample Output 1

13

Let B_1=6, B_2=4, and B_3=3, and the condition will be satisfied.

Sample Input 2

5
12 12 12 12 12

Sample Output 2

5

We can let all B_i be 1.

Sample Input 3

3
1000000 999999 999998

Sample Output 3

996989508

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


main = do
    _ <- getLine
    a <- (map read) . words <$> getLine
    print $ mod (sum $ map (\x -> div (foldr lcm 1 a) x) a) 1000000007


{-# LANGUAGE MultiWayIf #-}

module Main where
import           Prelude
import           Control.Monad
import           Data.Monoid
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    <- getI
  vecSE <- VU.fromList . sortBy (comparing snd) <$> replicateM
    iN
    ((\x -> (uncurry (-) x, uncurry (+) x)) <$> getIT2)

  let selected = selectArm vecSE 0
  print $ VU.length selected

selectArm :: VU.Vector (Int, Int) -> Int -> VU.Vector (Int, Int)
selectArm vecSE n
  | n > VU.length vecSE - 1
  = VU.empty
  | n == VU.length vecSE - 1
  = VU.singleton $ vecSE VU.! n
  | otherwise
  = let arm@(start, end)     = vecSE VU.! n
        nextFromDup          = searchMinEndNOfDup end vecSE n n
        (nextStart, nextEnd) = vecSE VU.! nextFromDup
    in  VU.cons
          (vecSE VU.! nextFromDup)
          (selectArm vecSE (searchOverDupN nextEnd vecSE (nextFromDup + 1)))

searchMinEndNOfDup :: Int -> VU.Vector (Int, Int) -> Int -> Int -> Int
searchMinEndNOfDup target vecSE n minN
  | n > VU.length vecSE - 1
  = n - 1
  | otherwise
  = let arm@( start , end ) = vecSE VU.! n
        mArm@(mStart, mEnd) = vecSE VU.! minN
        newMinN             = if end < mEnd then n else minN
    in  if target <= start
          then newMinN
          else searchMinEndNOfDup target vecSE (n + 1) newMinN

searchOverDupN :: Int -> VU.Vector (Int, Int) -> Int -> Int
searchOverDupN target vecSE n
  | n > VU.length vecSE - 1
  = n
  | otherwise
  = let arm@(start, end) = vecSE VU.! n
    in  if target <= start then n else searchOverDupN target vecSE (n + 1)

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

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

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

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

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

--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)

knappsack :: Int -> [(Int, Int)] -> VU.Vector Int
knappsack maxW [] = VU.replicate (maxW + 1) 0
knappsack maxW ((w, v) : xs) =
  let tailDP = knappsack maxW xs
  in  VU.generate (maxW + 1) $ \i -> if w <= i
        then max (tailDP VU.! i) (tailDP VU.! (i - w) + v)
        else tailDP VU.! i

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]

lcsTable :: BS.ByteString -> BS.ByteString -> V.Vector (VU.Vector Int)
lcsTable xs ys = V.scanl step (VU.replicate (m + 1) 0) xs'
 where
  n   = BS.length xs
  m   = BS.length ys
  xs' = V.generate n $ BSC8.index xs :: V.Vector Char
  ys' = VU.generate m $ BSC8.index ys :: VU.Vector Char
  step :: VU.Vector Int -> Char -> VU.Vector Int
  step v x = VU.scanl innerStep 0 (VU.zip3 v (VU.tail v) ys')
   where
    innerStep :: Int -> (Int, Int, Char) -> Int
    innerStep a (b, c, y) | x == y    = 1 + b
                          | otherwise = max a c
{-
main = do
xs <- BS.getLine
ys <- BS.getLine
print $ VU.last $ V.last $ lcsTable xs ys
-}
{-
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 : 200 points

Problem Statement

In a factory, there are N robots placed on a number line.
Robot i is placed at coordinate X_i and can extend its arms of length L_i in both directions, positive and negative.

We want to remove zero or more robots so that the movable ranges of arms of no two remaining robots intersect.
Here, for each i (1 \leq i \leq N), the movable range of arms of Robot i is the part of the number line between the coordinates X_i - L_i and X_i + L_i, excluding the endpoints.

Find the maximum number of robots that we can keep.

Constraints

1 \leq N \leq 100,000

0 \leq X_i \leq 10^9 (1 \leq i \leq N)

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

If i \neq j, X_i \neq X_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 L_1
X_2 L_2
\vdots
X_N L_N

Output

Print the maximum number of robots that we can keep.

Sample Input 1

4
2 4
4 3
9 3
100 5

Sample Output 1

3

By removing Robot 2, we can keep the other three robots.

Sample Input 2

2
8 20
1 10

Sample Output 2

1

Sample Input 3

5
10 1
2 1
4 1
6 1
8 1

Sample Output 3

5


{-# 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.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 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 <- readInt <$> getLine
  as_ <- getVecULn n rIntS
  bs_ <- getVecULn n rIntS
  let !totSort = VU.create $ do
        vec <- VU.unsafeThaw $ VU.indexed $ as_ VU.++ bs_
        vait_sortBy (compare `on` swap) vec; return vec
      lenAs = VU.length as_
      !(!as,!bs,!numVals) = runST $ do
        as <- VUM.new lenAs
        bs <- VUM.new (VU.length bs_)
        if VU.null totSort then return (VU.empty,VU.empty,0) else do
          (!kLast,!_) <- VU.foldM'
            (\ (!kprev,!vprev) (!i,!v) -> do
                let !k = if vprev == v then kprev else kprev+1
                if i < lenAs
                  then VUM.unsafeWrite as i k
                  else VUM.unsafeWrite bs (i-lenAs) k
                return (k,v))
            (0,snd $ VU.head totSort) totSort
          liftA2 (,,kLast+1) (VU.unsafeFreeze as) (VU.unsafeFreeze bs)
  -- print as
  -- print bs
  print $ fromMaybe (-1) $ query n numVals as bs
  return ()

{-# INLINE query #-}
query :: Int -> Int -> VU.Vector Int -> VU.Vector Int -> Maybe Int
query n numVals as bs = ret $ go 0 0
  where
    calc !inSeq !maxSeq
      | VU.any (\ !i -> VU.unsafeIndex as i < maxSeq
                 && VU.unsafeIndex bs i < maxSeq)
        $ enumUnsetBits n inSeq = 254
      | otherwise = VU.minimum $ VU.cons 254
        $ VU.map (\(!bef,!i,!v) -> bef + go (setBit inSeq i) v)
        $ VU.filter (\(!_,!_,!v) -> v>=maxSeq)
        $ VU.imap (\ !bef !i -> if xor i cnt .&. 1 /= 0
                   then (bef,i,) $! VU.unsafeIndex bs i
                   else (bef,i,) $! VU.unsafeIndex as i)
        $ enumUnsetBits n inSeq
      where
        !cnt = popCount inSeq
    go !inSeq !maxSeq = BSU.accursedUnutterablePerformIO $ do
      prevVal <- toInt <$> VUM.unsafeRead (dp `V.unsafeIndex` maxSeq) inSeq
      if prevVal < 255 then return prevVal else do
        VUM.unsafeWrite (dp `V.unsafeIndex` maxSeq) inSeq $! toW8 res
        return res
      where res = calc inSeq maxSeq
    {-# NOINLINE dp #-}
    !dp = unsafePerformIO $ do
      dpLin <- VUM.replicate (numVals * bit n) (255 :: Word8)
      let !dp = mLinToMat numVals (bit n) dpLin
      V.forM_ dp $ \ !vec -> VUM.unsafeWrite vec bMask 0
      return dp
    !bMask = bit n - 1
    ret x | x >= 254 = Nothing
          | otherwise = Just x

enumUnsetBits :: forall b. FiniteBits b => Int -> b -> VU.Vector Int
{-# INLINE enumUnsetBits #-}
enumUnsetBits !n !x = VU.filter (not . testBit x) $ VU.generate n id

enumSetBits :: forall b. FiniteBits b => Int -> b -> VU.Vector Int
{-# INLINE enumSetBits #-}
enumSetBits !n !x = VU.filter (testBit x) $ VU.generate n id
  -- what, this is faster
{- LEGACY:
enumSetBits _ = VU.unfoldrN (finiteBitSize (undefined :: b)) $ \ !b ->
  let !i = countTrailingZeros b
  in if b == zeroBits then Nothing else Just (i,clearBit b i)
-}

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

#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) $ \case
      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

Score : 700 points

Problem Statement

We have N cards numbered 1, 2, ..., N.
Card i (1 \leq i \leq N) has an integer A_i written in red ink on one side and an integer B_i written in blue ink on the other side.
Initially, these cards are arranged from left to right in the order from Card 1 to Card N, with the red numbers facing up.

Determine whether it is possible to have a non-decreasing sequence facing up from left to right (that is, for each i (1 \leq i \leq N - 1), the integer facing up on the (i+1)-th card from the left is not less than the integer facing up on the i-th card from the left) by repeating the operation below. If the answer is yes, find the minimum number of operations required to achieve it.

Choose an integer i (1 \leq i \leq N - 1).
Swap the i-th and (i+1)-th cards from the left, then flip these two cards.

Constraints

1 \leq N \leq 18

1 \leq A_i, B_i \leq 50 (1 \leq 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
B_1 B_2 ... B_N

Output

If it is impossible to have a non-decreasing sequence, print -1.
If it is possible, print the minimum number of operations required to achieve it.

Sample Input 1

3
3 4 3
3 2 3

Sample Output 1

1

By doing the operation once with i = 1, we have a sequence [2, 3, 3] facing up, which is non-decreasing.

Sample Input 2

2
2 1
1 2

Sample Output 2

-1

After any number of operations, we have the sequence [2, 1] facing up, which is not non-decreasing.

Sample Input 3

4
1 2 3 4
5 6 7 8

Sample Output 3

0

No operation may be required.

Sample Input 4

5
28 15 22 43 31
20 22 43 33 32

Sample Output 4

-1

Sample Input 5

5
4 46 6 38 43
33 15 18 27 37

Sample Output 5

3


import Data.Char
main = do
  alphabet <- getChar
  putChar $ chr $ ord alphabet + 1

Score : 100 points

Problem Statement

Given is a lowercase English letter C that is not z. Print the letter that follows C in alphabetical order.

Constraints

C is a lowercase English letter that is not z.

Input

Input is given from Standard Input in the following format:

C

Output

Print the letter that follows C in alphabetical order.

Sample Input 1

a

Sample Output 1

b

a is followed by b.

Sample Input 2

y

Sample Output 2

z

y is followed by z.


main = do
    c <- getChar
    putChar $ succ c

main = do
    c <- getChar
    putChar $ succ c