{-# LANGUAGE BangPatterns #-}
import           Control.Exception (assert, evaluate)

main :: IO ()
main = do
  n <- readLn
  s <- getLine
  evaluate $ assert (length s == n) ()
  q <- readLn
  ks <- take q . map read . words <$> getLine
  putStr . unlines . map (show . (\k -> f k s)) $ ks

f :: Int -> String -> Int
f k = dmc . foldl g initialState . defer k
  where
    g state (c, c') = (countIn c (maybe id countOut c' state))

-- Strict にしないと TLE がでる
data State =
  State
  { d   :: !Int
  , m   :: !Int
  , dm  :: !Int
  , dmc :: !Int
  }

defer :: Int -> [a] -> [(a, Maybe a)]
defer n xs = zip xs $ replicate n Nothing ++ map Just xs

initialState :: State
initialState = State { d = 0, m = 0, dm = 0, dmc = 0 }

countIn :: Char -> State -> State
countIn 'D' count = count { d = d count + 1 }
countIn 'M' count = count { m = m count + 1, dm = dm count + d count }
countIn 'C' count = count { dmc = dmc count + dm count }
countIn _   count = count

countOut :: Char -> State -> State
countOut 'D' count = count { d = d count - 1, dm = dm count - m count }
countOut 'M' count = count { m = m count - 1 }
countOut _   count = count

Score : 600 points

Problem Statement

In Dwango Co., Ltd., there is a content distribution system named 'Dwango Media Cluster', and it is called 'DMC' for short.

The name 'DMC' sounds cool for Niwango-kun, so he starts to define DMC-ness of a string.

Given a string S of length N and an integer k (k \geq 3),
he defines the k-DMC number of S as the number of triples (a, b, c) of integers that satisfy the following conditions:

0 \leq a < b < c \leq N - 1

S[a] = D

S[b] = M

S[c] = C

c-a < k

Here S[a] is the a-th character of the string S. Indexing is zero-based, that is, 0 \leq a \leq N - 1 holds.

For a string S and Q integers k_0, k_1, ..., k_{Q-1}, calculate the k_i-DMC number of S for each i (0 \leq i \leq Q-1).

Constraints

3 \leq N \leq 10^6

S consists of uppercase English letters

1 \leq Q \leq 75

3 \leq k_i \leq N

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

N
S
Q
k_{0} k_{1} ... k_{Q-1}

Output

Print Q lines.
The i-th line should contain the k_i-DMC number of the string S.

Sample Input 1

18
DWANGOMEDIACLUSTER
1
18

Sample Output 1

1

(a,b,c) = (0, 6, 11) satisfies the conditions.

Strangely, Dwango Media Cluster does not have so much DMC-ness by his definition.

Sample Input 2

18
DDDDDDMMMMMCCCCCCC
1
18

Sample Output 2

210

The number of triples can be calculated as 6\times 5\times 7.

Sample Input 3

54
DIALUPWIDEAREANETWORKGAMINGOPERATIONCORPORATIONLIMITED
3
20 30 40

Sample Output 3

0
1
2

(a, b, c) = (0, 23, 36), (8, 23, 36) satisfy the conditions except the last one, namely, c-a < k_i.

By the way, DWANGO is an acronym for "Dial-up Wide Area Network Gaming Operation".

Sample Output 4

30
DMCDMCDMCDMCDMCDMCDMCDMCDMCDMC
4
5 10 15 20

Sample Output 4

10
52
110
140


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

main :: IO ()
main = do
  [x, y] <- getInts
  print $ solve x y

solve :: Int -> Int -> Int
solve x y = x + y `div` 2

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

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

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

Score: 100 points

Problem Statement

There is a train going from Station A to Station B that costs X yen (the currency of Japan).

Also, there is a bus going from Station B to Station C that costs Y yen.

Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then travels from Station B to Station C by bus.

How much does it cost to travel from Station A to Station C if she uses this ticket?

Constraints

1 \leq X,Y \leq 100

Y is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If it costs x yen to travel from Station A to Station C, print x.

Sample Input 1

81 58

Sample Output 1

110

The train fare is 81 yen.

The train fare is 58 ⁄ 2=29 yen with the 50% discount.

Thus, it costs 110 yen to travel from Station A to Station C.

Sample Input 2

4 54

Sample Output 2

31

Submitted source-code file size, in bytes.

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

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


import Data.List (minimumBy)
import Data.Function (on)

main = do n <- readLn :: IO Int
          [t, a] <- map read . words <$> getLine
          hs <- map read . words <$> getLine

          let poyo = zip [1..] [abs (a - t * 1000 - h * 6) | h <- hs]
          print $ fst $ minimumBy (compare `on` snd) poyo

Score: 200 points

Problem Statement

A country decides to build a palace.

In this country, the average temperature of a point at an elevation of x meters is T-x \times 0.006 degrees Celsius.

There are N places proposed for the place. The elevation of Place i is H_i meters.

Among them, Princess Joisino orders you to select the place whose average temperature is the closest to A degrees Celsius, and build the palace there.

Print the index of the place where the palace should be built.

It is guaranteed that the solution is unique.

Constraints

1 \leq N \leq 1000

0 \leq T \leq 50

-60 \leq A \leq T

0 \leq H_i \leq 10^5

All values in input are integers.

The solution is unique.

Input

Input is given from Standard Input in the following format:

N
T A
H_1 H_2 ... H_N

Output

Print the index of the place where the palace should be built.

Sample Input 1

2
12 5
1000 2000

Sample Output 1

1

The average temperature of Place 1 is 12-1000 \times 0.006=6 degrees Celsius.

The average temperature of Place 2 is 12-2000 \times 0.006=0 degrees Celsius.

Thus, the palace should be built at Place 1.

Sample Input 2

3
21 -11
81234 94124 52141

Sample Output 2

3


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

main = do
    n<-readLn::IO Int
    (t:a:_)<-map read.words<$>getLine::IO [Int]
    hs<-unfoldr (B.readInt.B.dropWhile(==' '))<$>B.getLine::IO[Int]
    --
    print $ snd $ minimum $ zip (map (\x-> abs(t*1000 - x*1000*6 - a*1000)) hs) [1..]


import Data.List

collect :: Int -> IO [(Int,(Int,Int))]
collect n = zip [1..n] <$> geniof (\(x:y:ls) -> (x,y)) n

cdigit :: Int -> Int
cdigit n | (n`div`10 == 0) = 1
         | otherwise       = 1+(cdigit $ n`div`10)

rewrite :: Int -> [(Int,(Int,Int))] -> [(Int,String)]
rewrite _ [] = []
rewrite c ((a,(p,y)):ls) = let
   id6 = take (6-(cdigit p)) (repeat '0')  ++ (show p) ++ take (6-(cdigit c)) (repeat '0') ++  (show c)
   in if ls == [] || (fst.snd.head $ ls) == p
         then (a,id6) : rewrite (c+1) ls
         else (a,id6) : rewrite 1 ls

writedownf :: (a -> String) -> [a] -> IO ()
writedownf _ [] = return ()
writedownf f (x:xs) = putStrLn (f x) >> writedownf f xs

writedown ::  [String] -> IO ()
writedown = writedownf id

main :: IO ()
main = do
  [n,m] <- map read.words <$> getLine
  l <- (sortOn $ snd) <$> collect  m
  writedownf snd $ sortOn fst $ rewrite 1 l

geniof :: Read a => ([a] -> b) -> Int -> IO [b]
geniof _ 0 = return []
geniof f n = do
  l <- map read <$> words <$> getLine
  ls <- geniof f (n-1)
  return $ (f l):ls

genio :: Read b => Int -> IO [[b]]
genio = geniof id

Score: 300 points

Problem Statement

In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.

City i is established in year Y_i and belongs to Prefecture P_i.

You can assume that there are no multiple cities that are established in the same year.

It is decided to allocate a 12-digit ID number to each city.

If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.

Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.

Find the ID numbers for all the cities.

Note that there can be a prefecture with no cities.

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq P_i \leq N

1 \leq Y_i \leq 10^9

Y_i are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
P_1 Y_1
:
P_M Y_M

Output

Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).

Sample Input 1

2 3
1 32
2 63
1 12

Sample Output 1

000001000002
000002000001
000001000001

As City 1 is the second established city among the cities that belong to Prefecture 1, its ID number is 000001000002.

As City 2 is the first established city among the cities that belong to Prefecture 2, its ID number is 000002000001.

As City 3 is the first established city among the cities that belong to Prefecture 1, its ID number is 000001000001.

Sample Input 2

2 3
2 55
2 77
2 99

Sample Output 2

000002000001
000002000002
000002000003


import Control.Monad
import Data.Maybe
import Debug.Trace
import Data.List
import qualified Data.Map.Strict as Map
import qualified Data.IntMap.Strict as IntMap
import qualified Data.Set as Set
import qualified Data.IntSet as IntSet
import Data.Functor
import Data.Array

main :: IO ()
main = do
  (n:m:_) <- fmap (map read . words) getLine :: IO [Int]
  pys <- replicateM m $ map read . words <$> getLine :: IO [[Int]]
  putStr $ unlines $ solve n pys

-- solve :: It -> [[Int]] -> [String]
solve n pys = map (\(p:y:_) -> (seikei p) ++ seikei (dicdic IntMap.! p IntMap.! y)) pys
  where
    dic = foldr (\(p:y:_) acc -> IntMap.insertWith (++) p [y] acc) IntMap.empty pys :: IntMap.IntMap [Int]
    dicdic = IntMap.map (\l -> IntMap.fromList (zip l [1..])) dic

seikei :: Int -> String
seikei x = (replicate (6 - l) '0') ++ xstr
  where
    xstr = show x
    l = length xstr


import Control.Monad
import Data.List
import Data.Ord
import Text.Printf

main :: IO ()
main = do
  [n,m] <- getInts
  pys <- replicateM m $ do
    [p,y] <- getInts
    return (p,y)
  putStr . unlines $ solve pys

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

format :: (Int,Int) -> String
format (p,i) = printf "%06d%06d" p i

solve :: [(Int,Int)] -> [String]
solve cs = [format (p, 1 + rank p y) | (p,y) <- cs]
  where
    cs' = sortBy (comparing snd) cs
    rank p0 y0 = length $ filter (\(p,_) -> p == p0) $ takeWhile (\(_,y) -> y < y0) cs'


main :: IO ()
main = interact go

go :: String -> String
go s@[_, _, '\n'] = s
go s@[_, _, _, '\n'] = reverse s
go s = error (show s)

Score : 100 points

Problem Statement

You are given a string S of length 2 or 3 consisting of lowercase English letters. If the length of the string is 2, print it as is; if the length is 3, print the string after reversing it.

Constraints

The length of S is 2 or 3.

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If the length of S is 2, print S as is; if the length is 3, print S after reversing it.

Sample Input 1

abc

Sample Output 1

cba

As the length of S is 3, we print it after reversing it.

Sample Input 2

ac

Sample Output 2

ac

As the length of S is 2, we print it as is.


main :: IO ()
main = do
  s <-  getLine
  if length s == 2 then putStrLn $ s else putStrLn $ reverse s


import Data.List
import Data.Tuple
import Data.Monoid
import Data.Foldable

oper (a, b) = let h = div a 2 in (b+h, h)

f [a, b, k] = (if odd k then swap else id) $ appEndo (foldMap Endo (replicate k oper)) (a, b)

joinTuple (a, b) = show a ++ " " ++ show b

main = do
    map read . words <$> getLine >>= putStrLn . joinTuple . f

Score : 200 points

Problem Statement

In the beginning, Takahashi has A cookies, and Aoki has B cookies.
They will perform the following operation alternately, starting from Takahashi:

If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person.

Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total.

Constraints

1 \leq A,B \leq 10^9

1 \leq K \leq 100

A,B and K are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total.

Sample Input 1

5 4 2

Sample Output 1

5 3

The process will go as follows:

In the beginning, Takahashi and Aoki have 5 and 4 cookies, respectively.

Takahashi eats one cookie and gives two cookies to Aoki. They now have 2 and 6 cookies, respectively.

Aoki gives three cookies to Takahashi. They now have 5 and 3 cookies, respectively.

Sample Input 2

3 3 3

Sample Output 2

1 3

Sample Input 3

314159265 358979323 84

Sample Output 3

448759046 224379523


import Control.Applicative
import Control.Monad

main :: IO ()
main = do
  [n, tl] <- f
  solve tl <$> replicateM n f >>= putStrLn
  where
    f = map read <$> words <$> getLine

solve :: Int -> [[Int]] -> String
solve tl cts = let cts' = filter (\[_,t] -> t <= tl) cts
               in if null cts' then "TLE" else (show . (!! 0) . minimum) cts'

Score : 200 points

Problem Statement

When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.

You, the smartwatch, has found N routes to his home.

If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i.

Find the smallest cost of a route that takes not longer than time T.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq T \leq 1000

1 \leq c_i \leq 1000

1 \leq t_i \leq 1000

The pairs (c_i, t_i) are distinct.

Input

Input is given from Standard Input in the following format:

N T
c_1 t_1
c_2 t_2
:
c_N t_N

Output

Print the smallest cost of a route that takes not longer than time T.

If there is no route that takes not longer than time T, print TLE instead.

Sample Input 1

3 70
7 60
1 80
4 50

Sample Output 1

4

The first route gets him home at cost 7.

The second route takes longer than time T = 70.

The third route gets him home at cost 4.

Thus, the cost 4 of the third route is the minimum.

Sample Input 2

4 3
1 1000
2 4
3 1000
4 500

Sample Output 2

TLE

There is no route that takes not longer than time T = 3.

Sample Input 3

5 9
25 8
5 9
4 10
1000 1000
6 1

Sample Output 3

5


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

main :: IO ()
main = breads >>= print . solve

solve :: [Int] -> Int
solve [n, m]
    | v == 0 = r
    | otherwise = calc [r, (r - 1)..1]
    where
        (r, v) = m `divMod` n

        calc (ans : xs)
            | y > 0 = calc xs
            | x > n + 1 = ans
            | otherwise = calc xs
            where
                (x, y) = m `divMod` ans

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

Score : 400 points

Problem Statement

You are given integers N and M.

Consider a sequence a of length N consisting of positive integers such that a_1 + a_2 + ... + a_N = M. Find the maximum possible value of the greatest common divisor of a_1, a_2, ..., a_N.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

N \leq M \leq 10^9

Input

Input is given from Standard Input in the following format:

N M

Output

Print the maximum possible value of the greatest common divisor of a sequence a_1, a_2, ..., a_N that satisfies the condition.

Sample Input 1

3 14

Sample Output 1

2

Consider the sequence (a_1, a_2, a_3) = (2, 4, 8). Their greatest common divisor is 2, and this is the maximum value.

Sample Input 2

10 123

Sample Output 2

3

Sample Input 3

100000 1000000000

Sample Output 3

10000


f x=if mod x 111==0 then x else f(x+1);main=readLn>>=print.f

Score : 200 points

Problem Statement

Kurohashi has never participated in AtCoder Beginner Contest (ABC).

The next ABC to be held is ABC N (the N-th ABC ever held).
Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.

What is the earliest ABC where Kurohashi can make his debut?

Constraints

100 \leq N \leq 999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If the earliest ABC where Kurohashi can make his debut is ABC n, print n.

Sample Input 1

111

Sample Output 1

111

The next ABC to be held is ABC 111, where Kurohashi can make his debut.

Sample Input 2

112

Sample Output 2

222

The next ABC to be held is ABC 112, which means Kurohashi can no longer participate in ABC 111.
Among the ABCs where Kurohashi can make his debut, the earliest one is ABC 222.

Sample Input 3

750

Sample Output 3

777


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns          #-}
{-# LANGUAGE CPP                   #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE RecordWildCards       #-}
{-# LANGUAGE TupleSections         #-}
{-# LANGUAGE TypeFamilies          #-}

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Data.Bool
import qualified Data.ByteString.Char8       as B
import qualified Data.ByteString.Unsafe      as B
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
import qualified Data.IntMap.Strict          as IM
import qualified Data.IntSet                 as IS
import qualified Data.List                   as L
import qualified Data.Map.Strict             as M
import           Data.Monoid
import           Data.Ord
import           Data.Primitive.MutVar
import qualified Data.Set                    as S
import           Data.Tuple
import qualified Data.Vector                 as V
import qualified Data.Vector.Generic         as G
import qualified Data.Vector.Generic.Mutable as GM
import qualified Data.Vector.Unboxed         as U
import qualified Data.Vector.Unboxed.Mutable as UM
import           Debug.Trace
import           Foreign                     hiding (void)
import           Unsafe.Coerce

main :: IO ()
main = do
    !n <- readLn :: IO Int
    xys <- U.unfoldrN (div n 2) parseInt2 <$> B.getLine
    print $ solve n xys

lim :: Int
lim = 10^5

solve :: Int -> U.Vector (Int, Int) -> Int
solve 2 xys
    | uncurry (/=) $ U.head xys = 0
    | otherwise = 1
solve n xys
    | freqMaxIxX /= freqMaxIxY = n - U.maximum freqX - U.maximum freqY
    | otherwise = minimum
        [ n - freqX U.! freqMaxIxX - freqMaxY'
        , n - freqMaxX' - freqY U.! freqMaxIxY
        ]
  where
    xs = U.map fst xys
    ys = U.map snd xys

    freqX = freq xs
    freqY = freq ys

    freqMaxIxX = U.maxIndex freqX
    freqMaxIxY = U.maxIndex freqY

    freqMaxX' = U.maximum $ U.ifilter (\i _ -> i /= freqMaxIxX) freqX
    freqMaxY' = U.maximum $ U.ifilter (\i _ -> i /= freqMaxIxY) freqY

freq :: U.Vector Int -> U.Vector Int
freq = U.accumulate (+) (U.replicate (lim + 1) 0) . U.map (flip (,) 1)

-------------------------------------------------------------------------------
type Parser a = B.ByteString -> Maybe (a, B.ByteString)

parseInt :: Parser Int
parseInt = B.readInt . B.dropWhile isSpace

parseInt2 :: Parser (Int, Int)
parseInt2 = runStateT $
    (,) <$> StateT (B.readInt . B.dropWhile isSpace)
        <*> StateT (B.readInt . B.unsafeTail)

parseInt3 :: Parser (Int, Int, Int)
parseInt3 = runStateT $
    (,,) <$> StateT (B.readInt . B.dropWhile isSpace)
        <*> StateT (B.readInt . B.unsafeTail)
        <*> StateT (B.readInt . B.unsafeTail)

parseInt4 :: Parser (Int, Int, Int, Int)
parseInt4 = runStateT $
    (,,,) <$> StateT (B.readInt . B.dropWhile isSpace)
        <*> StateT (B.readInt . B.unsafeTail)
        <*> StateT (B.readInt . B.unsafeTail)
        <*> StateT (B.readInt . B.unsafeTail)

Score : 300 points

Problem Statement

A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied:

For each i = 1,2,..., n-2, a_i = a_{i+2}.

Exactly two different numbers appear in the sequence.

You are given a sequence v_1,v_2,...,v_n whose length is even.
We would like to make this sequence /\/\/\/ by replacing some of its elements.
Find the minimum number of elements that needs to be replaced.

Constraints

2 \leq n \leq 10^5

n is even.

1 \leq v_i \leq 10^5

v_i is an integer.

Input

Input is given from Standard Input in the following format:

n
v_1 v_2 ... v_n

Output

Print the minimum number of elements that needs to be replaced.

Sample Input 1

4
3 1 3 2

Sample Output 1

1

The sequence 3,1,3,2 is not /\/\/\/, but we can make it /\/\/\/ by replacing one of its elements: for example, replace the fourth element to make it 3,1,3,1.

Sample Input 2

6
105 119 105 119 105 119

Sample Output 2

0

The sequence 105,119,105,119,105,119 is /\/\/\/.

Sample Input 3

4
1 1 1 1

Sample Output 3

2

The elements of the sequence 1,1,1,1 are all the same, so it is not /\/\/\/.


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

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

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

import qualified Data.ByteString.Char8 as B

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

import Debug.Trace
import Text.Printf

import GHC.Exts

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

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

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

main = do
	n <- readInt
	as <- readInts
	let
		f = map fst . filter snd . zip as . cycle
		evens = f [ True, False ]
		odds  = f [ False, True ]
	print $ ( n - ) $ minimum' ( n `div` 2 ) $ do
		( a, c1 ) <- take 2 $ majors evens
		( b, c2 ) <- take 2 $ majors odds
		guard $ a /= b
		return $ c1 + c2

majors as = runST $ do
	counts <- newArray ( 0, maximum as + 1 ) 0 :: ST s ( STUArray s Int Int )
	forM_ as $ \a -> do
		modifyArray counts a succ
	reverse . sortWith snd . filter ( ( 0 < ) . snd ) <$> getAssocs counts

minimum' a [] = a
minimum' _ as = minimum as


import Data.List

splitRec _ [] = []
splitRec n xs = let (h, t) = splitAt n xs in h : splitRec n t

counting = (++[(0, 0)]) . sortBy (flip compare) . map (\es -> (length es, head es)) . group . sort

calc n os es
  | ov /= ev || length (takeWhile ((==oc) . fst) os) > 1 || length (takeWhile ((==ec) . fst) es) > 1 = n - oc - ec
  | otherwise = min (n - oc - secondc es) (n - ec - secondc os)
  where
    (oc, ov) = head os
    (ec, ev) = head es
    secondc = fst . head . tail

main = do
    n <- readLn :: IO Int
    [os, es] <- map counting . transpose . splitRec 2 . map (read :: String -> Int) . words <$> getLine
    print $ calc n os es


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

main :: IO ()
main = getLine >> readLine >>= print . solve

solve :: [Int] -> Int
solve vs = check as bs
    where
        check xxs@((an, al) : xs) yys@((bn, bl) : ys)
            | an /= bn = n - al - bl
            | al > bl = check xs yys
            | otherwise = check xxs ys
        check ((_, al) : _) _ = n - al
        check _ ((_, bl) : _) = n - bl
        check _ _ = n

        as = count es
        bs = count os

        n = length vs

        count = sortBy cmpf . map mf . group . sort
            where
                cmpf lhs rhs = comparing snd rhs lhs `mappend` comparing fst lhs rhs
                mf = (,) <$> head <*> length

        (es, os) = fst $ foldr ff (([], []), True) vs
            where
                ff v ((acc, bcc), f)
                    | f = ((v : acc, bcc), not f)
                    | otherwise = ((acc, v : bcc), not f)

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

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


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

main = do
    s <- B.getLine
    t <- B.getLine
    xs <- VUM.replicate 26 (0 :: Int)
    ys <- VUM.replicate 26 (0 :: Int)
    forM_ [0..B.length s - 1] $ \i -> do
        let s' = B.index s i
        let t' = B.index t i
        VUM.modify xs (+1) (ord s' - ord 'a')
        VUM.modify ys (+1) (ord t' - ord 'a')
    xs' <- sort . VU.toList <$> VU.unsafeFreeze xs
    ys' <- sort . VU.toList <$> VU.unsafeFreeze ys
    putStrLn $ if and $ zipWith (==) xs' ys' then "Yes" else "No"

Score : 300 points

Problem Statement

You are given strings S and T consisting of lowercase English letters.

You can perform the following operation on S any number of times:

Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1.

Determine if S and T can be made equal by performing the operation zero or more times.

Constraints

1 \leq |S| \leq 2 \times 10^5

|S| = |T|

S and T consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S and T can be made equal, print Yes; otherwise, print No.

Sample Input 1

azzel
apple

Sample Output 1

Yes

azzel can be changed to apple, as follows:

Choose e as c_1 and l as c_2. azzel becomes azzle.

Choose z as c_1 and p as c_2. azzle becomes apple.

Sample Input 2

chokudai
redcoder

Sample Output 2

No

No sequences of operation can change chokudai to redcoder.

Sample Input 3

abcdefghijklmnopqrstuvwxyz
ibyhqfrekavclxjstdwgpzmonu

Sample Output 3

Yes


import Data.List

code :: String -> [Int]
code [] = []
code [x] = [1]
code (x:y:l) = if x==y then (1+(head $ code $ y:l)):(tail $ code $ y:l)
                       else 1:(code $ y:l)

main :: IO ()
main = do
  l <- sort <$> getLine
  r <- sort <$> getLine
  if ((length l) == (length r)) && ((code l) == (code r)) then putStrLn "Yes" else putStrLn "No"


import Data.List

code :: String -> [Int]
code [] = []
code [x] = [1]
code (x:y:l) = if x==y then (1+(head $ code $ y:l)):(tail $ code $ y:l)
                       else 1:(code $ y:l)

main :: IO ()
main = do
  l <- code . sort <$> getLine
  r <- code . sort <$> getLine
  if l == r then putStrLn "Yes" else putStrLn "No"


{-# LANGUAGE DataKinds      #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeOperators  #-}

import           Data.List    (group)
import           Data.Ratio   (denominator, numerator)
import           GHC.TypeLits (KnownNat, Nat, natVal, type (+), type (^))

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

type Modulus = 10 ^ 9 + 7

f :: Int -> Int -> Int
f n m = unModular $ g $ map (fromIntegral . length) $ group $ factors m
  where
    g :: [Modular Int Modulus] -> Modular Int Modulus
    g = product . map (\b -> nCombinations (b + fromIntegral n - 1) b)

factors :: Integral a => a -> [a]
factors = factors' primes
  where
    factors' pps@(p:ps) n
      | n < 2              = []
      | n < p ^ (2 :: Int) = [n]  -- stop early
      | n `mod` p == 0     = p : factors' pps (n `div` p)
      | otherwise          = factors' ps n
    factors' _ _ = error "`primes` is a infinite list"

primes :: Integral a => [a]
primes = 2 : filter (\n -> head (factors n) == n) [3, 5 ..]

nCombinations :: (Eq a, Fractional a) => a -> a -> a
nCombinations n k = factorial n / factorial k / factorial (n - k)

factorial :: (Eq a, Num a) => a -> a
factorial 0 = 1
factorial n = n * factorial (n - 1)

tests, test1, test2, test3 :: Bool
tests = test1 && test2 && test3
test1 = f 2 6 == 4
test2 = f 3 12 == 18
test3 = f 100000 1000000000 == 957870001

newtype Modular a (modulus :: Nat) =
  Modular { unModular :: a }
  deriving (Eq)

instance Show a => Show (Modular a modulus) where
  show (Modular n) = show n

instance (Integral a, KnownNat modulus) => Num (Modular a modulus) where
  fromInteger           = toModular . fromInteger
  Modular n + Modular m = toModular $ n + m
  Modular n * Modular m = toModular $ n * m
  negate (Modular n)    = toModular $ negate n
  abs (Modular n)       = toModular $ abs n
  signum (Modular n)    = toModular $ signum n

instance (Integral a, KnownNat modulus) => Fractional (Modular a modulus) where
  recip m@(Modular n) = toModular $ modularReciprocal (fromInteger (natVal m)) n
  fromRational r = fromInteger (numerator r) / fromInteger (denominator r)

toModular :: (Integral a, KnownNat modulus) => a -> Modular a modulus
toModular n = let m = Modular $ n `mod` fromInteger (natVal m) in m

modularReciprocal :: Integral a => a -> a -> a
modularReciprocal modulus n = snd $ modularReciprocal' modulus n
  where
    -- modularReciprocal' n m = (x, y)
    -- n * x + m * y = 1
    modularReciprocal' _ 0 = notCoprimeError
    modularReciprocal' _ 1 = (0, 1)
    modularReciprocal' m l = (y, x - q * y)
      where
        (q, r) = m `divMod` l
        (x, y) = modularReciprocal' l r
    notCoprimeError =
      error $ unwords
        [ "divider"
        , parentheses $ showIntegral n
        , "must be coprime to modulus"
        , parentheses $ showIntegral modulus
        ]
    parentheses s = "(" ++ s ++ ")"
    showIntegral = show . toInteger

Score : 400 points

Problem Statement

You are given positive integers N and M.

How many sequences a of length N consisting of positive integers satisfy a_1 \times a_2 \times ... \times a_N = M? Find the count modulo 10^9+7.

Here, two sequences a' and a'' are considered different when there exists some i such that a_i' \neq a_i''.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^9

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of the sequences consisting of positive integers that satisfy the condition, modulo 10^9 + 7.

Sample Input 1

2 6

Sample Output 1

4

Four sequences satisfy the condition: \{a_1, a_2\} = \{1, 6\}, \{2, 3\}, \{3, 2\} and \{6, 1\}.

Sample Input 2

3 12

Sample Output 2

18

Sample Input 3

100000 1000000000

Sample Output 3

957870001


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

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

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

import qualified Data.ByteString.Char8 as B

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

import Debug.Trace
import Text.Printf

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

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

modBase = 1000000007 :: Integer

a *% b = ( a * b ) `mod` modBase

primeFactorization 1 = []
primeFactorization n = f 2 n
	where
		f p n
			| n == p = [p]
			| n `mod` p == 0 = p : f p ( n `div` p )
			| otherwise = f ( p + 1 ) n

nCr 0 _ = 1
nCr _ 0 = 1
nCr n r = nCr ( n - 1 ) ( r - 1 ) * n `div` r

nHr n r = nCr ( n + r - 1 ) r

main = do
	[ n, m ] <- map fromIntegral <$> readInts
	let degrees = map ( fromIntegral . length ) $ group $ primeFactorization m
	print $ foldl (*%) 1 $ map ( n `nHr` ) degrees


import Data.List
main=do
 [n,k]<-map read.words<$>getLine
 a<-scanl1(+).sort.map read.words<$>getLine
 let b=length$takeWhile(k>=)a
 print$if b==n&&last a<k then n-1 else b

Score : 200 points

Problem Statement

There are N children, numbered 1, 2, ..., N.

Snuke has decided to distribute x sweets among them.
He needs to give out all the x sweets, but some of the children may get zero sweets.

For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets.
Snuke is trying to maximize the number of happy children by optimally distributing the sweets.
Find the maximum possible number of happy children.

Constraints

All values in input are integers.

2 \leq N \leq 100

1 \leq x \leq 10^9

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Print the maximum possible number of happy children.

Sample Input 1

3 70
20 30 10

Sample Output 1

2

One optimal way to distribute sweets is (20, 30, 20).

Sample Input 2

3 10
20 30 10

Sample Output 2

1

The optimal way to distribute sweets is (0, 0, 10).

Sample Input 3

4 1111
1 10 100 1000

Sample Output 3

4

The optimal way to distribute sweets is (1, 10, 100, 1000).

Sample Input 4

2 10
20 20

Sample Output 4

0

No children will be happy, no matter how the sweets are distributed.


import Control.Monad
import Control.Applicative

main = do
    [x1,y1,x2,y2]  <- map read . words <$> getLine
    forM [x2 - y2 + y1, y2 + x2 - x1 , x1 - y2 + y1 , y1 + x2 - x1] $ \i -> do
        print i

Score : 200 points

Problem Statement

There is a square in the xy-plane. The coordinates of its four vertices are (x_1,y_1),(x_2,y_2),(x_3,y_3) and (x_4,y_4) in counter-clockwise order.
(Assume that the positive x-axis points right, and the positive y-axis points up.)

Takahashi remembers (x_1,y_1) and (x_2,y_2), but he has forgot (x_3,y_3) and (x_4,y_4).

Given x_1,x_2,y_1,y_2, restore x_3,y_3,x_4,y_4. It can be shown that x_3,y_3,x_4 and y_4 uniquely exist and have integer values.

Constraints

|x_1|,|y_1|,|x_2|,|y_2| \leq 100

(x_1,y_1) ≠ (x_2,y_2)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

x_1 y_1 x_2 y_2

Output

Print x_3,y_3,x_4 and y_4 as integers, in this order.

Sample Input 1

0 0 0 1

Sample Output 1

-1 1 -1 0

(0,0),(0,1),(-1,1),(-1,0) is the four vertices of a square in counter-clockwise order.
Note that (x_3,y_3)=(1,1),(x_4,y_4)=(1,0) is not accepted, as the vertices are in clockwise order.

Sample Input 2

2 3 6 6

Sample Output 2

3 10 -1 7

Sample Input 3

31 -41 -59 26

Sample Output 3

-126 -64 -36 -131


main = map read . words <$> getLine >>= \[n, k] -> print (answer n k)
answer n k = let candidates = [k, 2 * k .. 2 * n] in
    length [() |
      ab <- candidates, bc <- candidates, ca <- candidates,
      let abc = (ab + bc + ca) `div` 2,
      let a = abc - bc,
      let b = abc - ca,
      let c = abc - ab,
      let range x = 0 < x && x <= n,
      (ab + bc + ca) `mod` 2 == 0 && range a && range b && range c]

Score : 300 points

Problem Statement

You are given integers N and K. Find the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K.
The order of a,b,c does matter, and some of them can be the same.

Constraints

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

N and K are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K.

Sample Input 1

3 2

Sample Output 1

9

(1,1,1),(1,1,3),(1,3,1),(1,3,3),(2,2,2),(3,1,1),(3,1,3),(3,3,1) and (3,3,3) satisfy the condition.

Sample Input 2

5 3

Sample Output 2

1

Sample Input 3

31415 9265

Sample Output 3

27

Sample Input 4

35897 932

Sample Output 4

114191


main=interact$show.f.map read.words;f[n,k]=div n k^3+sum[1|x<-[1..n],rem x k*2==k]^3


main = do
    [n, i] <- map read . words <$> getLine
    print $ n - i + 1

Score : 100 points

Problem Statement

There is an N-car train.

You are given an integer i. Find the value of j such that the following statement is true: "the i-th car from the front of the train is the j-th car from the back."

Constraints

1 \leq N \leq 100

1 \leq i \leq N

Input

Input is given from Standard Input in the following format:

N i

Output

Print the answer.

Sample Input 1

4 2

Sample Output 1

3

The second car from the front of a 4-car train is the third car from the back.

Sample Input 2

1 1

Sample Output 2

1

Sample Input 3

15 11

Sample Output 3

5


main = do
  [n,i] <- map read . words <$> getLine
  print $ n - i + 1


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


import Data.Vector.Unboxed as V(fromList,(!),Vector)
import Control.Monad

inf :: Int
inf = 200000000

main :: IO ()
main = do
  [n,k] <- map read.words <$> getLine
  as <- V.fromList . map read.words <$> getLine :: IO (Vector Int)
  ls <- forM [0..n-k] $ \i -> return $ (min (abs $ as!i) $ (abs $ as!(i+k-1))) + (as!(i+k-1) - as!i)
  print $ minimum ls

Score : 300 points

Problem Statement

There are N candles placed on a number line.
The i-th candle from the left is placed on coordinate x_i.
Here, x_1 < x_2 < ... < x_N holds.

Initially, no candles are burning.
Snuke decides to light K of the N candles.

Now, he is at coordinate 0.
He can move left and right along the line with speed 1.
He can also light a candle when he is at the same position as the candle, in negligible time.

Find the minimum time required to light K candles.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq N

x_i is an integer.

|x_i| \leq 10^8

x_1 < x_2 < ... < x_N

Input

Input is given from Standard Input in the following format:

N K
x_1 x_2 ... x_N

Output

Print the minimum time required to light K candles.

Sample Input 1

5 3
-30 -10 10 20 50

Sample Output 1

40

He should move and light candles as follows:

Move from coordinate 0 to -10.

Light the second candle from the left.

Move from coordinate -10 to 10.

Light the third candle from the left.

Move from coordinate 10 to 20.

Light the fourth candle from the left.

Sample Input 2

3 2
10 20 30

Sample Output 2

20

Sample Input 3

1 1
0

Sample Output 3

0

There may be a candle placed at coordinate 0.

Sample Input 4

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

Sample Output 4

10


{-#LANGUAGE FlexibleContexts#-}
import Control.Monad
import Control.Monad.State
import Control.Monad.Reader
import Control.Arrow
-- import Control.Comonad
import Data.Maybe
import Data.List
import Data.Bool
import Data.Fixed
import Data.Tuple
import Data.Ratio
import Data.Bits
import qualified Data.Map.Strict as M
import qualified Data.Array.IO as IA
import qualified Data.Vector as V

getI = read <$> getLine :: IO Int
getIs = map read . words <$> getLine :: IO [Int]
getD = read <$> getLine :: IO Double
getDs = map read . words <$> getLine :: IO [Double]
getInt = read <$> getLine :: IO Integer
getInts = map read . words <$> getLine :: IO [Integer]

type Row = Integer
type Col = Integer
type PointI = (Integer, Integer)
type Point = (Int, Int)

mmm = 1000000007
fact n
    | n < 1 = 1
    | True = foldr1 (*) [1..n]
ti = toInteger
fi = fromInteger
fig = fromIntegral
rf = realToFrac

(.<.) :: Integer -> Integer -> Integer
(.<.) f g -- combination
    | g < 1 || f < 1 || f < g = 1
    | True = foldr1 (*) (take (fi g) [f,f-1..]) `div` fact g
(.>.) f g --combination with repetition
    | g < 1 || f < 1 = 1
    | True = fact (f + g - 1) `div` (fact (f - 1) * fact g)
permutation n x
    | n < x || x < 0 = 0
    | True = foldr1 (*) . take x $ [n,n-1..1]

comb = (.<.)
combWp = (.>.)

unique a = unique_ (reverse . sort $ a) [] Nothing
    where
        unique_ [] arr _ = arr
        unique_ (x:xs) arr n
            | n == Just x = unique_ xs arr n
            | otherwise = unique_ xs (x:arr) $ Just x

zeroume keta num
    | (length . show $ num) > keta = show num
    | otherwise = do
        let zeros = take keta $ repeat '0'
        reverse . take keta $ (reverse . show $ num) ++ zeros

i2b num
    | num < 2 = show num
    | otherwise = i2b_ num []
        where
            i2b_ num str
                | num == 0 = str
                | num == 1 = '1':str
                | otherwise = do
                    let next = num `div` 2
                    let this = if odd num then '1' else '0'
                    i2b_ next (this:str)

mapIncr = mapPlus 1
mapPlus n Nothing = Just n
mapPlus n a = (+) n <$> a

countIf f = length . filter f

enumDivisor :: Int -> [Int]
enumDivisor n = do
    let sqrted = floor $ sqrt (fromIntegral n)
        smaller = filter (\x -> mod n x == 0) [1..sqrted]
        bigger = reverse $ map (div n) smaller
    if head bigger == sqrted then smaller ++ (init bigger)
    else smaller ++ bigger

--
--
--

main = do
    [_,n] <- getIs
    candles <- getIs
    putStrLn . show $ findMin candles n

findMin candles n = do
    let (neg, pos) = span (flip (<) 0) candles
    _findMin (reverse $ map abs neg) pos n
_findMin neg pos n
    | length pos < length neg = _findMin pos neg n
    | neg == []  = pos !! (n - 1)
    | length pos >= n = evalState calc (pos !! (n - 1), neg, reverse $ take (n - 1) pos)
    | True = do
        let (taken, remain) = splitAt (n - length pos) neg
            lastn = last taken
            lastp = last pos
            m = min (lastn * 2 + lastp) (lastp * 2 + lastn)
        evalState calc (m , remain, reverse $ init pos)
calc = get >>= _calc
    where
        _calc (m, [], _) = return m
        _calc (m, (neg:negs), []) = return $ min m neg
        _calc (m, (neg:negs), (pos:poss)) = put (minimum [m, (pos*2+neg), (neg*2+pos)], negs, poss) >> calc


{-
  This code was written after reading the editorial.
-}

import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad.Primitive
import Data.Function
import Data.List
import Data.Maybe
import Control.Monad
import Control.Monad.ST
import Data.Bits
import Debug.Trace

solve :: Int -> [Int] -> Int
solve n as = binsch 1 (10^9 + 1)
  where
    binsch xMin xMax | xMin + 1 == xMax = xMin
                     | try mid n as     = binsch mid xMax
                     | otherwise        = binsch xMin mid
      where mid = (xMax + xMin) `div` 2

try :: Int -> Int -> [Int] -> Bool
try x n as =
  t >= ((n * (n+1) `div` 2) + 1) `div` 2
  where
    t :: Int
    t = numIncr n ss
    ss :: [Int]
    ss = scanl' (+) 0 $ map (\a -> if a >= x then 1 else -1) $ as

numIncr :: Int -> [Int] -> Int
numIncr n ss = runST $ do
  v <- VUM.replicate (2*n+2) 0
  liftM sum $ forM ss $ \s -> do
    let i = s + (n+1)
    bit_add v (2*n + 1) i 1
    (+ (-1)) <$> bit_intv v i

{--
  bit_add v n i x ... a_i += x
--}
bit_add :: VUM.MVector s Int -> Int -> Int -> Int -> ST s ()
bit_add v n i x = forM_ (unfoldr f i) $ VUM.modify v (+ x)
  where f j | j > n = Nothing
            | otherwise = Just (j, j + (j .&. (-j)))

{--
  bit_intv v i    ... \Sum_{j=1}^{i} a_i
--}
bit_intv :: VUM.MVector s Int -> Int -> ST s Int
bit_intv v i = sum <$> (forM (unfoldr f i) $ VUM.read v)
  where f j | j == 0    = Nothing
            | otherwise = Just (j, j - (j .&. (-j)))

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

tmain :: B.ByteString -> Int
tmain cont =
  let n : as = bsReadInts cont
  in solve n as

main = putStrLn . show . tmain =<< B.getContents

Score : 700 points

Problem Statement

We will define the median of a sequence b of length M, as follows:

Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.

For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.

Snuke comes up with the following problem.

You are given a sequence a of length N.
For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a.
We will list m_{l, r} for all pairs (l, r) to create a new sequence m.
Find the median of m.

Constraints

1 \leq N \leq 10^5

a_i is an integer.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the median of m.

Sample Input 1

3
10 30 20

Sample Output 1

30

The median of each contiguous subsequence of a is as follows:

The median of (10) is 10.

The median of (30) is 30.

The median of (20) is 20.

The median of (10, 30) is 30.

The median of (30, 20) is 30.

The median of (10, 30, 20) is 20.

Thus, m = (10, 30, 20, 30, 30, 20) and the median of m is 30.

Sample Input 2

1
10

Sample Output 2

10

Sample Input 3

10
5 9 5 9 8 9 3 5 4 3

Sample Output 3

8


{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE TypeFamilies #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Monad.Primitive
import Data.List
import Data.Maybe
import Data.Bits
import qualified Data.ByteString.Char8 as BS
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import qualified Data.IntMap as IM

readIntBS = fst . fromJust . BS.readInt

main :: IO ()
main = do
  n <- readLn :: IO Int
  as <- map readIntBS . BS.words <$> BS.getLine :: IO [Int]

  fen <- newFenwickTree (2*n+1) 0 (+) :: IO (IOUFenwickTree Int)

  let
    m = n*(n+1)`div`2
    solve l r
      | l == r = return l
      | l+1 == r = aux r >>= \a -> return $ if a then r else l
      | otherwise = do
          a <- aux $ (l+r)`div`2
          if a then
            solve ((l+r)`div`2) r
            else
            solve l ((l+r)`div`2)
        where
          aux x = do
            let
              as' = map (+(n+1)) . scanl (+) 0 $ map (\a -> if a >= x then 1 else -1) as :: [Int]

            (\(tree,_,_,_) -> forM_ [1..2*n+1] $ \i -> VUM.unsafeWrite tree i 0) fen
            y <- sum <$> (forM as' $ \a -> queryFenwickTree fen a >>= \q -> modifyFenwickTree fen a (+1) >> return q)
            return $ y >= m`div`2

  print =<< solve (minimum as) (maximum as)

type MFenwickTree v s a = (v s a, a, (a -> a -> a), Int) -- (フェニック木, 単位元, 二項演算)
type STFenwickTree s a = MFenwickTree VM.MVector s a
type IOFenwickTree a = STFenwickTree RealWorld a
type STUFenwickTree s a = MFenwickTree VUM.MVector s a
type IOUFenwickTree a = STUFenwickTree RealWorld a

newFenwickTree :: (Applicative m, PrimMonad m, VGM.MVector v a) => Int -> a -> (a -> a -> a) -> m (MFenwickTree v (PrimState m) a)
newFenwickTree n e f = (,e,f,n) <$> VGM.replicate (n+1) e

modifyFenwickTree :: (Applicative m, PrimMonad m, VGM.MVector v a) => MFenwickTree v (PrimState m) a -> Int -> (a -> a) -> m ()
modifyFenwickTree (tree,e,f,size) i g = do
  aux i
  where
    aux j = do
      when (j <= size) $ do
        VGM.unsafeWrite tree j =<< g <$> VGM.unsafeRead tree j
        aux (j + (j .&. (-j)))

queryFenwickTree :: (Applicative m, PrimMonad m, VGM.MVector v a) => MFenwickTree v (PrimState m) a -> Int -> m a
queryFenwickTree (tree,e,f,size) i = do
  aux i
  where
    aux j
      | j <= 0 = return e
      | otherwise = f <$> VGM.unsafeRead tree j <*> aux (j - (j .&. (-j)))

lowerBoundFenwickTree :: (Num a, Ord a, Eq a, Applicative m, PrimMonad m, VGM.MVector v a) => MFenwickTree v (PrimState m) a -> a -> m Int
lowerBoundFenwickTree (tree,e,f,size) x = do
  aux k 0 x
  where
    k = (2 ^ (floor $ logBase 2 (fromIntegral size)))
    aux i j w
      | i == 0 = return (j+1)
      | otherwise = do
          if i+j <= size then do
            a <- VGM.unsafeRead tree (i+j)
            if a < w then aux (i `div` 2) (i+j) (w-a) else aux (i `div` 2) j w
            else
            aux (i `div` 2) j w


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

Score: 100 points

Problem Statement

There is a farm whose length and width are A yard and B yard, respectively. A farmer, John, made a vertical road and a horizontal road inside the farm from one border to another, as shown below: (The gray part represents the roads.)

What is the area of this yard excluding the roads? Find it.

Note

It can be proved that the positions of the roads do not affect the area.

Constraints

A is an integer between 2 and 100 (inclusive).

B is an integer between 2 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

A B

Output

Print the area of this yard excluding the roads (in square yards).

Sample Input 1

2 2

Sample Output 1

1

In this case, the area is 1 square yard.

Sample Input 2

5 7

Sample Output 2

24

In this case, the area is 24 square yards.


import Data.List

main :: IO ()
main = do
  n <- getInt
  print $ countIf ((== 8) . length . divisors) [1,3..n]

divisors :: Int -> [Int]
divisors n = [x | x <- [1..n], n `rem` x == 0]

getInt :: IO Int
getInt = read <$> getLine

countIf :: (a -> Bool) -> [a] -> Int
countIf f = length . filter f

Score: 200 points

Problem Statement

The number 105 is quite special - it is odd but still it has eight divisors.
Now, your task is this: how many odd numbers with exactly eight positive divisors are there between 1 and N (inclusive)?

Constraints

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

Input

Input is given from Standard Input in the following format:

N

Output

Print the count.

Sample Input 1

105

Sample Output 1

1

Among the numbers between 1 and 105, the only number that is odd and has exactly eight divisors is 105.

Sample Input 2

7

Sample Output 2

0

1 has one divisor. 3, 5 and 7 are all prime and have two divisors. Thus, there is no number that satisfies the condition.


import Control.Applicative
import Data.List

main = do
    n <- readLn
    putStrLn $ show (solve n)

factors :: Int -> [Int]
factors n = [x | x <- [1..n], n `mod` x == 0]

factorization :: Int -> [Int]
factorization 1 = []
factorization x = v : factorization (x `div` v)
    where
        v = (factors x) !! 1

ndivider :: Int -> Int
ndivider n = foldl (\acc x -> acc * (length x + 1)) 1 (group $ factorization n)

solve :: Int -> Int
solve n = length([x | x <- [1..n], x `mod` 2 == 1, ndivider x == 8])


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

getKthNumber :: String -> Int -> Int
getKthNumber s k
  | nk <= 0 = n
  | otherwise = getKthNumber ns nk
      where
        n = toInt $ take 1 s
        ns = tail s
        nk
          | n == 1 = k - 1
          | otherwise = k - n * 5000000000000000

main = do
  s <- getLine
  k <- toInt <$> getLine
  putStrLn $ show $ getKthNumber s k

Score: 300 points

Problem Statement

Mr. Infinity has a string S consisting of digits from 1 to 9. Each time the date changes, this string changes as follows:

Each occurrence of 2 in S is replaced with 22. Similarly, each 3 becomes 333, 4 becomes 4444, 5 becomes 55555, 6 becomes 666666, 7 becomes 7777777, 8 becomes 88888888 and 9 becomes 999999999. 1 remains as 1.

For example, if S is 1324, it becomes 1333224444 the next day, and it becomes 133333333322224444444444444444 the day after next.
You are interested in what the string looks like after 5 \times 10^{15} days. What is the K-th character from the left in the string after 5 \times 10^{15} days?

Constraints

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

K is an integer between 1 and 10^{18} (inclusive).

The length of the string after 5 \times 10^{15} days is at least K.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the K-th character from the left in Mr. Infinity's string after 5 \times 10^{15} days.

Sample Input 1

1214
4

Sample Output 1

2

The string S changes as follows:

Now: 1214

After one day: 12214444

After two days: 1222214444444444444444

After three days: 12222222214444444444444444444444444444444444444444444444444444444444444444

The first five characters in the string after 5 \times 10^{15} days is 12222. As K=4, we should print the fourth character, 2.

Sample Input 2

3
157

Sample Output 2

3

The initial string is 3. The string after 5 \times 10^{15} days consists only of 3.

Sample Input 3

299792458
9460730472580800

Sample Output 3

2


import Debug.Trace

solve :: [Int] -> Int -> Int
solve (h:t) x
    | x == 1 = h
    | h == 1 = solve t (x-1)
    | otherwise = h

main :: IO ()
main = do
    s <- map (\x -> read [x]) <$> getLine
    x <- read <$> getLine
    print (solve s x)


import Control.Monad
import Data.Array

main = do
  l <- getLine
  let [n,m,q] = map read $ words l
  lrs <- getpairs m
  pqs <- getpairs q
  let lra = prepare n lrs
  mapM (print . compute lra) pqs

getpairs :: Int -> IO [(Int,Int)]
getpairs n = forM [1..n] $ \_ -> do
  l <- getLine
  let [a,b] = map read $ words l
  return (a,b)

prepare n lrs = accumArray (+) 0 ((1,1),(n,n)) $ map (\lr -> (lr,1)) lrs

compute lra (p,q) = sum $ elems $ ixmap ((p,p),(q,q)) id lra

Score: 400 points

Problem Statement

In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east.
A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i).
Takahashi the king is interested in the following Q matters:

The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.

Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.

Constraints

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

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

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

1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)

1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q

Output

Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.

Sample Input 1

2 3 1
1 1
1 2
2 2
1 2

Sample Output 1

3

As all the trains runs within the section from City 1 to City 2, the answer to the only query is 3.

Sample Input 2

10 3 2
1 5
2 8
7 10
1 7
3 10

Sample Output 2

1
1

The first query is on the section from City 1 to 7. There is only one train that runs strictly within that section: Train 1.
The second query is on the section from City 3 to 10. There is only one train that runs strictly within that section: Train 3.

Sample Input 3

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

Sample Output 3

7
9
10
6
8
9
6
7
8
10


import Control.Applicative

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

solve :: Int -> Int -> String
solve a b = if mod a b == 0 then "0" else "1"

Score : 100 points

Problem Statement

Takahashi has decided to distribute N AtCoder Crackers to K users of as evenly as possible.
When all the crackers are distributed, find the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Constraints

1 \leq N,K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Sample Input 1

7 3

Sample Output 1

1

When the users receive two, two and three crackers, respectively, the (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user, is 1.

Sample Input 2

100 10

Sample Output 2

0

The crackers can be distributed evenly.

Sample Input 3

1 1

Sample Output 3

0


main::IO ()
main = do
    [a,b] <- map read . words <$> getLine
    print $ if mod a b == 0 then 0 else 1


main=do
 [a,b]<-map read.words<$>getLine
 print$if(mod a b)==0 then 0 else 1


import Control.Applicative ((<$>))

fi = fromIntegral

main :: IO ()
main = do
  [n,k] <- map read . words <$> getLine :: IO [Int]
  print $ if min (ceiling (fi n/fi k)*k-n) (n-(n`div`k)*k) > 0
    then 1
    else 0


import Debug.Trace

main :: IO ()
main = do
    n <- read <$> getLine
    let num = length $ filter (\(a, b) -> a * 4 + b * 7 == n) [(a, b) | a <- [0..n], b <- [0..n]]
    putStrLn (if num == 0 then "No" else "Yes")

Score : 200 points

Problem Statement

La Confiserie d'ABC sells cakes at 4 dollars each and doughnuts at 7 dollars each.
Determine if there is a way to buy some of them for exactly N dollars. You can buy two or more doughnuts and two or more cakes, and you can also choose to buy zero doughnuts or zero cakes.

Constraints

N is an integer between 1 and 100, inclusive.

Input

Input is given from Standard Input in the following format:

N

Output

If there is a way to buy some cakes and some doughnuts for exactly N dollars, print Yes; otherwise, print No.

Sample Input 1

11

Sample Output 1

Yes

If you buy one cake and one doughnut, the total will be 4 + 7 = 11 dollars.

Sample Input 2

40

Sample Output 2

Yes

If you buy ten cakes, the total will be 4 \times 10 = 40 dollars.

Sample Input 3

3

Sample Output 3

No

The prices of cakes (4 dollars) and doughnuts (7 dollars) are both higher than 3 dollars, so there is no such way.


import Data.List
import Data.Array
import Data.Array.IO
import Data.Maybe
import Data.Bits
import Control.Monad
import Control.Applicative

modifyArray arr i f = readArray arr i >>= \x -> writeArray arr i (f x)

listToTuple2 (a:b:_) = (a,b)
listToTuple3 (a:b:c:_) = (a,b,c)
listToTuple4 (a:b:c:d:_) = (a,b,c,d)

main :: IO ()
main = do
  n <- readLn :: IO Int
  putStrLn $ if or $ map (\x -> n-x >= 0 && mod (n-x) 4 == 0) (takeWhile (<=100) $ [0,7..]) then "Yes" else "No"

  return ()


import Control.Monad
import Data.List

main=do
    n<-readLn::IO Int
    putStrLn $ if null [1|x<-[0..25],y<-[0..14], x*4+y*7==n] then "No" else "Yes"


solve :: Int -> String
solve x
  | x < 1200 = "ABC"
  | x < 2800 = "ARC"
  | otherwise = "AGC"

main :: IO ()
main = do
  x <-  getLine
  let r = read x :: Int
  putStrLn $ solve r

Score : 100 points

Problem Statement

A programming competition site AtCode regularly holds programming contests.

The next contest on AtCode is called ABC, which is rated for contestants with ratings less than 1200.

The contest after the ABC is called ARC, which is rated for contestants with ratings less than 2800.

The contest after the ARC is called AGC, which is rated for all contestants.

Takahashi's rating on AtCode is R. What is the next contest rated for him?

Constraints

0 ≤ R ≤ 4208

R is an integer.

Input

Input is given from Standard Input in the following format:

R

Output

Print the name of the next contest rated for Takahashi (ABC, ARC or AGC).

Sample Input 1

1199

Sample Output 1

ABC

1199 is less than 1200, so ABC will be rated.

Sample Input 2

1200

Sample Output 2

ARC

1200 is not less than 1200 and ABC will be unrated, but it is less than 2800 and ARC will be rated.

Sample Input 3

4208

Sample Output 3

AGC


main = do
  (c1:c2:cs) <- getLine
  if (c1 /= 'A' || c2 <= 'Z' || filter (<= 'Z') (init cs) /= "C" || last cs <= 'Z') then putStrLn "WA"
  else putStrLn "AC"

Score : 200 points

Problem Statement

You are given a string S. Each character of S is uppercase or lowercase English letter.
Determine if S satisfies all of the following conditions:

The initial character of S is an uppercase A.

There is exactly one occurrence of C between the third character from the beginning and the second to last character (inclusive).

All letters except the A and C mentioned above are lowercase.

Constraints

4 ≤ |S| ≤ 10 (|S| is the length of the string S.)

Each character of S is uppercase or lowercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

If S satisfies all of the conditions in the problem statement, print AC; otherwise, print WA.

Sample Input 1

AtCoder

Sample Output 1

AC

The first letter is A, the third letter is C and the remaining letters are all lowercase, so all the conditions are satisfied.

Sample Input 2

ACoder

Sample Output 2

WA

The second letter should not be C.

Sample Input 3

AcycliC

Sample Output 3

WA

The last letter should not be C, either.

Sample Input 4

AtCoCo

Sample Output 4

WA

There should not be two or more occurrences of C.

Sample Input 5

Atcoder

Sample Output 5

WA

The number of C should not be zero, either.


import Data.Char(isUpper)

main = do
    s <- getLine
    if accept s then putStrLn "AC"
                else putStrLn "WA"

accept :: String -> Bool
accept (s:xs) = s == 'A' && filter isUpper xs == "C" && (findC $ take (length xs-2) (tail xs))

findC :: String -> Bool
findC [] = False
findC (x:xs)
    | x == 'C'  = True
    | otherwise = findC xs


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

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

main = do
    [d,g] <- getIntList
    pc <- fmap (zip [1..]) $ replicateM d $ do
        [p,c] <- getIntList
        return (p,c)
    let tfs = sequence $ replicate d [True,False]
    let solve tf = ans
            where solve' tf = foldl' (\(a,b) (a',b') -> (a+a',b+b')) (0,0) $ zipWith f pc tf
                      where f (i,(p,c)) True = (p, i*100*p + c)
                            f _ False = (0,0)
                  (probs,score) = solve' tf
                  m = g - score
                  ans | m <= 0 = (probs,score)
                      | otherwise = (probs+p',score+s')
                              where (i',(pi',_)) = fst . last . filter (not . snd) $ zip pc tf
                                    p' = min pi' $ (m - 1) `div` (i' * 100) + 1
                                    s' = i' * 100 * p'
    let anss = map solve tfs
    print . minimum . map fst $ filter ((g<=) . snd) anss

Score : 300 points

Problem Statement

A programming competition site AtCode provides algorithmic problems.
Each problem is allocated a score based on its difficulty.
Currently, for each integer i between 1 and D (inclusive), there are p_i problems with a score of 100i points.
These p_1 + … + p_D problems are all of the problems available on AtCode.

A user of AtCode has a value called total score.
The total score of a user is the sum of the following two elements:

Base score: the sum of the scores of all problems solved by the user.

Perfect bonuses: when a user solves all problems with a score of 100i points, he/she earns the perfect bonus of c_i points, aside from the base score (1 ≤ i ≤ D).

Takahashi, who is the new user of AtCode, has not solved any problem.
His objective is to have a total score of G or more points.
At least how many problems does he need to solve for this objective?

Constraints

1 ≤ D ≤ 10

1 ≤ p_i ≤ 100

100 ≤ c_i ≤ 10^6

100 ≤ G

All values in input are integers.

c_i and G are all multiples of 100.

It is possible to have a total score of G or more points.

Input

Input is given from Standard Input in the following format:

D G
p_1 c_1
:
p_D c_D

Output

Print the minimum number of problems that needs to be solved in order to have a total score of G or more points. Note that this objective is always achievable (see Constraints).

Sample Input 1

2 700
3 500
5 800

Sample Output 1

3

In this case, there are three problems each with 100 points and five problems each with 200 points. The perfect bonus for solving all the 100-point problems is 500 points, and the perfect bonus for solving all the 200-point problems is 800 points. Takahashi's objective is to have a total score of 700 points or more.

One way to achieve this objective is to solve four 200-point problems and earn a base score of 800 points. However, if we solve three 100-point problems, we can earn the perfect bonus of 500 points in addition to the base score of 300 points, for a total score of 800 points, and we can achieve the objective with fewer problems.

Sample Input 2

2 2000
3 500
5 800

Sample Output 2

7

This case is similar to Sample Input 1, but the Takahashi's objective this time is 2000 points or more. In this case, we inevitably need to solve all five 200-point problems, and by solving two 100-point problems additionally we have the total score of 2000 points.

Sample Input 3

2 400
3 500
5 800

Sample Output 3

2

This case is again similar to Sample Input 1, but the Takahashi's objective this time is 400 points or more. In this case, we only need to solve two 200-point problems to achieve the objective.

Sample Input 4

5 25000
20 1000
40 1000
50 1000
30 1000
1 1000

Sample Output 4

66

There is only one 500-point problem, but the perfect bonus can be earned even in such a case.


module Main where

import Data.List (subsequences)

main :: IO ()
main = interact $ show . f . readABCs . head . lines

data ABC
  = A
  | B
  | C
  deriving (Show, Eq)

f :: [[ABC]] -> Int
-- f xss = length . (filter ([A, B, C] ==)) $ subsequences =<< xss
f xss = length . (filter ([A, B, C] ==)) $ combinations 3 =<< xss

readABCs :: String -> [[ABC]]
readABCs "" = [[]]
readABCs ('A' : cs) = map (A:) $ readABCs cs
readABCs ('B' : cs) = map (B:) $ readABCs cs
readABCs ('C' : cs) = map (C:) $ readABCs cs
readABCs ('?' : cs) = (:) <$> [A, B, C] <*> readABCs cs
readABCs _ = error "readABCs: parse error"

tests :: [Bool]
tests = [test1, test2]

test1, test2 :: Bool
test1 = f (readABCs "A??C") == 8
test2 = f (readABCs "ABCBC") == 3
test3 = f (readABCs "????C?????B??????A???????") == 979596887

combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [[]]
combinations _ [] = []
combinations m xxs@(x : xs) = map (x:) (combinations (m - 1) xs) ++ combinations m xs

Score : 400 points

Problem Statement

The ABC number of a string T is the number of triples of integers (i, j, k) that satisfy all of the following conditions:

1 ≤ i < j < k ≤ |T| (|T| is the length of T.)

T_i = A (T_i is the i-th character of T from the beginning.)

T_j = B

T_k = C

For example, when T = ABCBC, there are three triples of integers (i, j, k) that satisfy the conditions: (1, 2, 3), (1, 2, 5), (1, 4, 5). Thus, the ABC number of T is 3.

You are given a string S. Each character of S is A, B, C or ?.

Let Q be the number of occurrences of ? in S. We can make 3^Q strings by replacing each occurrence of ? in S with A, B or C. Find the sum of the ABC numbers of all these strings.

This sum can be extremely large, so print the sum modulo 10^9 + 7.

Constraints

3 ≤ |S| ≤ 10^5

Each character of S is A, B, C or ?.

Input

Input is given from Standard Input in the following format:

S

Output

Print the sum of the ABC numbers of all the 3^Q strings, modulo 10^9 + 7.

Sample Input 1

A??C

Sample Output 1

8

In this case, Q = 2, and we can make 3^Q = 9 strings by by replacing each occurrence of ? with A, B or C. The ABC number of each of these strings is as follows:

AAAC: 0

AABC: 2

AACC: 0

ABAC: 1

ABBC: 2

ABCC: 2

ACAC: 0

ACBC: 1

ACCC: 0

The sum of these is 0 + 2 + 0 + 1 + 2 + 2 + 0 + 1 + 0 = 8, so we print 8 modulo 10^9 + 7, that is, 8.

Sample Input 2

ABCBC

Sample Output 2

3

When Q = 0, we print the ABC number of S itself, modulo 10^9 + 7. This string is the same as the one given as an example in the problem statement, and its ABC number is 3.

Sample Input 3

????C?????B??????A???????

Sample Output 3

979596887

In this case, the sum of the ABC numbers of all the 3^Q strings is 2291979612924, and we should print this number modulo 10^9 + 7, that is, 979596887.


import Data.List
main=interact $ show.f.sort.map read.words
f x = (last x)-(head x)

Score : 100 points

Problem Statement

You have three tasks, all of which need to be completed.

First, you can complete any one task at cost 0.

Then, just after completing the i-th task, you can complete the j-th task at cost |A_j - A_i|.

Here, |x| denotes the absolute value of x.

Find the minimum total cost required to complete all the task.

Constraints

All values in input are integers.

1 \leq A_1, A_2, A_3 \leq 100

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

Print the minimum total cost required to complete all the task.

Sample Input 1

1 6 3

Sample Output 1

5

When the tasks are completed in the following order, the total cost will be 5, which is the minimum:

Complete the first task at cost 0.

Complete the third task at cost 2.

Complete the second task at cost 3.

Sample Input 2

11 5 5

Sample Output 2

6

Sample Input 3

100 100 100

Sample Output 3

0


main = do
    [a,b,c] <- map read . words <$> getLine
    let list = map abs [a - b, b - c, c - a]
    print $ sum list  - maximum list


import Data.List (mapAccumL)
main = do
    (x:xs) <- map read . words <$> getLine
    print . sum . snd . mapAccumL (\a c -> (c, abs (a - c))) x $ xs


import qualified Data.ByteString.Char8 as BS

readString = map BS.unpack . BS.words

getString = readString <$> BS.getLine

calc :: String -> String ->Int -> String
calc ss ts 1 | ss == ts = "Yes"
             | otherwise = "No"
calc ss ts n | ss == ts = "Yes"
             | otherwise = calc (last ss : init ss) ts (n-1)

main = do
  [ss] <- getString
  [ts] <- getString
  let ssl = length(ss)
  putStrLn $ calc ss ts ssl

Score : 200 points

Problem Statement

You are given string S and T consisting of lowercase English letters.

Determine if S equals T after rotation.

That is, determine if S equals T after the following operation is performed some number of times:

Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}.

Here, |X| denotes the length of the string X.

Constraints

2 \leq |S| \leq 100

|S| = |T|

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S equals T after rotation, print Yes; if it does not, print No.

Sample Input 1

kyoto
tokyo

Sample Output 1

Yes

In the first operation, kyoto becomes okyot.

In the second operation, okyot becomes tokyo.

Sample Input 2

abc
arc

Sample Output 2

No

abc does not equal arc after any number of operations.

Sample Input 3

aaaaaaaaaaaaaaab
aaaaaaaaaaaaaaab

Sample Output 3

Yes


main = do
    _ <- getLine
    a <- map read . words <$> getLine :: IO [Int]
    let m = pred $ foldr1 lcm a
     in print . sum $ map (m `mod`) a

Score : 300 points

Problem Statement

You are given N positive integers a_1, a_2, ..., a_N.

For a non-negative integer m, let f(m) = (m\ mod\ a_1) + (m\ mod\ a_2) + ... + (m\ mod\ a_N).

Here, X\ mod\ Y denotes the remainder of the division of X by Y.

Find the maximum value of f.

Constraints

All values in input are integers.

2 \leq N \leq 3000

2 \leq a_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the maximum value of f.

Sample Input 1

3
3 4 6

Sample Output 1

10

f(11) = (11\ mod\ 3) + (11\ mod\ 4) + (11\ mod\ 6) = 10 is the maximum value of f.

Sample Input 2

5
7 46 11 20 11

Sample Output 2

90

Sample Input 3

7
994 518 941 851 647 2 581

Sample Output 3

4527


import Data.List
main=do
    n<-readLn::IO Int
    as<-map read.words<$>getLine::IO[Int]
    print $ maximum $ take 1000 $ map (f as) [fl as-1000..]

f as m = sum $ map (\a-> m`mod`a) as
fl as = foldl1 lcm as


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

readInts = map (fst . fromJust . BC.readInt) . BC.words <$> BC.getLine

main :: IO ()
main = do
  n <- readLn
  --qs <- replicateM n $ fmap (map read . words) getLine :: IO [[Integer]]
  qs <- replicateM n readInts :: IO [[Int]]
  let ans = map solve qs
  seq ans $ mapM_ (\x -> putStrLn $ if x then "Yes" else "No") ans

solve :: [Int] -> Bool
solve as
  | a < b || b > d = False
  | b == d = a `mod` b <= c
  | c >= b = True
  | otherwise = ow
  where
    (a:b:c:d:_) = as
    gcdbd = gcd b d
    --ow = all (\x -> (x + if x <= c then d else 0) >= b) $ [(a + x * gcdbd) `mod` b| x <- [0..(div b gcdbd)]]
    ow = b - gcdbd + a `mod` gcdbd <= c

Score : 600 points

Problem Statement

Ringo Mart, a convenience store, sells apple juice.

On the opening day of Ringo Mart, there were A cans of juice in stock in the morning.
Snuke buys B cans of juice here every day in the daytime.
Then, the manager checks the number of cans of juice remaining in stock every night.
If there are C or less cans, D new cans will be added to the stock by the next morning.

Determine if Snuke can buy juice indefinitely, that is, there is always B or more cans of juice in stock when he attempts to buy them.
Nobody besides Snuke buy juice at this store.

Note that each test case in this problem consists of T queries.

Constraints

1 \leq T \leq 300

1 \leq A, B, C, D \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

T
A_1 B_1 C_1 D_1
A_2 B_2 C_2 D_2
:
A_T B_T C_T D_T

In the i-th query, A = A_i, B = B_i, C = C_i, D = D_i.

Output

Print T lines. The i-th line should contain Yes if Snuke can buy apple juice indefinitely in the i-th query; No otherwise.

Sample Input 1

14
9 7 5 9
9 7 6 9
14 10 7 12
14 10 8 12
14 10 9 12
14 10 7 11
14 10 8 11
14 10 9 11
9 10 5 10
10 10 5 10
11 10 5 10
16 10 5 10
1000000000000000000 17 14 999999999999999985
1000000000000000000 17 15 999999999999999985

Sample Output 1

No
Yes
No
Yes
Yes
No
No
Yes
No
Yes
Yes
No
No
Yes

In the first query, the number of cans of juice in stock changes as follows: (D represents daytime and N represents night.)

9
→D 2
→N 11
→D 4
→N 13
→D 6
→N 6
→D x

In the second query, the number of cans of juice in stock changes as follows:

9
→D 2
→N 11
→D 4
→N 13
→D 6
→N 15
→D 8
→N 8
→D 1
→N 10
→D 3
→N 12
→D 5
→N 14
→D 7
→N 7
→D 0
→N 9
→D 2
→N 11
→D …

and so on, thus Snuke can buy juice indefinitely.

Sample Input 2

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

Sample Output 2

No
No
No
No
No
No
Yes
Yes
No
No
No
No
Yes
Yes
Yes
No
No
No
Yes
Yes
Yes
No
No
No


main = do
	[a,b] <- map read . words <$> getLine :: IO [Int]
	putStrLn $
		if a+b == 15 then "+"
		else if a*b == 15 then "*"
		else "x"

Score : 100 points

Problem Statement

You are given two integers a and b.
Determine if a+b=15 or a\times b=15 or neither holds.

Note that a+b=15 and a\times b=15 do not hold at the same time.

Constraints

1 \leq a,b \leq 15

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

If a+b=15, print +;
if a\times b=15, print *;
if neither holds, print x.

Sample Input 1

4 11

Sample Output 1

+

4+11=15.

Sample Input 2

3 5

Sample Output 2

*

3\times 5=15.

Sample Input 3

1 1

Sample Output 3

x

1+1=2 and 1\times 1=1, neither of which is 15.


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

solve :: [Int] -> Double
solve [n, m, d] = fromIntegral (m - 1) * avg
  where
    avg = (if d==0 then 1.0 else 2.0) * (1.0 - fromIntegral d / fromIntegral n) / fromIntegral n

main = map read . words <$> getLine >>= putStrLn . printf "%.15f" . solve

Score : 300 points

Problem Statement

Let us define the beauty of a sequence (a_1,... ,a_n) as the number of pairs of two adjacent elements in it whose absolute differences are d.
For example, when d=1, the beauty of the sequence (3, 2, 3, 10, 9) is 3.

There are a total of n^m sequences of length m where each element is an integer between 1 and n (inclusive).
Find the beauty of each of these n^m sequences, and print the average of those values.

Constraints

0 \leq d < n \leq 10^9

2 \leq m \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n m d

Output

Print the average of the beauties of the sequences of length m where each element is an integer between 1 and n.
The output will be judged correct if the absolute or relative error is at most 10^{-6}.

Sample Input 1

2 3 1

Sample Output 1

1.0000000000

The beauty of (1,1,1) is 0.

The beauty of (1,1,2) is 1.

The beauty of (1,2,1) is 2.

The beauty of (1,2,2) is 1.

The beauty of (2,1,1) is 1.

The beauty of (2,1,2) is 2.

The beauty of (2,2,1) is 1.

The beauty of (2,2,2) is 0.

The answer is the average of these values: (0+1+2+1+1+2+1+0)/8=1.

Sample Input 2

1000000000 180707 0

Sample Output 2

0.0001807060


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

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

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

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

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

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

data PQueue a = PQueue !Int !(VUM.IOVector a)

new :: VUM.Unbox a => Int -> PQueue a
new !s = PQueue 0 $ accursedUnutterablePerformIO $ VUM.new (s + 1)

push :: (Ord a, Bounded a) => VUM.Unbox a => a -> PQueue a -> PQueue a
push !a !(PQueue k vec) = PQueue (k + 1) vec'
 where
  vec' = up k a $ uwrite k a $ if VUM.length vec <= k
    then accursedUnutterablePerformIO $ VUM.unsafeGrow vec (VUM.length vec * 2)
    else vec

  up !i !cv !vec = (\(_, v) -> v) $ fix
    ( \f (!ci, !vec) ->
      let pi = (ci - 1) `div` 2
          pv = if 0 < ci then uread pi vec else minBound
      in  if 0 < ci && cv < pv
            then let vec' = uswap pi ci vec in vec' `seq` f (pi, vec')
            else (ci, vec)
    )
    (i, vec)

popMin :: (Ord a, Bounded a, VUM.Unbox a) => PQueue a -> Maybe (a, PQueue a)
popMin !(PQueue k vec) | k <= 0    = Nothing
                       | otherwise = Just (uread 0 vec, PQueue (k - 1) vec')
 where
  vec' = let v = uswap (k - 1) 0 vec in v `seq` down 0 (uread 0 vec) v

  down !i !cv !vec = (\(_, v) -> v) $ fix
    ( \f (!ci, !vec) ->
      let li = ci * 2 + 1
          lv = if li < k - 1 then uread li vec else maxBound
          ri = ci * 2 + 2
          rv = if ri < k - 1 then uread ri vec else maxBound
      in  if cv <= lv && cv <= rv
            then (ci, vec)
            else
              let p    = if lv > rv then ri else li
                  vec' = uswap p ci vec
              in  vec' `seq` f (p, vec')
    )
    (i, vec)

popMin' :: (Ord a, Bounded a, VUM.Unbox a) => PQueue a -> (a, PQueue a)
popMin' !pq = maybe (error "size < 0") id $ popMin pq

umodifyV :: Int -> (a -> a) -> VM.IOVector a -> VM.IOVector a
umodifyV !i !f !v = accursedUnutterablePerformIO $ VM.modify v f i >> return v

uthawV :: V.Vector a -> VM.IOVector a
uthawV !v = accursedUnutterablePerformIO $ V.thaw v

ufreezeV :: VM.IOVector a -> V.Vector a
ufreezeV !v = accursedUnutterablePerformIO $ V.freeze v

dijkstra
  :: Int  -- ^ nodes
  -> V.Vector [(Int, Int)]  -- ^ edges from i-th node: (end, cost)
  -> Int  -- ^ start node
  -> Int  -- ^ end node
  -> VU.Vector Int  -- ^ constructed graph
dijkstra !n !edges !s !t = ufreeze $ snd $ fix
  ( \f (!nodes, !costs) -> case popMin nodes of
    Nothing              -> (nodes, costs)
    Just ((c, n), nodes) -> if c <= uread n costs
      then
        let es = edges V.! n
        in  f $ foldl'
              ( \(!ns, !cs) (!e, !ec) ->
                let c' = c + ec
                in  if c' < uread e costs
                      then (push (c', e) ns, uwrite e c' cs)
                      else (ns, cs)
              )
              (nodes, costs)
              es
      else f (nodes, costs)
  )
  (nodes0, costs0)
 where
  costs0 :: VUM.IOVector Int
  costs0 = uwrite s 0 $ uthaw $ VU.replicate n maxBound

  nodes0 :: PQueue (Int, Int)
  nodes0 = push (0, s) $ new 0

solve :: Int -> Int -> Int -> Int -> VU.Vector (Int, Int, Int, Int) -> [Int]
solve !n !m !s !t !trains = map (10 ^ 15 -) $ fst $ foldl'
  (\(!acc, !prev) !i -> (0 : acc, 0))
  ([], 10 ^ 15 :: Int)
  [n - 1, n - 2 .. 0]
 where
  yenGraph = dijkstra
    n
    ( ufreezeV $ VU.foldl'
      (\gr (u, v, a, b) -> umodifyV v ((u, a) :) $ umodifyV u ((v, a) :) $ gr)
      (uthawV $ V.replicate n [])
      trains
    )
    s
    t
  snookGraph = dijkstra
    n
    ( ufreezeV $ VU.foldl'
      (\gr (u, v, a, b) -> umodifyV v ((u, b) :) $ umodifyV u ((v, b) :) $ gr)
      (uthawV $ V.replicate n [])
      trains
    )
    t
    s

  calcCost i = yenGraph VU.! i + snookGraph VU.! i

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

  (n, m, s, t) <-
    (\vec -> (vec VU.! 0, vec VU.! 1, vec VU.! 2 - 1, vec VU.! 3 - 1))
    .   VU.unfoldrN 4 readInt
    <$> B.getLine
  uvab <-
    VU.replicateM m
    $   (\vec -> (vec VU.! 0 - 1, vec VU.! 1 - 1, vec VU.! 2, vec VU.! 3))
    .   VU.unfoldrN 4 readInt
    <$> B.getLine
  mapM_ print $ solve n m s t uvab

Score : 400 points

Problem Statement

Kenkoooo is planning a trip in Republic of Snuke.
In this country, there are n cities and m trains running.
The cities are numbered 1 through n, and the i-th train connects City u_i and v_i bidirectionally.
Any city can be reached from any city by changing trains.

Two currencies are used in the country: yen and snuuk.
Any train fare can be paid by both yen and snuuk.
The fare of the i-th train is a_i yen if paid in yen, and b_i snuuk if paid in snuuk.

In a city with a money exchange office, you can change 1 yen into 1 snuuk.
However, when you do a money exchange, you have to change all your yen into snuuk.
That is, if Kenkoooo does a money exchange when he has X yen, he will then have X snuuk.
Currently, there is a money exchange office in every city, but the office in City i will shut down in i years and can never be used in and after that year.

Kenkoooo is planning to depart City s with 10^{15} yen in his pocket and head for City t, and change his yen into snuuk in some city while traveling.
It is acceptable to do the exchange in City s or City t.

Kenkoooo would like to have as much snuuk as possible when he reaches City t by making the optimal choices for the route to travel and the city to do the exchange.
For each i=0,...,n-1, find the maximum amount of snuuk that Kenkoooo has when he reaches City t if he goes on a trip from City s to City t after i years.
You can assume that the trip finishes within the year.

Constraints

2 \leq n \leq 10^5

1 \leq m \leq 10^5

1 \leq s,t \leq n

s \neq t

1 \leq u_i < v_i \leq n

1 \leq a_i,b_i \leq 10^9

If i\neq j, then u_i \neq u_j or v_i \neq v_j.

Any city can be reached from any city by changing trains.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n m s t
u_1 v_1 a_1 b_1
:
u_m v_m a_m b_m

Output

Print n lines.
In the i-th line, print the maximum amount of snuuk that Kenkoooo has when he reaches City t if he goes on a trip from City s to City t after i-1 years.

Sample Input 1

4 3 2 3
1 4 1 100
1 2 1 10
1 3 20 1

Sample Output 1

999999999999998
999999999999989
999999999999979
999999999999897

After 0 years, it is optimal to do the exchange in City 1.

After 1 years, it is optimal to do the exchange in City 2.

Note that City 1 can still be visited even after the exchange office is closed.
Also note that, if it was allowed to keep 1 yen when do the exchange in City 2 and change the remaining yen into snuuk, we could reach City 3 with 999999999999998 snuuk, but this is NOT allowed.

After 2 years, it is optimal to do the exchange in City 3.

After 3 years, it is optimal to do the exchange in City 4.
Note that the same train can be used multiple times.

Sample Input 2

8 12 3 8
2 8 685087149 857180777
6 7 298270585 209942236
2 4 346080035 234079976
2 5 131857300 22507157
4 8 30723332 173476334
2 6 480845267 448565596
1 4 181424400 548830121
4 5 57429995 195056405
7 8 160277628 479932440
1 6 475692952 203530153
3 5 336869679 160714712
2 7 389775999 199123879

Sample Output 2

999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994


{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}
{-# OPTIONS_GHC -O2 #-}

import Data.Array.IArray
import Data.Array.Unboxed
import Data.Array.ST
import Data.Char
import Data.List
import Data.Int
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Monad.ST

inf :: Int64
inf = 1000000000000000

getInts :: IO [Int]
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

dijkstra :: Array Int [(Int, Int)] -> Int -> [Int64]
dijkstra g source = runST $ do
    ds :: STUArray s Int Int64 <- newArray (1, n) maxBound
    writeArray ds source 0
    let
      step :: S.Set (Int64, Int) -> ST s ()
      step q =
          case S.minView q of
            Nothing -> return ()
            Just ((d, v), q) -> do
              let
                relax q (u, w) = do
                    d <- readArray ds u

                    if d' < d
                      then do
                        writeArray ds u d'
                        return $ S.insert (d', u) q
                      else return q
                  where
                    d' = d + (fromIntegral w)

              foldM relax q (g!v) >>= step

    step $ S.singleton (0, source)

    ds' :: UArray Int Int64 <- freeze ds
    return (elems ds')
  where
    n = snd $ bounds g

main :: IO ()
main = do
	[n, m, s, t] <- getInts
	es <- replicateM m getInts
	let gy = accumArray (flip (:)) [] (1, n) $ concatMap (\[u, v, y, s] -> [(u, (v, y)), (v, (u, y))]) es
	let gs = accumArray (flip (:)) [] (1, n) $ concatMap (\[u, v, y, s] -> [(u, (v, s)), (v, (u, s))]) es
	putStrLn $ unwords $ map show $ map (inf-) $ scanr1 min $ zipWith (+) (dijkstra gy s) (dijkstra gs t)


main=readLn>>=(\n->print$if even n then n else 2*n)

Score : 100 points

Problem Statement

You are given a positive integer N.
Find the minimum positive integer divisible by both 2 and N.

Constraints

1 \leq N \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum positive integer divisible by both 2 and N.

Sample Input 1

3

Sample Output 1

6

6 is divisible by both 2 and 3.
Also, there is no positive integer less than 6 that is divisible by both 2 and 3.
Thus, the answer is 6.

Sample Input 2

10

Sample Output 2

10

Sample Input 3

999999999

Sample Output 3

1999999998


main = do
  _ <- getLine
  as <- map read . words <$> getLine :: IO [Int]
  print $ maximum as - minimum as

Score : 200 points

Problem Statement

You are given an integer sequence A of length N.
Find the maximum absolute difference of two elements (with different indices) in A.

Constraints

2 \leq N \leq 100

1 \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

Print the maximum absolute difference of two elements (with different indices) in A.

Sample Input 1

4
1 4 6 3

Sample Output 1

5

The maximum absolute difference of two elements is A_3-A_1=6-1=5.

Sample Input 2

2
1000000000 1

Sample Output 2

999999999

Sample Input 3

5
1 1 1 1 1

Sample Output 3

0


main :: IO ()
main = do
    ipt <- map (read :: String -> Int) . words <$> getLine
    print $ maximum $  scanl dist (head ipt) ipt
        where
            dist a b = abs $ a - b


main = do
    s <- getLine
    print $ length (filter (=='+') s) - length (filter (=='-') s)

Score : 100 points

Problem Statement

There is always an integer in Takahashi's mind.

Initially, the integer in Takahashi's mind is 0. Takahashi is now going to eat four symbols, each of which is + or -. When he eats +, the integer in his mind increases by 1; when he eats -, the integer in his mind decreases by 1.

The symbols Takahashi is going to eat are given to you as a string S. The i-th character in S is the i-th symbol for him to eat.

Find the integer in Takahashi's mind after he eats all the symbols.

Constraints

The length of S is 4.

Each character in S is + or -.

Input

Input is given from Standard Input in the following format:

S

Output

Print the integer in Takahashi's mind after he eats all the symbols.

Sample Input 1

+-++

Sample Output 1

2

Initially, the integer in Takahashi's mind is 0.

The first integer for him to eat is +. After eating it, the integer in his mind becomes 1.

The second integer to eat is -. After eating it, the integer in his mind becomes 0.

The third integer to eat is +. After eating it, the integer in his mind becomes 1.

The fourth integer to eat is +. After eating it, the integer in his mind becomes 2.

Thus, the integer in Takahashi's mind after he eats all the symbols is 2.

Sample Input 2

-+--

Sample Output 2

-2

Sample Input 3

----

Sample Output 3

-4


main = do
  s <- getLine
  print $ length (filter (== '+') s) - length (filter (== '-') s)


Score : 300 points

Problem Statement

There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N.

On this sequence, Snuke can perform the following operation:

Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements.

Snuke would like to make all the elements in this sequence equal by repeating the operation above some number of times.
Find the minimum number of operations required.
It can be proved that, Under the constraints of this problem, this objective is always achievable.

Constraints

2 \leq K \leq N \leq 100000

A_1, A_2, ..., A_N is a permutation of 1, 2, ..., N.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of operations required.

Sample Input 1

4 3
2 3 1 4

Sample Output 1

2

One optimal strategy is as follows:

In the first operation, choose the first, second and third elements. The sequence A becomes 1, 1, 1, 4.

In the second operation, choose the second, third and fourth elements. The sequence A becomes 1, 1, 1, 1.

Sample Input 2

3 3
1 2 3

Sample Output 2

1

Sample Input 3

8 3
7 3 1 8 4 6 2 5

Sample Output 3

4


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

-- utility functions

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

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

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

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

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

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

-- main

solv k as = div (lbfr1+k-2) (k-1) + div (laft1+k-2) (k-1) where
  (lbfr1, laft1) = second (subtract 1) $ V.length *** V.length $ V.break (==1) as

main = do
  [n,k] <- map read . words <$> getLine
  as <- readIntsV n <$> B.getLine
  print $ solv k as


import Control.Applicative
main = do
	[n,k]<-map read . words <$> getLine
	getLine
	print $ -1*(div (-n+1) (k-1))


{-# OPTIONS_GHC -O #-}
{-# LANGUAGE ViewPatterns #-}

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

main=do
    [n,k]<-map read.words<$>getLine :: IO [Int]
    as <- unfoldr (B.readInt.B.dropWhile (==' ')) <$> B.getLine
    --
    print $ if n<=k
        then 1
        else let (c,bs) = lchk k as in (+) c $ fst $ lchk k (reverse bs)

lchk k ar =
    let
        n = ((f1 ar) + k-2) `div` (k-1)
    in
        (n, (1:(drop (n*(k-1)+1) ar)))

f1 as = case findIndex (==1) as of
            Just i -> i
            Nothing -> undefined


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

main = do
  [n,k] <- map read . words <$> getLine :: IO [Int]
  xs <- map read . words <$> getLine :: IO [Int]
  let m = minimum xs
  let Just i = elemIndex m xs
  let a = (length xs - 1) - i + 1
  let b = i - 0
  print $ a `div` (k-1) + b `div` (k-1)


import Data.List
import Debug.Trace

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

solve n k as =
  -- traceShow (l,r) $
  -- traceShow (lenl,lenr) $
  -- traceShow (ansl,ansr) $
  ans
  where
    (l,r) = span (>1) as
    lenl = --if length l >= k then length l + 1 else
      length l
    lenr = length r
    (ansl,next) = if lenl==0 then (0,0) else solve_ (lenl+1) k (0,0)
    (ansr,_) = if lenr==0 then (0,0) else solve_ (lenr - next) k (0,0)
    ans = ansl + ansr
    solve_ len k (ans,next) =
      if len <= k then (ans+1,k-len)
      else solve_ (len - (k-1)) k (ans+1,0)


import Data.Bool
main = putStrLn . bool ":(" "Yay!" . all (<=8) . map read . words =<< getLine

Score: 100 points

Problem Statement

E869120's and square1001's 16-th birthday is coming soon.

Takahashi from AtCoder Kingdom gave them a round cake cut into 16 equal fan-shaped pieces.

E869120 and square1001 were just about to eat A and B of those pieces, respectively,

when they found a note attached to the cake saying that "the same person should not take two adjacent pieces of cake".

Can both of them obey the instruction in the note and take desired numbers of pieces of cake?

Constraints

A and B are integers between 1 and 16 (inclusive).

A+B is at most 16.

Input

Input is given from Standard Input in the following format:

A B

Output

If both E869120 and square1001 can obey the instruction in the note and take desired numbers of pieces of cake, print Yay!; otherwise, print :(.

Sample Input 1

5 4

Sample Output 1

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 2

8 8

Sample Output 2

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 3

11 4

Sample Output 3

:(

In this case, there is no way for them to take desired number of pieces, unfortunately.


main=getLine>>=putStr.(\x->if x>0 then ":(" else "Yay!").sum.filter(<9).map read.words


main = do
    [a,b] <- map read . words <$> getLine :: IO [Int]
    putStrLn $ if a <= 8 && b <= 8 then "Yay!" else ":("


main = do
  _ <- getLine
  as <- getLine >>= return . map read . words :: IO [Integer]
  print $ sum $ map count as

  where
    count n = if even n then 1 + count (div n 2) else 0

Score: 300 points

Problem Statement

As AtCoder Beginner Contest 100 is taking place, the office of AtCoder, Inc. is decorated with a sequence of length N, a = {a_1, a_2, a_3, ..., a_N}.

Snuke, an employee, would like to play with this sequence.

Specifically, he would like to repeat the following operation as many times as possible:

For every i satisfying 1 \leq i \leq N, perform one of the following: "divide a_i by 2" and "multiply a_i by 3".
Here, choosing "multiply a_i by 3" for every i is not allowed, and the value of a_i after the operation must be an integer.

At most how many operations can be performed?

Constraints

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

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

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 a_3 ... a_N

Output

Print the maximum number of operations that Snuke can perform.

Sample Input 1

3
5 2 4

Sample Output 1

3

The sequence is initially {5, 2, 4}. Three operations can be performed as follows:

First, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {15, 6, 2}.

Next, multiply a_1 by 3, divide a_2 by 2 and multiply a_3 by 3. The sequence is now {45, 3, 6}.

Finally, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {135, 9, 3}.

Sample Input 2

4
631 577 243 199

Sample Output 2

0

No operation can be performed since all the elements are odd. Thus, the answer is 0.

Sample Input 3

10
2184 2126 1721 1800 1024 2528 3360 1945 1280 1776

Sample Output 3

39