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

main :: IO ()
main = do
  [n, m] <- readInts
  input <- readNIntegers n
  print $ solve n m input

solve :: Int -> Int -> [[Integer]] -> Integer
solve n m input = maximum $ map gettopmsum [0 .. 7]
  where
    gettopmsum :: Int -> Integer
    gettopmsum flag = sum $ take m $ reverse $ sort $ prepro flag
    prepro flag = map (\x -> sum $ map (\y -> (fst y) (snd y)) $ zip prefuncs x) input
      where
        prefuncs = map (\x ->
          if flag .&. (bit x) /= 0
            then ((-) 0)
            else ((+) 0)
          ) [0 .. 2]

comb :: [a] -> Int -> [[a]]
comb _ 0     = [[]]
comb [] _     = []
comb (x:xs) n = map (x:) (comb xs (n-1)) ++ comb xs n

-- 以下ライブラリ

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

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

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

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

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

toTup2 :: [[a]] -> [(a, a)]
toTup2 = map (\ys -> case ys of y : z : zs -> (y, z))

encIdx2 :: Int -> (Int, Int) -> Int
encIdx2 mx (y, x) = y * mx + x

decIdx2 :: Int -> Int -> (Int, Int)
decIdx2 mx idx = (idx `div` mx, idx `mod` mx)

encIdx3 :: (Int, Int) -> (Int, Int, Int) -> Int
encIdx3 (my, mx) (z, y, x) = z * my * mx + y * mx + x

decIdx3 :: (Int, Int) -> Int -> (Int, Int, Int)
decIdx3 (my, mx) idx = (z, y, x)
  where
    basez = my * mx
    z = idx `div` basez
    y = (idx `mod` basez) `div` mx
    x = idx `mod` mx

while :: Monad m => m Bool -> m () -> m ()
while cond body = do
  b <- cond
  when b $ do
    body
    while cond body

Score: 400 points

Problem Statement

Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100.

The shop sells N kinds of cakes.

Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The i-th kind of cake has the beauty of x_i, the tastiness of y_i and the popularity of z_i.

These values may be zero or negative.

Ringo has decided to have M pieces of cakes here. He will choose the set of cakes as follows:

Do not have two or more pieces of the same kind of cake.

Under the condition above, choose the set of cakes to maximize (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity).

Find the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.

Constraints

N is an integer between 1 and 1 \ 000 (inclusive).

M is an integer between 0 and N (inclusive).

x_i, y_i, z_i \ (1 \leq i \leq N) are integers between -10 \ 000 \ 000 \ 000 and 10 \ 000 \ 000 \ 000 (inclusive).

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1 z_1
x_2 y_2 z_2
: :
x_N y_N z_N

Output

Print the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.

Sample Input 1

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

Sample Output 1

56

Consider having the 2-nd, 4-th and 5-th kinds of cakes. The total beauty, tastiness and popularity will be as follows:

Beauty: 1 + 3 + 9 = 13

Tastiness: 5 + 5 + 7 = 17

Popularity: 9 + 8 + 9 = 26

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 13 + 17 + 26 = 56. This is the maximum value.

Sample Input 2

5 3
1 -2 3
-4 5 -6
7 -8 -9
-10 11 -12
13 -14 15

Sample Output 2

54

Consider having the 1-st, 3-rd and 5-th kinds of cakes. The total beauty, tastiness and popularity will be as follows:

Beauty: 1 + 7 + 13 = 21

Tastiness: (-2) + (-8) + (-14) = -24

Popularity: 3 + (-9) + 15 = 9

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 21 + 24 + 9 = 54. This is the maximum value.

Sample Input 3

10 5
10 -80 21
23 8 38
-94 28 11
-26 -2 18
-69 72 79
-26 -86 -54
-72 -50 59
21 65 -32
40 -94 87
-62 18 82

Sample Output 3

638

If we have the 3-rd, 4-th, 5-th, 7-th and 10-th kinds of cakes, the total beauty, tastiness and popularity will be -323, 66 and 249, respectively.

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 323 + 66 + 249 = 638. This is the maximum value.

Sample Input 4

3 2
2000000000 -9000000000 4000000000
7000000000 -5000000000 3000000000
6000000000 -1000000000 8000000000

Sample Output 4

30000000000

The values of the beauty, tastiness and popularity of the cakes and the value to be printed may not fit into 32-bit integers.


import Control.Applicative
import Data.List
import Control.Monad
import Data.Function
import Data.Array

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

answer [a,b] = b2 - b where
    n = b-a
    b2 = sum [1..n]

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

Score : 200 points

Problem Statement

In some village, there are 999 towers that are 1,(1+2),(1+2+3),...,(1+2+3+...+999) meters high from west to east, at intervals of 1 meter.

It had been snowing for a while before it finally stopped. For some two adjacent towers located 1 meter apart, we measured the lengths of the parts of those towers that are not covered with snow, and the results are a meters for the west tower, and b meters for the east tower.

Assuming that the depth of snow cover and the altitude are the same everywhere in the village, find the amount of the snow cover.

Assume also that the depth of the snow cover is always at least 1 meter.

Constraints

1 \leq a < b < 499500(=1+2+3+...+999)

All values in input are integers.

There is no input that contradicts the assumption.

Input

Input is given from Standard Input in the following format:

a b

Output

If the depth of the snow cover is x meters, print x as an integer.

Sample Input 1

8 13

Sample Output 1

2

The heights of the two towers are 10 meters and 15 meters, respectively.
Thus, we can see that the depth of the snow cover is 2 meters.

Sample Input 2

54 65

Sample Output 2

1

Submitted source-code file size, in bytes.

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

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


{-# LANGUAGE FlexibleContexts #-}
main :: IO ()
main = do
  n <- readLn :: IO Int
  let count6 = map (count 6) [0..n]
      count9 = map (count 9) [n,n-1..0]
  print $ minimum $ zipWith (+) count6 count9

count :: Int -> Int -> Int
count unit money = let idx = ceiling $ logBase (fromIntegral unit) $ fromIntegral money
                   in  go (map (unit^) [idx,idx-1..0]) money 0
  where go _ 0 c      = c
        go (x:xs) m c = go xs (m`mod`x) (c + m`div`x)

Score : 300 points

Problem Statement

To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation:

1 yen (the currency of Japan)

6 yen, 6^2(=36) yen, 6^3(=216) yen, ...

9 yen, 9^2(=81) yen, 9^3(=729) yen, ...

At least how many operations are required to withdraw exactly N yen in total?

It is not allowed to re-deposit the money you withdrew.

Constraints

1 \leq N \leq 100000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If at least x operations are required to withdraw exactly N yen in total, print x.

Sample Input 1

127

Sample Output 1

4

By withdrawing 1 yen, 9 yen, 36(=6^2) yen and 81(=9^2) yen, we can withdraw 127 yen in four operations.

Sample Input 2

3

Sample Output 2

3

By withdrawing 1 yen three times, we can withdraw 3 yen in three operations.

Sample Input 3

44852

Sample Output 3

16


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

import Debug.Trace (trace)

-- utility functions

--tr x = trace (show x) x
tr = id

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

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

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

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

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

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

dp :: (Array Int Int -> Int -> Int) -> Int -> Int
dp f n = result ! n where
  result = listArray (0,n) $ map nth [0..]
  nth i = f result (tr i)

-- main

amount = [1,6,36,216,1296,7776,46656,9,81,729,6561,59049]

solv n = dp f n where
  f t 0 = 0
  f t i = 1 + minimum [t!j| a<-amount, let j=i-a, j>=0]

main = do
  n <- read <$> getLine
  print $ solv n


main = getLine >>= putStrLn.show.answer.(read :: String -> Int)

answer n = minimum $ n:map (f 0) (zip [0..n] [0..n]) where
    f v (i,nn) = if i > 0 then f (v+mod i 6) (div i 6,nn) else g v (n-nn)
    g v i = if i > 0 then g (v+mod i 9) (div i 9) else v


{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE TypeSynonymInstances #-}

import           Control.Applicative
import           Control.DeepSeq
import           Control.Monad
import           Control.Monad.ST
import qualified Data.Array                  as A
import qualified Data.Array.IArray           as IA
import qualified Data.Array.IO               as AI
import qualified Data.Array.MArray           as MA
import qualified Data.Array.ST               as STA
import qualified Data.Array.Unboxed          as AU
import           Data.Bits
import qualified Data.ByteString.Char8       as BS
import           Data.Char
import qualified Data.Graph                  as G
import           Data.Int
import qualified Data.IntMap                 as IM
import qualified Data.IntSet                 as IS
import           Data.List
import qualified Data.Map.Strict             as M
import           Data.Maybe
import           Data.Ord
import qualified Data.Sequence               as SQ
import qualified Data.Set                    as S
import           Data.Time
import qualified Data.Tree                   as T
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

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

readInts :: Int -> IO [[Int]]
readInts n = replicateM n readInt

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

readIntegers :: Int -> IO [[Integer]]
readIntegers n = replicateM n readInteger

readString :: IO [String]
readString = map BS.unpack . BS.words <$> BS.getLine

readStrings :: Int -> IO [[String]]
readStrings n = replicateM n <$> readString

toPair :: [a] -> (a, a)
toPair [x, y] = (x, y)

count :: Eq a => a -> [a] -> Int
count a as = length $ filter (== a) as

put :: Show a => a -> IO ()
put = putStr . show

putLn :: Show a => a -> IO ()
putLn = print

putList :: Show a => [a] -> IO ()
putList [n] = put n
putList (n:ns) = do
  put n
  putStr " "
  putList ns

putStrList :: [String] -> IO ()
putStrList [n] = putStr n
putStrList (n:ns) = do
  putStr n
  putStr " "
  putStrList ns

main = do
  [a, b] <- readInt
  put $ maximum [a - b, a + b, a * b]

Score : 100 points

Problem Statement

You are given two integers A and B.
Find the largest value among A+B, A-B and A \times B.

Constraints

-1000 \leq A,B \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the largest value among A+B, A-B and A \times B.

Sample Input 1

3 1

Sample Output 1

4

3+1=4, 3-1=2 and 3 \times 1=3. The largest among them is 4.

Sample Input 2

4 -2

Sample Output 2

6

The largest is 4 - (-2) = 6.

Sample Input 3

0 0

Sample Output 3

0


main :: IO ()
main = do
  [a, b] <- map read . words <$> getLine :: IO [Int]
  print $ maximum $ map (\f -> f a b) [(+), (-), (*)]


maxout [x] = x
maxout (x:y:ys)
    |x>=y = maxout (x:ys)
    |x <y = maxout (y:ys)

main = do
    n <- readLn
    m <- readLn
    print $ maxout [n+m, n-m, n*m]


import Data.Set
main=do
 getLine
 s<-getLine
 print$f s []
f[]a=0
f s@(x:xs) a=max(size$intersection(fromList s)$fromList a)(f xs$x:a)

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters.
We will cut this string at one position into two strings X and Y.
Here, we would like to maximize the number of different letters contained in both X and Y.
Find the largest possible number of different letters contained in both X and Y when we cut the string at the optimal position.

Constraints

2 \leq N \leq 100

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the largest possible number of different letters contained in both X and Y.

Sample Input 1

6
aabbca

Sample Output 1

2

If we cut the string between the third and fourth letters into X = aab and Y = bca, the letters contained in both X and Y are a and b.
There will never be three or more different letters contained in both X and Y, so the answer is 2.

Sample Input 2

10
aaaaaaaaaa

Sample Output 2

1

However we divide S, only a will be contained in both X and Y.

Sample Input 3

45
tgxgdqkyjzhyputjjtllptdfxocrylqfqjynmfbfucbir

Sample Output 3

9


east :: String -> Int-> [Int]
east [] n = []
east (x:xs) n
  | x == 'E' = (n+1) : (east xs (n+1))
  | otherwise = n : (east xs n)

west :: String -> Int -> [Int]
west [] n = []
west (x:xs) n
  | x == 'W' = (n+1) : (west xs (n+1))
  | otherwise = n : (west xs n)

main = do
  n <- (read :: String -> Int) <$> getLine
  s <- getLine
  let y = zipWith (+) (reverse $ east (reverse s) 0) (west s 0)
  putStrLn . show $ (-) (minimum y) 1

Score : 300 points

Problem Statement

There are N people standing in a row from west to east.
Each person is facing east or west.
The directions of the people is given as a string S of length N.
The i-th person from the west is facing east if S_i = E, and west if S_i = W.

You will appoint one of the N people as the leader, then command the rest of them to face in the direction of the leader.
Here, we do not care which direction the leader is facing.

The people in the row hate to change their directions, so you would like to select the leader so that the number of people who have to change their directions is minimized.
Find the minimum number of people who have to change their directions.

Constraints

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

|S| = N

S_i is E or W.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of people who have to change their directions.

Sample Input 1

5
WEEWW

Sample Output 1

1

Assume that we appoint the third person from the west as the leader.
Then, the first person from the west needs to face east and has to turn around.
The other people do not need to change their directions, so the number of people who have to change their directions is 1 in this case.
It is not possible to have 0 people who have to change their directions, so the answer is 1.

Sample Input 2

12
WEWEWEEEWWWE

Sample Output 2

4

Sample Input 3

8
WWWWWEEE

Sample Output 3

3


solve :: String -> Int
solve s = minimum $ zipWith (+) (scanl (\n x -> if x == 'W' then n+1 else n) 0 (init s))
                                (scanr (\x n -> if x == 'E' then n+1 else n) 0 (tail s))

main :: IO ()
main = do
  _n <- read <$> getLine :: IO [Int]
  s <- getLine :: IO String
  print $ solve s


import Data.List

main = do
  getLine
  s <- getLine
  let minN = min (length s1) (length s2)
        where (s1, s2) = let s' = sort s in span (== head s') $ s'
  print minN


import Control.Applicative
import Control.Monad
import Data.List
import Data.Array
import qualified Data.IntMap as I
import qualified Data.Map as M

main = do
    n <- readLn
    s <- getLine
    print $ solve n s

solve :: Int -> String -> Int
solve n s = minimum (g s) + h s

h :: String -> Int
h s = length $ filter ('E'==) (tail s)

g :: String -> [Int]
g s = foldl f [0] (zip s (tail s))

f :: [Int] -> (Char,Char) -> [Int]
f [] _ = [0]
f all@(x:xs) (c,d) = x':all
    where x' = x + cc + dd
          cc = if c == 'W' then 1 else 0
          dd = if d == 'E' then -1 else 0


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

Score : 100 points

Problem Statement

Three people, A, B and C, are trying to communicate using transceivers.
They are standing along a number line, and the coordinates of A, B and C are a, b and c (in meters), respectively.
Two people can directly communicate when the distance between them is at most d meters.
Determine if A and C can communicate, either directly or indirectly.
Here, A and C can indirectly communicate when A and B can directly communicate and also B and C can directly communicate.

Constraints

1 ≤ a,b,c ≤ 100

1 ≤ d ≤ 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

If A and C can communicate, print Yes; if they cannot, print No.

Sample Input 1

4 7 9 3

Sample Output 1

Yes

A and B can directly communicate, and also B and C can directly communicate, so we should print Yes.

Sample Input 2

100 10 1 2

Sample Output 2

No

They cannot communicate in this case.

Sample Input 3

10 10 10 1

Sample Output 3

Yes

There can be multiple people at the same position.

Sample Input 4

1 100 2 10

Sample Output 4

Yes


import Data.List

substrings s = concat [substrings' s i | i<-[1..(min 5 (length s))]]
  where
    substrings' s@(x:xs) i
      | length s == i = [s]
      | otherwise = (take i s) : (substrings' xs i)

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

  putStrLn $ (solve [] (substrings s)) !! (k-1)

  where
    solve :: [String] -> [String] -> [String]
    solve sorted [] = sorted
    solve sorted (x:xs) = solve s xs
      where s = sort' sorted x

    sort' sorted x
      | elem x sorted = sorted
      | length sorted < 5 = sort $ x:sorted
      | last sorted <= x = sorted
      | otherwise = init (sort $ x:sorted)


import Data.List

main :: IO ()
main = do
  x <- readLn
  print . last $ sort [n ^ m | n <- [1..40], m <- [2..10], n ^ m <= x]

Score : 200 points

Problem Statement

You are given a positive integer X.
Find the largest perfect power that is at most X.
Here, a perfect power is an integer that can be represented as b^p, where b is an integer not less than 1 and p is an integer not less than 2.

Constraints

1 ≤ X ≤ 1000

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the largest perfect power that is at most X.

Sample Input 1

10

Sample Output 1

9

There are four perfect powers that are at most 10: 1, 4, 8 and 9.
We should print the largest among them, 9.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

999

Sample Output 3

961


main :: IO ()
main = do
  n <- readLn
  print $ last [x ^ 2 | x <- [1..40], x ^ 2 <= n]


{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Maybe
import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import Debug.Trace

solve :: Int -> Int -> [Int] -> [(Int,Int)] -> Int
solve n m ps xys = answer where

  grp0 = foldr (uncurry uftMerge) IM.empty xys

  im1 :: IM.IntMap (IS.IntSet, IS.IntSet)
--  grp0xxx = (trace ("grp0" ++ show grp0) grp0)
  grp0xxx = grp0
  (im1, _) = foldr op (IM.empty, grp0xxx) (zip [1..] ps) where
    op :: (Int, Int) -> (IM.IntMap (IS.IntSet, IS.IntSet), IM.IntMap Int)
       -> (IM.IntMap (IS.IntSet, IS.IntSet), IM.IntMap Int)
    op (n, p) (jm, grp) = (jm', grp') where
      (r, grp') = getRoot n grp
      jm' = IM.alter f r jm where
        f Nothing         = Just (IS.singleton n, IS.singleton p)
        f (Just (cn, cp)) = Just (IS.insert n cn, IS.insert p cp)

  answer = foldr op 0 im1 where
    op (cn, cp) sum = sum + IS.size (IS.intersection cn cp)

uftMerge :: Int -> Int -> IM.IntMap Int -> IM.IntMap Int
uftMerge x y im | rx == ry = im
                | otherwise = IM.insert rx ry im2
  where (rx, im1) = getRoot x im
        (ry, im2) = getRoot y im1

getRoot :: Int -> IM.IntMap Int -> (Int, IM.IntMap Int)
getRoot x im = case IM.lookup x im of
                 Nothing -> (x, im)
                 Just y -> let (root, im1) = getRoot y im
                           in (root, IM.adjust (const root) x im1)

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

tmain :: B.ByteString -> Int
tmain cont =
  let remLines0 = map B.words (B.lines cont)
      [bs_n,bs_m]:remLines1 = remLines0
      n = readBInt bs_n
      m = readBInt bs_m
      line2:remLines2 = remLines1
      ps = map readBInt line2
      xys = map (\[x1,x2] -> (readBInt x1,readBInt x2)) remLines2
  in solve n m ps xys

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

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

Score : 400 points

Problem Statement

We have a permutation of the integers from 1 through N, p_1, p_2, .., p_N.
We also have M pairs of two integers between 1 and N (inclusive), represented as (x_1,y_1), (x_2,y_2), .., (x_M,y_M).
AtCoDeer the deer is going to perform the following operation on p as many times as desired so that the number of i (1 ≤ i ≤ N) such that p_i = i is maximized:

Choose j such that 1 ≤ j ≤ M, and swap p_{x_j} and p_{y_j}.

Find the maximum possible number of i such that p_i = i after operations.

Constraints

2 ≤ N ≤ 10^5

1 ≤ M ≤ 10^5

p is a permutation of integers from 1 through N.

1 ≤ x_j,y_j ≤ N

x_j ≠ y_j

If i ≠ j, \{x_i,y_i\} ≠ \{x_j,y_j\}.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
p_1 p_2 .. p_N
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the maximum possible number of i such that p_i = i after operations.

Sample Input 1

5 2
5 3 1 4 2
1 3
5 4

Sample Output 1

2

If we perform the operation by choosing j=1, p becomes 1 3 5 4 2, which is optimal, so the answer is 2.

Sample Input 2

3 2
3 2 1
1 2
2 3

Sample Output 2

3

If we perform the operation by, for example, choosing j=1, j=2, j=1 in this order, p becomes 1 2 3, which is obviously optimal.
Note that we may choose the same j any number of times.

Sample Input 3

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

Sample Output 3

8

Sample Input 4

5 1
1 2 3 4 5
1 5

Sample Output 4

5

We do not have to perform the operation.


import Control.Monad (replicateM)
import Data.Array.IO

import Control.Monad.ST
import Data.Array.ST

makeSets :: Int -> ST s (STUArray s Int Int)
makeSets n = newListArray (1, n) [1..n]

find :: STUArray s Int Int -> Int -> ST s Int
find arr x = do
  parent <- readArray arr x
  if parent == x
    then return x
    else do
      root <- find arr parent
      writeArray arr x root
      return root

union :: STUArray s Int Int -> Int -> Int -> ST s ()
union sets x y = do
  x_root <- find sets x
  y_root <- find sets y
  writeArray sets x_root y_root

readOperation :: String -> (Int, Int)
readOperation s = let [x, y] = map read . words $ s in (x, y)

solve :: [(Int, Int)] -> [Int] -> Int
solve operations permutation = runST $ do
    sets <- makeSets (length permutation)
    mapM_ (uncurry (union sets)) operations
    sum <$> mapM (beTogether sets) (zip [1..] permutation)
  where
    beTogether sets (i, x) = do
      i_root <- find sets i
      x_root <- find sets x
      if i_root == x_root
        then return 1
        else return 0

main :: IO ()
main = do
  [_n, m] <- map read . words <$> getLine
  permutation <- map read . words <$> getLine
  operations <- replicateM m (readOperation <$> getLine)
  print $ solve operations permutation


import Data.List

-- 与えられた文字列の最大n文字までの部分文字列のリスト
-- 部分文字列を全てに求めると爆発するのでn文字で足きり
-- n+1文字の文字列から先頭から1,..,n文字までの部分文字列が辞書順で前に来る
substrings :: Int -> String -> [String]
substrings n s = foldl (++) [] $ map (heads n) $ tails s

-- 先頭から1文字,2文字,...,n文字までの部分文字列
heads :: Int -> String -> [String]
heads n s = map ((flip take) s) [1..(minimum [n, length s])]

pickup_small :: Ord a => Int -> [a] -> [a]
pickup_small n l = take' n $ sort $ nub l
    where
        take' n l = take (minimum [n, length l]) l

kth :: Int -> String -> String
kth k s = (foldr f [] $ substrings k s) !! (k - 1)
    where
        f e r = pickup_small k (e:r)

main = do
    s <- getLine
    k <- readLn
    putStrLn $ kth k s

Score : 300 points

Problem Statement

You are given a string s.
Among the different substrings of s, print the K-th lexicographically smallest one.

A substring of s is a string obtained by taking out a non-empty contiguous part in s.
For example, if s = ababc, a, bab and ababc are substrings of s, while ac, z and an empty string are not.
Also, we say that substrings are different when they are different as strings.

Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.

Constraints

1 ≤ |s| ≤ 5000

s consists of lowercase English letters.

1 ≤ K ≤ 5

s has at least K different substrings.

Partial Score

200 points will be awarded as a partial score for passing the test set satisfying |s| ≤ 50.

Input

Input is given from Standard Input in the following format:

s
K

Output

Print the K-th lexicographically smallest substring of K.

Sample Input 1

aba
4

Sample Output 1

b

s has five substrings: a, b, ab, ba and aba.
Among them, we should print the fourth smallest one, b.
Note that we do not count a twice.

Sample Input 2

atcoderandatcodeer
5

Sample Output 2

andat

Sample Input 3

z
1

Sample Output 3

z


import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.List
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

newUF n = VUM.replicate n (-1 :: Int)

root uf x = do
    p <- VUM.read uf x
    if p < 0
        then return x
        else do
            r <- root uf p
            VUM.write uf x r
            return r

same uf x y = liftM2 (==) (root uf x) (root uf y)

unite uf x y = do
    px <- root uf x
    py <- root uf y
    when (px /= py) $ do
        sx <- VUM.read uf px
        sy <- VUM.read uf py
        let (par, chld) = if sx < sy then (px, py)　else (py, px)
        VUM.write uf chld par
        VUM.write uf par (sx + sy)

size uf x = do
    px <- root uf x
    s <- VUM.read uf px
    return $ abs s

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

main = do
    [n,m] <- getIntList
    ps <- zip [0..] . map pred <$> getIntList
    xy <- replicateM m $ do
        [x,y] <- getIntList
        return (x-1,y-1)
    uf <- newUF n
    forM_ xy $ \(x,y) -> do
        unite uf x y
    ans <- sum <$> mapM (\(i,p) -> do
                       b <- same uf i p
                       return (if b then 1 else 0)) ps
    print ans


main :: IO ()
main = do
  ab <- map read . words <$> getLine
  print $ solve ab

solve :: [Int] -> Int
solve = minimum

Score: 100 points

Problem Statement

In AtCoder Kingdom, Gregorian calendar is used, and dates are written in the "year-month-day" order, or the "month-day" order without the year.

For example, May 3, 2018 is written as 2018-5-3, or 5-3 without the year.

In this country, a date is called Takahashi when the month and the day are equal as numbers. For example, 5-5 is Takahashi.

How many days from 2018-1-1 through 2018-a-b are Takahashi?

Constraints

a is an integer between 1 and 12 (inclusive).

b is an integer between 1 and 31 (inclusive).

2018-a-b is a valid date in Gregorian calendar.

Input

Input is given from Standard Input in the following format:

a b

Output

Print the number of days from 2018-1-1 through 2018-a-b that are Takahashi.

Sample Input 1

5 5

Sample Output 1

5

There are five days that are Takahashi: 1-1, 2-2, 3-3, 4-4 and 5-5.

Sample Input 2

2 1

Sample Output 2

1

There is only one day that is Takahashi: 1-1.

Sample Input 3

11 30

Sample Output 3

11

There are eleven days that are Takahashi: 1-1, 2-2, 3-3, 4-4, 5-5, 6-6, 7-7, 8-8, 9-9, 10-10 and 11-11.


main = do
    (a:b:_) <- (fmap read . words) <$> getLine
    if a<=b
        then print a
        else print (a-1)


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

main = do
  input <- B.getContents
  let [a,b] = map readInt . B.words $ input
  print (solve a b)

readInt :: B.ByteString -> Int
readInt s = case B.readInt s of Just (n,_) -> n

solve :: Int -> Int -> Int
solve a b =
  length [(i,i) |i<-[1..12], (i,i)<=(a,b)]


import Data.List

main = do
  (a:b:c:xs) <- map read . words <$> getLine
  d <- read <$> getLine
  putStrLn . show $ solve a b c d

solve a b c d =
  let (t:s:f:xs) = sort [a,b,c]
  in t + s + f * d

Score: 200 points

Problem Statement

There are three positive integers A, B and C written on a blackboard. E869120 performs the following operation K times:

Choose one integer written on the blackboard and let the chosen integer be n. Replace the chosen integer with 2n.

What is the largest possible sum of the integers written on the blackboard after K operations?

Constraints

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

K is an integer between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

A B C
K

Output

Print the largest possible sum of the integers written on the blackboard after K operations by E869220.

Sample Input 1

5 3 11
1

Sample Output 1

30

In this sample, 5, 3, 11 are initially written on the blackboard, and E869120 can perform the operation once.

There are three choices:

Double 5: The integers written on the board after the operation are 10, 3, 11.

Double 3: The integers written on the board after the operation are 5, 6, 11.

Double 11: The integers written on the board after the operation are 5, 3, 22.

If he chooses 3., the sum of the integers written on the board afterwards is 5 + 3 + 22 = 30, which is the largest among 1. through 3.

Sample Input 2

3 3 4
2

Sample Output 2

22

E869120 can perform the operation twice. The sum of the integers eventually written on the blackboard is maximized as follows:

First, double 4. The integers written on the board are now 3, 3, 8.

Next, double 8. The integers written on the board are now 3, 3, 16.

Then, the sum of the integers eventually written on the blackboard is 3 + 3 + 16 = 22.


import Data.List

main = do
    [a, b, c] <- sort . map read . words <$> getLine :: IO [Int]
    k <- read <$> getLine :: IO Int
    print $ a + b + c * pow 2 k

pow n 0 = 1
pow n k = n * pow n (k-1)


import Data.List
import Control.Monad

main = do
    (h:w:_) <- (fmap read . words) <$> getLine
    matrix <- replicateM h getLine
    let checkH = and $ map outHori matrix
    let matrixT = transpose matrix
    let checkV = and $ map outHori matrixT
    if (checkH && checkV)
        then print "Yes"
        else print "No"

outHori :: String -> Bool
outHori str = (take 2 str == "#.") || isInfixOf ".#." str || (drop ((length str)-2) str == ".#")

Score: 300 points

Problem Statement

We have a canvas divided into a grid with H rows and W columns. The square at the i-th row from the top and the j-th column from the left is represented as (i, j).

Initially, all the squares are white. square1001 wants to draw a picture with black paint. His specific objective is to make Square (i, j) black when s_{i, j}= #, and to make Square (i, j) white when s_{i, j}= ..

However, since he is not a good painter, he can only choose two squares that are horizontally or vertically adjacent and paint those squares black, for some number of times (possibly zero). He may choose squares that are already painted black, in which case the color of those squares remain black.

Determine if square1001 can achieve his objective.

Constraints

H is an integer between 1 and 50 (inclusive).

W is an integer between 1 and 50 (inclusive).

For every (i, j) (1 \leq i \leq H, 1 \leq j \leq W), s_{i, j} is # or ..

Input

Input is given from Standard Input in the following format:

H W
s_{1, 1} s_{1, 2} s_{1, 3} ... s_{1, W}
s_{2, 1} s_{2, 2} s_{2, 3} ... s_{2, W}
: :
s_{H, 1} s_{H, 2} s_{H, 3} ... s_{H, W}

Output

If square1001 can achieve his objective, print Yes; if he cannot, print No.

Sample Input 1

3 3
.#.
###
.#.

Sample Output 1

Yes

One possible way to achieve the objective is shown in the figure below. Here, the squares being painted are marked by stars.

Sample Input 2

5 5
#.#.#
.#.#.
#.#.#
.#.#.
#.#.#

Sample Output 2

No

square1001 cannot achieve his objective here.

Sample Input 3

11 11
...#####...
.##.....##.
#..##.##..#
#..##.##..#
#.........#
#...###...#
.#########.
.#.#.#.#.#.
##.#.#.#.##
..##.#.##..
.##..#..##.

Sample Output 3

Yes


import qualified Data.Vector as V

main :: IO ()
main = do
  [h,w] <- map read . words <$> getLine
  t <- getTable
  putStrLn $ if solve t h w then "Yes" else "No"

getTable :: IO Table
getTable = V.fromList . map (V.fromList . map toBW) . lines <$> getContents
  where toBW '#' = B
        toBW '.' = W
        toBW _ = error "!"

solve :: Table -> Int -> Int -> Bool
solve tbl w h = all check [(i,j) | i <- [0..(w-1)], j <- [0..(h-1)]]
  where
    get (i,j) = tbl V.! j V.! i
    around (x,y) | x == 0 && y == 0 = [(1,0),(0,1)]
                 | x == 0 && y == h-1 = [(x,y-1),(x+1,y)]
                 | x == w-1 && y == 0 = [(x-1,y),(x,y+1)]
                 | x == w-1 && y == h-1 = [(x-1,y),(x,y-1)]
                 | x == 0 = [(x,y-1),(x,y+1),(x+1,y)]
                 | x == w-1 = [(x,y-1),(x,y+1),(x-1,y)]
                 | y == 0 = [(x-1,y),(x+1,y),(x,y+1)]
                 | y == h-1 = [(x-1,y),(x+1,y),(x,y-1)]
                 | otherwise = [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]
    check i | get i == W = True
            | otherwise = any (==B) $ [get n | n <- around i]

data BW = B | W deriving Eq

type Table = V.Vector (V.Vector BW)


import Control.Monad
import Text.Printf
import Control.Applicative
import Data.List as L

main :: IO()
main = do
  _ <- getLine
  a <- map read . words <$> getLine
  printf "%d" $ slv a

slv :: [Integer] -> Integer
slv a = slv' a 0
  where slv' a@(aa:aas) ret = slv' aas (ret + sum [if x == 0 then 1 else 0 | x <- scanl1 (+) a, x == 0])
        slv' [] ret = ret

Score : 200 points

Problem Statement

We have an integer sequence A, whose length is N.

Find the number of the non-empty contiguous subsequences of A whose sums are 0.
Note that we are counting the ways to take out subsequences.
That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from different positions.

Constraints

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

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

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

Find the number of the non-empty contiguous subsequences of A whose sum is 0.

Sample Input 1

6
1 3 -4 2 2 -2

Sample Output 1

3

There are three contiguous subsequences whose sums are 0: (1,3,-4), (-4,2,2) and (2,-2).

Sample Input 2

7
1 -1 1 -1 1 -1 1

Sample Output 2

12

In this case, some subsequences that have the same contents but are taken from different positions are counted individually.
For example, three occurrences of (1, -1) are counted.

Sample Input 3

5
1 -2 3 -4 5

Sample Output 3

0

There are no contiguous subsequences whose sums are 0.


import Data.Array
import Debug.Trace

main = do
  n <- readLn
  input <- getContents
  let tab = listArray ((1,1),(n,n)) $ concat $ lines $ input
  print (solve n tab)

type Table = Array (Int,Int) Char

isGood :: Table -> Bool
isGood tab =
  and [tab!(i,j) == tab!(j,i) | i<-[s1..t1], j<-[i..t2]]
  where
    ((s1,s2),(t1,t2)) = bounds tab

solve :: Int -> Table -> Int
solve n tab =
  length [1 | i<-[1..n], j<-[1..n], let rtab = ixmap ((1,1),(n,n)) (f i j) tab, isGood rtab]
  where
    f i j (x,y) = ((x+i)`mod`n+1, (y+j)`mod`n+1)

Score : 500 points

Problem Statement

Snuke has two boards, each divided into a grid with N rows and N columns.
For both of these boards, the square at the i-th row from the top and the j-th column from the left is called Square (i,j).

There is a lowercase English letter written in each square on the first board. The letter written in Square (i,j) is S_{i,j}. On the second board, nothing is written yet.

Snuke will write letters on the second board, as follows:

First, choose two integers A and B ( 0 \leq A, B < N ).

Write one letter in each square on the second board.
Specifically, write the letter written in Square ( i+A, j+B ) on the first board into Square (i,j) on the second board.
Here, the k-th row is also represented as the (N+k)-th row, and the k-th column is also represented as the (N+k)-th column.

After this operation, the second board is called a good board when, for every i and j ( 1 \leq i, j \leq N ), the letter in Square (i,j) and the letter in Square (j,i) are equal.

Find the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Constraints

1 \leq N \leq 300

S_{i,j} ( 1 \leq i, j \leq N ) is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
S_{1,1}S_{1,2}..S_{1,N}
S_{2,1}S_{2,2}..S_{2,N}
:
S_{N,1}S_{N,2}..S_{N,N}

Output

Print the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Sample Input 1

2
ab
ca

Sample Output 1

2

For each pair of A and B, the second board will look as shown below:

The second board is a good board when (A,B) = (0,1) or (A,B) = (1,0), thus the answer is 2.

Sample Input 2

4
aaaa
aaaa
aaaa
aaaa

Sample Output 2

16

Every possible choice of A and B makes the second board good.

Sample Input 3

5
abcde
fghij
klmno
pqrst
uvwxy

Sample Output 3

0

No possible choice of A and B makes the second board good.


import Control.Applicative
import Control.Monad
import Data.List
import Data.Array
import Data.Char

main = do
  s <- getLine
  print $ foldl (\acc c -> if c == 'o' then acc + 100 else acc) 700 s

Score : 100 points

Problem Statement

In "Takahashi-ya", a ramen restaurant, a bowl of ramen costs 700 yen (the currency of Japan), plus 100 yen for each kind of topping (boiled egg, sliced pork, green onions).

A customer ordered a bowl of ramen and told which toppings to put on his ramen to a clerk. The clerk took a memo of the order as a string S. S is three characters long, and if the first character in S is o, it means the ramen should be topped with boiled egg; if that character is x, it means the ramen should not be topped with boiled egg. Similarly, the second and third characters in S mean the presence or absence of sliced pork and green onions on top of the ramen.

Write a program that, when S is given, prints the price of the corresponding bowl of ramen.

Constraints

S is a string of length 3.

Each character in S is o or x.

Input

Input is given from Standard Input in the following format:

S

Output

Print the price of the bowl of ramen corresponding to S.

Sample Input 1

oxo

Sample Output 1

900

The price of a ramen topped with two kinds of toppings, boiled egg and green onions, is 700 + 100 \times 2 = 900 yen.

Sample Input 2

ooo

Sample Output 2

1000

The price of a ramen topped with all three kinds of toppings is 700 + 100 \times 3 = 1000 yen.

Sample Input 3

xxx

Sample Output 3

700

The price of a ramen without any toppings is 700 yen.


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

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

data PizzaPrice = PizzaPrice{
priceA :: Integer,
priceB :: Integer,
priceC :: Integer
}

data ReqNum = ReqNum{
quantityX :: Integer,
quantityY :: Integer
}

type Price = Integer

halfAndHalf :: PizzaPrice -> ReqNum -> Price
halfAndHalf pp rn
            | a + b < 2 * c = a * x + b * y
            | x > y = min ((y * 2 * c)  + ( (x - y) * a)) (x * 2 * c)
            | otherwise = min ((x * 2 * c)  + ( (y - x) * b)) (y * 2 * c)
            where
                a = priceA pp
                b = priceB pp
                c = priceC pp
                x = quantityX rn
                y = quantityY rn

main = do
     [a,b,c,x,y] <- getIntList
     print $ halfAndHalf (PizzaPrice a b c) (ReqNum x y)

Score : 300 points

Problem Statement

"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the currency of Japan), respectively.

Nakahashi needs to prepare X A-pizzas and Y B-pizzas for a party tonight. He can only obtain these pizzas by directly buying A-pizzas and B-pizzas, or buying two AB-pizzas and then rearrange them into one A-pizza and one B-pizza. At least how much money does he need for this? It is fine to have more pizzas than necessary by rearranging pizzas.

Constraints

1 ≤ A, B, C ≤ 5000

1 ≤ X, Y ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C X Y

Output

Print the minimum amount of money required to prepare X A-pizzas and Y B-pizzas.

Sample Input 1

1500 2000 1600 3 2

Sample Output 1

7900

It is optimal to buy four AB-pizzas and rearrange them into two A-pizzas and two B-pizzas, then buy additional one A-pizza.

Sample Input 2

1500 2000 1900 3 2

Sample Output 2

8500

It is optimal to directly buy three A-pizzas and two B-pizzas.

Sample Input 3

1500 2000 500 90000 100000

Sample Output 3

100000000

It is optimal to buy 200000 AB-pizzas and rearrange them into 100000 A-pizzas and 100000 B-pizzas. We will have 10000 more A-pizzas than necessary, but that is fine.


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 B
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.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

solve a b c x y
  | c < a && c < b = 2 * c * max x y
  | otherwise =
      minimum [i * a + j * b + k * c * 2 | i <- [0..x], j <- [0..y], let k = max (x-i) (y-j)]

main = do
  [a,b,c,x,y] <- map read . words <$> getLine :: IO [Int]
  print $ solve a b c x y


import Data.List.Split

calc :: Int -> Int -> Int -> String
calc a b x
		| (a + b) < x = "NO"
		| a > x = "NO"
		| otherwise = "YES"

main = do
	str <- getLine
	let str' = splitOn " " str
	let nums = map (read :: String -> Int) str'
	let a = nums !! 0
	let b = nums !! 1
	let c = nums !! 2
	putStrLn $ calc a b c

Score : 100 points

Problem Statement

There are a total of A + B cats and dogs.
Among them, A are known to be cats, but the remaining B are not known to be either cats or dogs.

Determine if it is possible that there are exactly X cats among these A + B animals.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

1 \leq X \leq 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B X

Output

If it is possible that there are exactly X cats, print YES; if it is impossible, print NO.

Sample Input 1

3 5 4

Sample Output 1

YES

If there are one cat and four dogs among the B = 5 animals, there are X = 4 cats in total.

Sample Input 2

2 2 6

Sample Output 2

NO

Even if all of the B = 2 animals are cats, there are less than X = 6 cats in total.

Sample Input 3

5 3 2

Sample Output 3

NO

Even if all of the B = 3 animals are dogs, there are more than X = 2 cats in total.


import Control.Monad
import Text.Printf
import Control.Applicative
import Data.List as L

main :: IO()
main = do
  [a, b, x] <- map read . words <$> getLine
  printf "%s" $ slv a b x

slv :: Int -> Int -> Int -> String
slv a b x | x - a >= 0 && x - a <= b = "YES"
          | otherwise = "NO"


main :: IO ()
main = do
    [n,_,x] <- map read . words <$> getLine :: IO [Int]
    a <- map read . words <$> getLine :: IO [Int]
    let a' = map (\i -> if i `elem` a then 1 else 0) [0..n]
        (l,r) = splitAt x a'
    print $ min (sum l) (sum r)

Score : 200 points

Problem Statement

There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right.

Initially, you are in Square X.
You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N.
However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1.
It is guaranteed that there is no toll gate in Square 0, Square X and Square N.

Find the minimum cost incurred before reaching the goal.

Constraints

1 \leq N \leq 100

1 \leq M \leq 100

1 \leq X \leq N - 1

1 \leq A_1 < A_2 < ... < A_M \leq N

A_i \neq X

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M X
A_1 A_2 ... A_M

Output

Print the minimum cost incurred before reaching the goal.

Sample Input 1

5 3 3
1 2 4

Sample Output 1

1

The optimal solution is as follows:

First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.

Then, travel from Square 4 to Square 5. This time, no cost is incurred.

Now, we are in Square 5 and we have reached the goal.

In this case, the total cost incurred is 1.

Sample Input 2

7 3 2
4 5 6

Sample Output 2

0

We may be able to reach the goal at no cost.

Sample Input 3

10 7 5
1 2 3 4 6 8 9

Sample Output 3

3


main :: IO ()
main = do
    [n,m,x] <- map read . words <$> getLine :: IO [Int]
    as <- map read . words <$> getLine :: IO [Int]
    putStrLn $ show $ if (length (filter (<x) as) <= length (filter (>x) as)) then length (filter (<x) as) else length (filter (>x) as)


import qualified Data.ByteString.Char8 as BC
import Data.Maybe
import Data.List

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

main :: IO ()
main = do
  getLine
  xs <- readIntsLine
  let len = length xs
  let sxs = sort xs
  let ixs = map fst . sortOn snd $ zip [1..] $ map fst . sortOn snd $ zip [1..] xs
  let [a, b] = take 2 $ drop (len `div` 2 - 1) sxs
  let mark = len `div` 2
  mapM_ print [if x > mark then a else b | x <- ixs]

Score : 300 points

Problem Statement

When l is an odd number, the median of l numbers a_1, a_2, ..., a_l is the (\frac{l+1}{2})-th largest value among a_1, a_2, ..., a_l.

You are given N numbers X_1, X_2, ..., X_N, where N is an even number.
For each i = 1, 2, ..., N, let the median of X_1, X_2, ..., X_N excluding X_i, that is, the median of X_1, X_2, ..., X_{i-1}, X_{i+1}, ..., X_N be B_i.

Find B_i for each i = 1, 2, ..., N.

Constraints

2 \leq N \leq 200000

N is even.

1 \leq X_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 X_2 ... X_N

Output

Print N lines.
The i-th line should contain B_i.

Sample Input 1

4
2 4 4 3

Sample Output 1

4
3
3
4

Since the median of X_2, X_3, X_4 is 4, B_1 = 4.

Since the median of X_1, X_3, X_4 is 3, B_2 = 3.

Since the median of X_1, X_2, X_4 is 3, B_3 = 3.

Since the median of X_1, X_2, X_3 is 4, B_4 = 4.

Sample Input 2

2
1 2

Sample Output 2

2
1

Sample Input 3

6
5 5 4 4 3 3

Sample Output 3

4
4
4
4
4
4


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

main=do
    n<-readLn::IO Int
    xs<-unfoldr (B.readInt.B.dropWhile(==' '))<$>B.getLine
    --
    let ys=V.fromList.sort $ xs
    let m1= ys V.! ((n `div` 2)-1)
    let m2= ys V.! (n `div` 2)
    --
    sequence_ $ map (print.(f m1 m2)) xs

f m1 m2 x = if x < m2 then m2 else m1


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
import qualified Data.ByteString.Char8 as BC
import           Data.Maybe            (fromJust)
import           Data.Sequence         as S

main :: IO ()
main = do
  n <- readLn
  xs <- getInts
  putStr . unlines . map show $ solve n xs

solve :: Int -> [Int] -> [Int]
solve n xs = map f xs
  where f x = if x <= a then b else a
        a = S.index v (n `div` 2 - 1)
        b = S.index v (n `div` 2)
        v = S.unstableSort $ S.fromList xs

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

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


import Data.List

main = do
  n <- read <$> getLine::IO Int
  xs <- map read . words <$> getLine ::IO [Int]
  let xs_ = sort xs
  let (m1,m2) = (xs_!!(div n 2),xs_!!(div n 2))
  mapM_ print $ solve m1 m2 xs

--solve :: Int -> Int -> [Int] -> Int -> [Int] -> [Int]
solve _ _ [] = []
solve m1 m2 (x:xs)  =
  (if x<m1 then m2 else m1) : solve m1 m2 xs


import Control.Applicative ((<$>))
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Function (on)
import Data.Char (isSpace)

main :: IO ()
main = do
  n <- readLn
  solve n <$> getl (readil B.readInt) >>= mapM_ print

solve :: Int -> [(Int,Int)] -> [Int]
solve n xs = map f [1..n]
  where
    ls = sortBy (compare `on` snd) xs
    lm = snd $ ls !! (n `div` 2 - 1)
    rm = snd $ ls !! (n `div` 2)
    ll = map fst $ take (n `div` 2) ls
    f i | i `elem` ll = rm
        | otherwise = lm

getl :: (ByteString -> a) -> IO a
getl f = f <$> B.getLine

readil :: Integral a =>  (ByteString -> Maybe (a, ByteString)) -> ByteString -> [(Int,a)]
readil f x = unfoldr g (1, x)
  where
    g (i, s) = do
      (n, s') <- f s
      return ((i,n), (i+1, B.dropWhile isSpace s'))


--{-# 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.Vector.Algorithms.Merge as VAM
-- import qualified Data.Heap as HP
-- import Numeric.Extra
-- import Data.Tuple.Extra
-- import Data.List.Extra

--------------------------------------------------------------------------
step :: Int -> Int -> Int -> Int
step i acc j
    | (abs $ j - i') <= (abs $ acc - i') = j
    | otherwise = acc
    where
        i' = i `div` 2

main = do
    n <- int
    xs <- VU.fromList . sort <$> sLineToIntL
    let
        a = VU.maximum xs
        b = VU.foldl' (step a) 0 (VU.init xs)

    putStr $ show a
    putStr $ " "
    putStr $ show b
    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

Let {\rm comb}(n,r) be the number of ways to choose r objects from among n objects, disregarding order.
From n non-negative integers a_1, a_2, ..., a_n, select two numbers a_i > a_j so that {\rm comb}(a_i,a_j) is maximized.
If there are multiple pairs that maximize the value, any of them is accepted.

Constraints

2 \leq n \leq 10^5

0 \leq a_i \leq 10^9

a_1,a_2,...,a_n are pairwise distinct.

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

Print a_i and a_j that you selected, with a space in between.

Sample Input 1

5
6 9 4 2 11

Sample Output 1

11 6

\rm{comb}(a_i,a_j) for each possible selection is as follows:

\rm{comb}(4,2)=6

\rm{comb}(6,2)=15

\rm{comb}(6,4)=15

\rm{comb}(9,2)=36

\rm{comb}(9,4)=126

\rm{comb}(9,6)=84

\rm{comb}(11,2)=55

\rm{comb}(11,4)=330

\rm{comb}(11,6)=462

\rm{comb}(11,9)=55

Thus, we should print 11 and 6.

Sample Input 2

2
100 0

Sample Output 2

100 0


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

main :: IO()
main = do
    _ <- getLine
    nums <- map read . words <$> getLine
    putStrLn $ solve nums

solve :: [Integer] -> String
solve nums =
    case maxCombPair of
        (_, (a1', a2')) -> show a1' ++ " " ++ show a2'
    where
        pairs = [(a1, a2) | a1 <- nums, a2 <- nums, a1 > a2]
        maxCombPair = foldl (\temp pair -> if (fromJust $ comb pair) > fst temp then (fromJust $ comb pair, pair) else temp) (0, (0, 0)) pairs

comb :: (Integer, Integer) -> Maybe Integer
comb (a1, a2)
    | a1 <= a2 = Nothing
    | a2 == 0 = Just 1
    | a1 - a2 < a2 = comb (a1, a1 - a2)
    | otherwise = Just $ (foldl1 (*) . take (fromIntegral a2) $ reverse [0..a1]) `div` (foldl1 (*) [1..a2])


import Data.List

main :: IO ()
main = do
    n <- readLn
    xs <- map read . words <$> getLine
    mapM_ print (solve n xs)

solve :: Int -> [Int] -> [Int]
solve n xs = map fst (sortBy (\x y -> compare (snd x) (snd y)) $ zip a sorter) where
    sortedxs = sortBy (\x y -> compare (fst x) (fst y)) $ zip xs [0..n-1]
    sorter = map snd sortedxs
    divn2 = div n 2
    a = (replicate (divn2) $ fst $ sortedxs !! (divn2)) ++ (replicate (divn2) $ fst $ sortedxs !! (divn2 - 1))


import Data.List

main = do
  str <- getLine
  print $ if elem str $ permutations "abc" then "Yes" else "No"

Score : 100 points

Problem Statement

You are given a string S of length 3 consisting of a, b and c. Determine if S can be obtained by permuting abc.

Constraints

|S|=3

S consists of a, b and c.

Input

Input is given from Standard Input in the following format:

S

Output

If S can be obtained by permuting abc, print Yes; otherwise, print No.

Sample Input 1

bac

Sample Output 1

Yes

Swapping the first and second characters in bac results in abc.

Sample Input 2

bab

Sample Output 2

No

Sample Input 3

abc

Sample Output 3

Yes

Sample Input 4

aaa

Sample Output 4

No


main=do
 [a,b,k]<-map read.words<$>getLine
 let c=min(a+k-1)b
 f a (c-a)
 f c(b+1-c)
f a 0=return()
f a b=do
 print a
 f(a+1)(b-1)

Score : 200 points

Problem Statement

Print all the integers that satisfies the following in ascending order:

Among the integers between A and B (inclusive), it is either within the K smallest integers or within the K largest integers.

Constraints

1 \leq A \leq B \leq 10^9

1 \leq K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print all the integers that satisfies the condition above in ascending order.

Sample Input 1

3 8 2

Sample Output 1

3
4
7
8

3 is the first smallest integer among the integers between 3 and 8.

4 is the second smallest integer among the integers between 3 and 8.

7 is the second largest integer among the integers between 3 and 8.

8 is the first largest integer among the integers between 3 and 8.

Sample Input 2

4 8 3

Sample Output 2

4
5
6
7
8

Sample Input 3

2 9 100

Sample Output 3

2
3
4
5
6
7
8
9


import Data.List

solve :: Int -> Int -> Int -> [Int]
solve a b k =
  if b-a+1 > 2*k then [a..a+k-1] ++ [(b-k+1)..b]
  else [a..b]

main = do
  [a,b,k] <- map read . words <$> getLine :: IO [Int]
  mapM print (solve a b k)


import Data.List

f a b k
  | k < div range 2 + mod range 2 = (++) <*> (map (+ (b - (k -1)))) $ take k [a..b]
  | otherwise = [a..b]
  where range = b - a + 1

main = do
   [a,b,k] <- map read . words <$> getLine
   mapM_ print $ f a b k


import Data.List

main = do
  n <- readLn
  xss <- mapM (const $ fmap (map read . words) getLine) [1..n]
  print (solve xss)

solve :: [[Int]] -> Int
solve xss =
  if as==bs then 0 else sum bs - foldr f (10^9) xss
  where
    [as,bs] = transpose xss
    f [a,b] c | a > b     = min c b
              | otherwise = c

Score : 700 points

Problem Statement

You are given sequences A and B consisting of non-negative integers.
The lengths of both A and B are N, and the sums of the elements in A and B are equal.
The i-th element in A is A_i, and the i-th element in B is B_i.

Tozan and Gezan repeats the following sequence of operations:

If A and B are equal sequences, terminate the process.

Otherwise, first Tozan chooses a positive element in A and decrease it by 1.

Then, Gezan chooses a positive element in B and decrease it by 1.

Then, give one candy to Takahashi, their pet.

Tozan wants the number of candies given to Takahashi until the process is terminated to be as large as possible, while Gezan wants it to be as small as possible.
Find the number of candies given to Takahashi when both of them perform the operations optimally.

Constraints

1 \leq N \leq 2 × 10^5

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

The sums of the elements in A and B are equal.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the number of candies given to Takahashi when both Tozan and Gezan perform the operations optimally.

Sample Input 1

2
1 2
3 2

Sample Output 1

2

When both Tozan and Gezan perform the operations optimally, the process will proceed as follows:

Tozan decreases A_1 by 1.

Gezan decreases B_1 by 1.

One candy is given to Takahashi.

Tozan decreases A_2 by 1.

Gezan decreases B_1 by 1.

One candy is given to Takahashi.

As A and B are equal, the process is terminated.

Sample Input 2

3
8 3
0 1
4 8

Sample Output 2

9

Sample Input 3

1
1 1

Sample Output 3

0


import Control.Monad (replicateM)

main = do
    [a, b, c, d] <- replicateM 4 readLn :: IO [Int]
    print $ min a b + min c d

Score : 100 points

Problem Statement

You planned a trip using trains and buses.
The train fare will be A yen (the currency of Japan) if you buy ordinary tickets along the way, and B yen if you buy an unlimited ticket.
Similarly, the bus fare will be C yen if you buy ordinary tickets along the way, and D yen if you buy an unlimited ticket.

Find the minimum total fare when the optimal choices are made for trains and buses.

Constraints

1 \leq A \leq 1 000

1 \leq B \leq 1 000

1 \leq C \leq 1 000

1 \leq D \leq 1 000

All input values are integers.

Input

Input is given from Standard Input in the following format:

A
B
C
D

Output

Print the minimum total fare.

Sample Input 1

600
300
220
420

Sample Output 1

520

The train fare will be 600 yen if you buy ordinary tickets, and 300 yen if you buy an unlimited ticket.
Thus, the optimal choice for trains is to buy an unlimited ticket for 300 yen.
On the other hand, the optimal choice for buses is to buy ordinary tickets for 220 yen.

Therefore, the minimum total fare is 300 + 220 = 520 yen.

Sample Input 2

555
555
400
200

Sample Output 2

755

Sample Input 3

549
817
715
603

Sample Output 3

1152


import Control.Applicative
import Control.Monad

main :: IO ()
main = do
  [a,b,c,d] <- replicateM 4 readLn
  print $ solve a b c d

solve a b c d = min a b + min c d


module Main where

import Control.Monad
import Control.Applicative

main = do
  [a, b, c, d] <- map (read:: String -> Int) . lines <$> getContents
  print $ min a b + min c d


main = do
  getLine
  [d,x] <- map read.words <$> getLine
  a <-map read.words <$> getContents
  let ans = sum [(d-1)`div` i + 1| i <- a]
  print $ ans+x

Score : 200 points

Problem Statement

Some number of chocolate pieces were prepared for a training camp.
The camp had N participants and lasted for D days.
The i-th participant (1 \leq i \leq N) ate one chocolate piece on each of the following days in the camp: the 1-st day, the (A_i + 1)-th day, the (2A_i + 1)-th day, and so on.
As a result, there were X chocolate pieces remaining at the end of the camp. During the camp, nobody except the participants ate chocolate pieces.

Find the number of chocolate pieces prepared at the beginning of the camp.

Constraints

1 \leq N \leq 100

1 \leq D \leq 100

1 \leq X \leq 100

1 \leq A_i \leq 100 (1 \leq i \leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
D X
A_1
A_2
:
A_N

Output

Find the number of chocolate pieces prepared at the beginning of the camp.

Sample Input 1

3
7 1
2
5
10

Sample Output 1

8

The camp has 3 participants and lasts for 7 days.
Each participant eats chocolate pieces as follows:

The first participant eats one chocolate piece on Day 1, 3, 5 and 7, for a total of four.

The second participant eats one chocolate piece on Day 1 and 6, for a total of two.

The third participant eats one chocolate piece only on Day 1, for a total of one.

Since the number of pieces remaining at the end of the camp is one, the number of pieces prepared at the beginning of the camp is 1 + 4 + 2 + 1 = 8.

Sample Input 2

2
8 20
1
10

Sample Output 2

29

Sample Input 3

5
30 44
26
18
81
18
6

Sample Output 3

56


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

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

--------------------------------------------------------------------------
solve :: [Int] -> Int -> Int
solve [] _ = 0
solve (y:ys) d = res + solve ys d
    where
        res = length $ filter (<=d) $ 1 : map (\i -> y*i+1) [1..100]

main = do
    n <- int
    [d,x] <- sLineToIntL
    ys <- mLinesToIntL n
    print $ x + solve ys d
--------------------------------------------------------------------------

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

double :: IO Double
double = readLn

str :: IO String
str = getLine

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


import Control.Monad

main = do
  n <- getLine
  a <- map read . words <$> getLine
  forM_ (solve a) $ \t ->
    putStrLn . show $ t

solve :: [Int] -> [Int]
solve xs =
  let wp = wholePath xs
  in inSolve 0 wp (xs ++ [0])

inSolve prev ttl [] = []
inSolve prev ttl (x:[]) = []
inSolve prev ttl (x:y:xs) =
  if prev <= x && x <= y || prev >= x && x >= y then
    ttl:(inSolve x ttl (y:xs))
  else
    (ttl + (abs (prev - y)) - (abs (x - y)) - (abs (prev - x))):(inSolve x ttl (y:xs))

wholePath xs = (abs (head xs)) + difsum xs

difsum :: [Int] -> Int
difsum [] = 0
difsum (x:[]) = abs x
difsum (x:y:xs) = (abs (x-y)) + (difsum (y:xs))

Score : 300 points

Problem Statement

There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N.
Spot i is at the point with coordinate A_i.
It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.

You planned a trip along the axis.
In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.

However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i.
You will visit the remaining spots as planned in the order they are numbered.
You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.

For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.

Constraints

2 \leq N \leq 10^5

-5000 \leq A_i \leq 5000 (1 \leq i \leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print N lines.
In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.

Sample Input 1

3
3 5 -1

Sample Output 1

12
8
10

Spot 1, 2 and 3 are at the points with coordinates 3, 5 and -1, respectively.
For each i, the course of the trip and the total cost of travel when the visit to Spot i is canceled, are as follows:

For i = 1, the course of the trip is 0 \rightarrow 5 \rightarrow -1 \rightarrow 0 and the total cost of travel is 5 + 6 + 1 = 12 yen.

For i = 2, the course of the trip is 0 \rightarrow 3 \rightarrow -1 \rightarrow 0 and the total cost of travel is 3 + 4 + 1 = 8 yen.

For i = 3, the course of the trip is 0 \rightarrow 3 \rightarrow 5 \rightarrow 0 and the total cost of travel is 3 + 2 + 5 = 10 yen.

Sample Input 2

5
1 1 1 2 0

Sample Output 2

4
4
4
2
4

Sample Input 3

6
-679 -2409 -3258 3095 -3291 -4462

Sample Output 3

21630
21630
19932
8924
21630
19288


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

main :: IO ()
main = readLine >>= printRes . solve
    where
        printRes (xs, ys) = mapM_ putStrLn $ (unwords $ map show xs) : ys

solve :: [Int] -> ([Int], [String])
solve [a, b] = ([length ws + length bs, 100], ws ++ reverse bs)
    where
        ws = buildW
        bs = buildB

        buildW
            | m == 0 = take (2 * r - 2) (cycle fills) ++ opens 50
            | otherwise = take (2 * r) (cycle fills) ++ opens m
            where
                (r, m) = a `divMod` 50
                fills = [take 100 $ cycle "#.", replicate 100 '#']
                opens n = ['#' : take 49 xs, '#' : take 49 ys]
                    where
                        (xs, ys) = buildOW n
                buildOW n
                    | n == 1 = (repeat '.', repeat '.')
                    | otherwise = ('.' : '#' : xs, '#' : '#' : ys)
                    where
                        (xs, ys) = buildOW $ n - 1
        buildB
            | m == 0 = take (2 * r - 2) (cycle fills) ++ opens 50
            | otherwise = take (2 * r) (cycle fills) ++ opens m
            where
                (r, m) = b `divMod` 50
                fills = [take 100 $ cycle "#.", replicate 100 '.']
                opens n = [reverse $ '.' : take 49 xs, reverse $ '.' : take 49 ys]
                    where
                        (xs, ys) = buildOB n
                buildOB n
                    | n == 1 = (repeat '#', repeat '#')
                    | otherwise = ('#' : '.' : xs, '.' : '.' : ys)
                    where
                        (xs, ys) = buildOB $ n - 1

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

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

Score : 500 points

Problem Statement

You are given two integers A and B.

Print a grid where each square is painted white or black that satisfies the following conditions, in the format specified in Output section:

Let the size of the grid be h \times w (h vertical, w horizontal). Both h and w are at most 100.

The set of the squares painted white is divided into exactly A connected components.

The set of the squares painted black is divided into exactly B connected components.

It can be proved that there always exist one or more solutions under the conditions specified in Constraints section.
If there are multiple solutions, any of them may be printed.

Notes

Two squares painted white, c_1 and c_2, are called connected when the square c_2 can be reached from the square c_1 passing only white squares by repeatedly moving up, down, left or right to an adjacent square.

A set of squares painted white, S, forms a connected component when the following conditions are met:

Any two squares in S are connected.

No pair of a square painted white that is not included in S and a square included in S is connected.

A connected component of squares painted black is defined similarly.

Constraints

1 \leq A \leq 500

1 \leq B \leq 500

Input

Input is given from Standard Input in the following format:

A B

Output

Output should be in the following format:

In the first line, print integers h and w representing the size of the grid you constructed, with a space in between.

Then, print h more lines. The i-th (1 \leq i \leq h) of these lines should contain a string s_i as follows:

If the square at the i-th row and j-th column (1 \leq j \leq w) in the grid is painted white, the j-th character in s_i should be ..

If the square at the i-th row and j-th column (1 \leq j \leq w) in the grid is painted black, the j-th character in s_i should be #.

Sample Input 1

2 3

Sample Output 1

3 3
##.
..#
#.#

This output corresponds to the grid below:

Sample Input 2

7 8

Sample Output 2

3 5
#.#.#
.#.#.
#.#.#

Sample Input 3

1 1

Sample Output 3

4 2
..
#.
##
##

Sample Input 4

3 14

Sample Output 4

8 18
..................
..................
....##.......####.
....#.#.....#.....
...#...#....#.....
..#.###.#...#.....
.#.......#..#.....
#.........#..####.


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

Score : 100 points

Problem Statement

An elementary school student Takahashi has come to a variety store.

He has two coins, A-yen and B-yen coins (yen is the currency of Japan), and wants to buy a toy that costs C yen. Can he buy it?

Note that he lives in Takahashi Kingdom, and may have coins that do not exist in Japan.

Constraints

All input values are integers.

1 \leq A, B \leq 500

1 \leq C \leq 1000

Input

Input is given from Standard Input in the following format:

A B C

Output

If Takahashi can buy the toy, print Yes; if he cannot, print No.

Sample Input 1

50 100 120

Sample Output 1

Yes

He has 50 + 100 = 150 yen, so he can buy the 120-yen toy.

Sample Input 2

500 100 1000

Sample Output 2

No

He has 500 + 100 = 600 yen, but he cannot buy the 1000-yen toy.

Sample Input 3

19 123 143

Sample Output 3

No

There are 19-yen and 123-yen coins in Takahashi Kingdom, which are rather hard to use.

Sample Input 4

19 123 142

Sample Output 4

Yes


{-# LANGUAGE TypeApplications #-}

import Control.Monad

main = do
    xs <- readLn @ Int >>= (flip replicateM) getLine
    ys <- readLn @ Int >>= (flip replicateM) getLine

    print $ (foldl max 0 . fmap (\x -> ((length . filter (== x)) xs) - ((length . filter (== x)) ys))) xs

Score : 200 points

Problem Statement

Takahashi has N blue cards and M red cards.
A string is written on each card. The string written on the i-th blue card is s_i, and the string written on the i-th red card is t_i.

Takahashi will now announce a string, and then check every card. Each time he finds a blue card with the string announced by him, he will earn 1 yen (the currency of Japan); each time he finds a red card with that string, he will lose 1 yen.

Here, we only consider the case where the string announced by Takahashi and the string on the card are exactly the same. For example, if he announces atcoder, he will not earn money even if there are blue cards with atcoderr, atcode, btcoder, and so on. (On the other hand, he will not lose money even if there are red cards with such strings, either.)

At most how much can he earn on balance?

Note that the same string may be written on multiple cards.

Constraints

N and M are integers.

1 \leq N, M \leq 100

s_1, s_2, ..., s_N, t_1, t_2, ..., t_M are all strings of lengths between 1 and 10 (inclusive) consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N
M
t_1
t_2
:
t_M

Output

If Takahashi can earn at most X yen on balance, print X.

Sample Input 1

3
apple
orange
apple
1
grape

Sample Output 1

2

He can earn 2 yen by announcing apple.

Sample Input 2

3
apple
orange
apple
5
apple
apple
apple
apple
apple

Sample Output 2

1

If he announces apple, he will lose 3 yen. If he announces orange, he can earn 1 yen.

Sample Input 3

1
voldemort
10
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort

Sample Output 3

0

If he announces voldemort, he will lose 9 yen. If he announces orange, for example, he can avoid losing a yen.

Sample Input 4

6
red
red
blue
yellow
yellow
red
5
red
red
yellow
green
blue

Sample Output 4

1


import Control.Monad
import Data.List

solve :: [(String, Int)] -> [(String, Int)] -> [Int]
solve [] _ = []
solve ((name, inc):ss) t = case lookup name t of
  Just dec -> (inc - dec) : solve ss t
  Nothing  -> inc : solve ss t

main :: IO ()
main = do
  let convert = map (\x -> (head x, length x)) . group . sort
  n <- readLn
  ss <- convert <$> replicateM n getLine
  m <- readLn
  ts <- convert <$> replicateM m getLine
  print . max 0 $ maximum $ solve ss ts


import Control.Monad

main = do
  n <- readLn :: IO Int
  s <- replicateM n getLine
  m <- readLn :: IO Int
  t <- replicateM m getLine

  print $ maximum $ map (\x -> if x<0 then 0 else x) [length (filter (==a) s) - length (filter (==a) t) | a <- s]


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

main = do
  n <- readLn
  as <- replicateM n getLine
  m <- readLn
  bs <- replicateM m getLine
  print $ solve as bs

solve :: [String] -> [String] -> Int
solve as bs = let
  cs = as \\ bs
  in if null cs then 0 else maximum $ map length $ group $ sort cs


import Control.Monad
import Data.Maybe
import Data.List
import Data.Array

main :: IO ()
main = do
  n <- readLn
  xs <- replicateM n $ map read . words <$> getLine :: IO [[Int]]
  ys <- replicateM n $ map read . words <$> getLine :: IO [[Int]]
  -- print $ solve xs ys
  print $ solve'' n xs ys

solve'' :: Int -> [[Int]] -> [[Int]] -> Int
solve'' n xs ys = n - (length $ foldl' go blues reds)
  where
    reds = reverse . sortOn last $  xs
    blues = sortOn head $ ys
    go :: [[Int]] -> [Int] -> [[Int]]
    go bs r = deleteBy canBeGoodFriends r bs

canBeGoodFriends :: [Int] -> [Int] -> Bool
canBeGoodFriends (a:b:_) (c:d:_) = a < c && b < d

Score : 400 points

Problem Statement

On a two-dimensional plane, there are N red points and N blue points.
The coordinates of the i-th red point are (a_i, b_i), and the coordinates of the i-th blue point are (c_i, d_i).

A red point and a blue point can form a friendly pair when, the x-coordinate of the red point is smaller than that of the blue point, and the y-coordinate of the red point is also smaller than that of the blue point.

At most how many friendly pairs can you form? Note that a point cannot belong to multiple pairs.

Constraints

All input values are integers.

1 \leq N \leq 100

0 \leq a_i, b_i, c_i, d_i < 2N

a_1, a_2, ..., a_N, c_1, c_2, ..., c_N are all different.

b_1, b_2, ..., b_N, d_1, d_2, ..., d_N are all different.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N

Output

Print the maximum number of friendly pairs.

Sample Input 1

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

Sample Output 1

2

For example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).

Sample Input 2

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

Sample Output 2

2

For example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).

Sample Input 3

2
2 2
3 3
0 0
1 1

Sample Output 3

0

It is possible that no pair can be formed.

Sample Input 4

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

Sample Output 4

5

Sample Input 5

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

Sample Output 5

4


main :: IO ()
main = do
    a <- getLine
    b <- getLine
    c <- getLine
    putChar $ (a!!0)
    putChar $ (b!!1)
    putChar $ (c!!2)

Score : 100 points

Problem Statement

We have a 3×3 square grid, where each square contains a lowercase English letters.
The letter in the square at the i-th row from the top and j-th column from the left is c_{ij}.

Print the string of length 3 that can be obtained by concatenating the letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.

Constraints

Input consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

c_{11}c_{12}c_{13}
c_{21}c_{22}c_{23}
c_{31}c_{32}c_{33}

Output

Print the string of length 3 that can be obtained by concatenating the letters on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.

Sample Input 1

ant
obe
rec

Sample Output 1

abc

The letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid are a, b and c from top-right to bottom-left. Concatenate these letters and print abc.

Sample Input 2

edu
cat
ion

Sample Output 2

ean


module Main where

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

main :: IO ()
main = do
    n <- readLn
    print $ n `div` 3

Score : 100 points

Problem Statement

There are N students in a school.

We will divide these students into some groups, and in each group they will discuss some themes.

You think that groups consisting of two or less students cannot have an effective discussion, so you want to have as many groups consisting of three or more students as possible.

Divide the students so that the number of groups consisting of three or more students is maximized.

Constraints

1 \leq N \leq 1000

All input values are integers.

Input

Input is given from Standard Input in the following format:

N

Output

If you can form at most x groups consisting of three or more students, print x.

Sample Input 1

8

Sample Output 1

2

For example, you can form a group of three students and another of five students.

Sample Input 2

2

Sample Output 2

0

Sometimes you cannot form any group consisting of three or more students, regardless of how you divide the students.

Sample Input 3

9

Sample Output 3

3


main = do
  n <- readLn
  print $ n `div` 3

main = do
  n <- readLn
  print $ n `div` 3


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

add vec xs
    | h == 'M' = VUM.modify vec (+1) 0
    | h == 'A' = VUM.modify vec (+1) 1
    | h == 'R' = VUM.modify vec (+1) 2
    | h == 'C' = VUM.modify vec (+1) 3
    | h == 'H' = VUM.modify vec (+1) 4
    | otherwise = VUM.modify vec (+1) 5
    where
        h = B.head xs

toBit n acc l
    | n <= 1 =
        let
            res = ((n `rem` 2):acc)
            l' = length res
        in
            if l' < l
                then reverse $  res ++ (replicate (l-l') 0)
                else reverse res
    | otherwise = toBit (n `quot` 2) ((n `rem` 2):acc) l

solve :: [Int] -> Int -> Int -> [Int]
solve xs n l
    | n < 0 = []
    | ones == 3 = (loop xs bs) : solve xs (n-1) l
    | otherwise = solve xs (n-1) l
    where
        ones = length $ filter (==1) bs
        bs = toBit n [] l
        loop [] [] = 1
        loop (x:xs) (b:bs)
            | b == 1 = x * loop xs bs
            | otherwise = loop xs bs

main = do
    n <- readLn :: IO Int
    tbl <- VUM.replicate 6 0
    forM_ [1..n] $ \_ -> do
        bs <- B.getLine
        add tbl bs
    tbl' <- VU.freeze tbl
    print tbl'
    let f = VU.toList $ VU.filter (/=0) (VU.init tbl')
    let l = length f
    print $
        if l < 3
            then 0
            else if l == 3
                then product f
                else sum $ solve f (2^l-1) l

Score : 300 points

Problem Statement

There are N people. The name of the i-th person is S_i.

We would like to choose three people so that the following conditions are met:

The name of every chosen person begins with M, A, R, C or H.

There are no multiple people whose names begin with the same letter.

How many such ways are there to choose three people, disregarding order?

Note that the answer may not fit into a 32-bit integer type.

Constraints

1 \leq N \leq 10^5

S_i consists of uppercase English letters.

1 \leq |S_i| \leq 10

S_i \neq S_j (i \neq j)

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

If there are x ways to choose three people so that the given conditions are met, print x.

Sample Input 1

5
MASHIKE
RUMOI
OBIRA
HABORO
HOROKANAI

Sample Output 1

2

We can choose three people with the following names:

MASHIKE, RUMOI, HABORO

MASHIKE, RUMOI, HOROKANAI

Thus, we have two ways.

Sample Input 2

4
ZZ
ZZZ
Z
ZZZZZZZZZZ

Sample Output 2

0

Note that there may be no ways to choose three people so that the given conditions are met.

Sample Input 3

5
CHOKUDAI
RNG
MAKOTO
AOKI
RINGO

Sample Output 3

7


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

main = do
  _ <- getLine
  ss <- B.lines <$> B.getContents
  let ns = (map length . groupBy (\s1 s2 -> B.head s1 == B.head s2) . sort . filter ((flip elem "MARCH") . B.head)) ss
  let ans = sum $ do
        let ins = zip [0..] ns
        (i,x) <- ins
        (j,y) <- delete (i,x) ins
        (k,z) <- delete (j,y) (delete (i,x) ins)
        guard (i<j && j<k)
        pure (x*y*z)
  print ans


import Control.Monad
import Control.Monad.ST
import Data.List
import qualified Data.ByteString.Char8 as B
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as UV
import qualified Data.Vector.Unboxed.Mutable as MV

mk h w as = runST $ do
    v' <- MV.replicate (h*w) (0,0) :: ST s (MV.STVector s (Int,Int))
    forM_ (zip [(i,j)|i<-[1..h],j<-[1..w]] as) $ \((i,j),a) ->
        MV.unsafeWrite v' (a-1) (i,j)
    UV.unsafeFreeze v'

main = do
    (h:w:d:_)<-map read.words<$>getLine::IO[Int]
    as<-fmap concat $ replicateM h $ map read.words<$>getLine::IO[Int]
    q<-readLn::IO Int
    lrs<-replicateM q $ unfoldr (B.readInt.B.dropWhile(==' '))<$>B.getLine::IO[[Int]]
    --
    let lij = mk h w as
    --
    spp <- fmap V.fromList $ forM [0..d-1] $ \s -> do
        sp <- forM [s,(s+d)..(h*w)-d-1] $ \l -> do
            let (si,sj) = lij UV.! l
            let (ei,ej) = lij UV.! (l+d)
            return $ abs (si-ei) + abs(sj-ej)
        return $ UV.fromList $ scanl (+) 0 sp
    --
    putStr $ unlines $ map show $ map (solve spp d) lrs
--
solve spp d (l:r:_) = (p r1 r2) - (p l1 l2)
    where
        l1 = (l+(d-1)) `mod` d
        l2 = (l-1) `div` d
        r1 = (r+(d-1)) `mod` d
        r2 = (r-1) `div` d
        p a b = (spp V.! a) UV.! b

Score : 400 points

Problem Statement

We have a grid with H rows and W columns. The square at the i-th row and the j-th column will be called Square (i,j).

The integers from 1 through H×W are written throughout the grid, and the integer written in Square (i,j) is A_{i,j}.

You, a magical girl, can teleport a piece placed on Square (i,j) to Square (x,y) by consuming |x-i|+|y-j| magic points.

You now have to take Q practical tests of your ability as a magical girl.

The i-th test will be conducted as follows:

Initially, a piece is placed on the square where the integer L_i is written.

Let x be the integer written in the square occupied by the piece. Repeatedly move the piece to the square where the integer x+D is written, as long as x is not R_i. The test ends when x=R_i.

Here, it is guaranteed that R_i-L_i is a multiple of D.

For each test, find the sum of magic points consumed during that test.

Constraints

1 \leq H,W \leq 300

1 \leq D \leq H×W

1 \leq A_{i,j} \leq H×W

A_{i,j} \neq A_{x,y} ((i,j) \neq (x,y))

1 \leq Q \leq 10^5

1 \leq L_i \leq R_i \leq H×W

(R_i-L_i) is a multiple of D.

Input

Input is given from Standard Input in the following format:

H W D
A_{1,1} A_{1,2} ... A_{1,W}
:
A_{H,1} A_{H,2} ... A_{H,W}
Q
L_1 R_1
:
L_Q R_Q

Output

For each test, print the sum of magic points consumed during that test.

Output should be in the order the tests are conducted.

Sample Input 1

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

Sample Output 1

5

4 is written in Square (1,2).

6 is written in Square (3,3).

8 is written in Square (3,1).

Thus, the sum of magic points consumed during the first test is (|3-1|+|3-2|)+(|3-3|+|1-3|)=5.

Sample Input 2

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

Sample Output 2

0
0

Note that there may be a test where the piece is not moved at all, and there may be multiple identical tests.

Sample Input 3

5 5 4
13 25 7 15 17
16 22 20 2 9
14 11 12 1 19
10 6 23 8 18
3 21 5 24 4
3
13 13
2 10
13 13

Sample Output 3

0
5
0


import Data.Char

main = do
  n <- getLine

  print $ maximum $ map (sum . map (\c -> ord c - ord '0')) (solve [] n)

  where
    solve pre [] = [pre]
    solve pre (x:xs) = (pre ++ (chr (ord x - 1) : map (const '9') xs)) : solve (pre++[x])xs

Score : 300 points

Problem Statement

Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.

Constraints

1\leq N \leq 10^{16}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.

Sample Input 1

100

Sample Output 1

18

For example, the sum of the digits in 99 is 18, which turns out to be the maximum value.

Sample Input 2

9995

Sample Output 2

35

For example, the sum of the digits in 9989 is 35, which turns out to be the maximum value.

Sample Input 3

3141592653589793

Sample Output 3

137


import Control.Monad

main :: IO ()
main = replicateM 2 readLn >>= putStrLn . solve

solve :: [Int] -> String
solve [n, a]
    | n `mod` 500 > a = "No"
    | otherwise = "Yes"

Score: 100 points

Problem Statement

E869120 has A 1-yen coins and infinitely many 500-yen coins.

Determine if he can pay exactly N yen using only these coins.

Constraints

N is an integer between 1 and 10000 (inclusive).

A is an integer between 0 and 1000 (inclusive).

Input

Input is given from Standard Input in the following format:

N
A

Output

If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print Yes; otherwise, print No.

Sample Input 1

2018
218

Sample Output 1

Yes

We can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer is Yes.

Sample Input 2

2763
0

Sample Output 2

No

When we have no 1-yen coins, we can only pay a multiple of 500 yen using only 500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.

Sample Input 3

37
514

Sample Output 3

Yes


import Data.List

main :: IO ()
main = do
  n <- readLn :: IO Int
  xs <- reverse . sort . map read . words <$> getLine :: IO [Int]
  print $ game xs

game :: [Int] -> Int
game [] = 0
game [x] = x
game (x:y:xs) = x-y + game xs

Score: 200 points

Problem Statement

We have N cards. A number a_i is written on the i-th card.

Alice and Bob will play a game using these cards. In this game, Alice and Bob alternately take one card. Alice goes first.

The game ends when all the cards are taken by the two players, and the score of each player is the sum of the numbers written on the cards he/she has taken. When both players take the optimal strategy to maximize their scores, find Alice's score minus Bob's score.

Constraints

N is an integer between 1 and 100 (inclusive).

a_i \ (1 \leq i \leq N) is an integer between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 a_3 ... a_N

Output

Print Alice's score minus Bob's score when both players take the optimal strategy to maximize their scores.

Sample Input 1

2
3 1

Sample Output 1

2

First, Alice will take the card with 3. Then, Bob will take the card with 1.
The difference of their scores will be 3 - 1 = 2.

Sample Input 2

3
2 7 4

Sample Output 2

5

First, Alice will take the card with 7. Then, Bob will take the card with 4. Lastly, Alice will take the card with 2. The difference of their scores will be 7 - 4 + 2 = 5. The difference of their scores will be 3 - 1 = 2.

Sample Input 3

4
20 18 2 18

Sample Output 3

18


import Data.List
main = do
    getLine
    a_s <- map read . words <$> getLine
    print $ sum $ zipWith (*) (cycle [1, -1]) $ reverse $ sort a_s


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

readInt = fromIntegral . fst . fromJust . BS.readInteger

readIntList = map readInt . BS.words

getInt = readInt <$> BS.getLine

getIntList = readIntList <$> BS.getLine

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

checkI css tup 0 _ = True
checkI css tup n v
  | n == 3 = checkI css tup (n -1) diff
  | v == diff = checkI css tup (n -1) v
  | otherwise = False
  where
    diff = css ! (fst tup, n) - css ! (snd tup, n)

checkJ css tup 0 _ = True
checkJ css tup n v
  | n == 3 = checkJ css tup (n -1) diff
  | v == diff = checkJ css tup (n -1) v
  | otherwise = False
  where
    diff = css ! (n, fst tup) - css ! (n, snd tup)

main = do
  let num = 3
  css <- getIntNList num
  let css' = listArray ((1, 1), (num, num)) (concat css)
  if checkI css' (3, 2) 3 0 && checkI css' (2, 1) 3 0 && checkJ css' (3, 2) 3 0 && checkJ css' (2, 1) 3 0
    then putStrLn "Yes"
    else putStrLn "No"

Score: 300 points

Problem Statement

We have a 3 \times 3 grid. A number c_{i, j} is written in the square (i, j), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.

According to Takahashi, there are six integers a_1, a_2, a_3, b_1, b_2, b_3 whose values are fixed, and the number written in the square (i, j) is equal to a_i + b_j.

Determine if he is correct.

Constraints

c_{i, j} \ (1 \leq i \leq 3, 1 \leq j \leq 3) is an integer between 0 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

c_{1,1} c_{1,2} c_{1,3}
c_{2,1} c_{2,2} c_{2,3}
c_{3,1} c_{3,2} c_{3,3}

Output

If Takahashi's statement is correct, print Yes; otherwise, print No.

Sample Input 1

1 0 1
2 1 2
1 0 1

Sample Output 1

Yes

Takahashi is correct, since there are possible sets of integers such as: a_1=0,a_2=1,a_3=0,b_1=1,b_2=0,b_3=1.

Sample Input 2

2 2 2
2 1 2
2 2 2

Sample Output 2

No

Takahashi is incorrect in this case.

Sample Input 3

0 8 8
0 8 8
0 8 8

Sample Output 3

Yes

Sample Input 4

1 8 6
2 9 7
0 7 7

Sample Output 4

No


import Control.Applicative

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

solve :: [Int] -> Int
solve [x, y]
  | x `mod` y == 0 = (-1)
  | otherwise = x

Score : 100 points

Problem Statement

You are given positive integers X and Y.
If there exists a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, choose one such integer and print it.
If it does not exist, print -1.

Constraints

1 ≤ X,Y ≤ 10^9

X and Y are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, or print -1 if it does not exist.

Sample Input 1

8 6

Sample Output 1

16

For example, 16 is a multiple of 8 but not a multiple of 6.

Sample Input 2

3 3

Sample Output 2

-1

A multiple of 3 is a multiple of 3.


main = do
  [x,y] <- map read . words <$> getLine :: IO [Int]
  if mod x y /= 0
    then print x
    else print $ negate 1