Monocarp is playing a computer game. Now he wants to complete the first level of this game.A level is a rectangular grid of $$$2$$$ rows and $$$n$$$ columns. Monocarp controls a character, which starts in cell $$$(1, 1)$$$ — at the intersection of the $$$1$$$-st row and the $$$1$$$-st column.Monocarp's character can move from one cell to another in one step if the cells are adjacent by side and/or corner. Formally, it is possible to move from cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$ in one step if $$$|x_1 - x_2| \le 1$$$ and $$$|y_1 - y_2| \le 1$$$. Obviously, it is prohibited to go outside the grid.There are traps in some cells. If Monocarp's character finds himself in such a cell, he dies, and the game ends.To complete a level, Monocarp's character should reach cell $$$(2, n)$$$ — at the intersection of row $$$2$$$ and column $$$n$$$.Help Monocarp determine if it is possible to complete the level.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$3 \le n \le 100$$$) — the number of columns. The next two lines describe the level. The $$$i$$$-th of these lines describes the $$$i$$$-th line of the level — the line consists of the characters '0' and '1'. The character '0' corresponds to a safe cell, the character '1' corresponds to a trap cell. Additional constraint on the input: cells $$$(1, 1)$$$ and $$$(2, n)$$$ are safe.

For each test case, output YES if it is possible to complete the level, and NO otherwise.

NoteConsider the example from the statement.In the first test case, one of the possible paths is $$$(1, 1) \rightarrow (2, 2) \rightarrow (2, 3)$$$.In the second test case, one of the possible paths is $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 3) \rightarrow (2, 4)$$$.In the fourth test case, one of the possible paths is $$$(1, 1) \rightarrow (2, 2) \rightarrow (1, 3) \rightarrow (2, 4) \rightarrow (1, 5) \rightarrow (2, 6)$$$.

{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B8
import qualified Data.ByteString.Builder as Bu
import Data.Functor.Identity
import Control.Monad.Trans.State
import Control.Monad
import Control.Applicative
import Control.Arrow
import Data.Function
import qualified Data.Bits as B
import qualified Data.Map.Lazy as M
import qualified Data.Set as S
import qualified Data.List as L

data Input = Input {m :: Int, row1 :: B8.ByteString, row2 :: B8.ByteString}
data Output = YES | NO deriving Show

solve :: Input -> Output
solve (Input _ xs ys) = maybe YES (const NO) $ L.find (==('1','1')) $ B8.zip xs ys

-- gives a State(T) monad which when run gives Input
input :: StateT [B8.ByteString] Identity Input
input = do
  ~[m] <- getIntegrals 1
  row1 <- state getNext
  row2 <- state getNext
  return $ Input m row1 row2

output :: Output -> Bu.Builder
output = go where
  str = Bu.string7
  nl  = Bu.string7 "\n"
  sp  = Bu.string7 " "
  dec = Bu.intDec
  go NO = str "NO" <> nl
  go (YES) = str "YES" <> nl --kkmconcat $ (<>nl) <$> [str "Yes", dec l, (mconcat $ fmap ((<> sp).dec) xs)]

numberOfTestcases :: St [Int]
numberOfTestcases = explicit
  where implicit = return [1] :: St [Int]
        explicit = getIntegrals 1

----------------------------- library -------------------------------
modp :: Integral t=>t->t
modp = (`mod` (10^9+7))

fastPow :: Integral t=>(t->t)->t->t->t
fastPow modf base' p' = go base' p' where
  go base 0 = base
  go base p = go (base`times`base) (p`div`2)  `times`  base^(p`mod`2)
  times = (modf.).(*)

primeFac :: Integral t=> t -> [(t,Int)]
primeFac  = map (\xs-> (head xs,length xs)).L.group.tryDiv 2 where
  tryDiv d n
    | n `mod` d == 0 = d : tryDiv d (n `div` d)
    | n == 1 = []
    | d*d < n = tryDiv (d+1+d`mod`2) n
    | otherwise = tryDiv n n

umakeset xs = (M.fromList (zip xs xs), M.fromList (zip xs (repeat 0)))
ufind uf@(parents,ranks) x = if parents M.! x == x then x else ufind uf (parents M.! x)
uunion uf@(parents, ranks) x y = if fx==fy then (False,uf) else (True, (parents1, ranks1)) where
  (fx, fy) = (ufind uf x, ufind uf y)
  [(r0,f0), (r1,f1)] = L.sort [(ranks M.! fx, fx), (ranks M.! fy, fy)]
  parents1 = M.insert f0 f1 parents
  ranks1 = if r0 /= r1 then ranks else M.insert f1 (r1+1) ranks

------------------------------- main --------------------------------
type St = StateT [B8.ByteString] Identity

doTestcase :: St Bu.Builder
doTestcase = input >>= (solve >>> output >>> return)

getNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])
getNext [] =  (B8.take 0 (B8.pack "."),[])
getNext (w:ws) =  (w,ws)

getIntegral :: Num t => B8.ByteString -> t
getIntegral x =  fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x

getIntegrals :: Num t => Int -> St [t]
getIntegrals n = replicateM n $ getIntegral <$> state getNext

main :: IO ()
main = do
  raw <- B8.getContents
  let bytestrings = B8.words raw
  let outputs = flip evalState bytestrings $ do
        ~[nTc] <- numberOfTestcases
        let answers = replicateM nTc doTestcase
        fmap mconcat answers
  B8.putStr $ Bu.toLazyByteString outputs

import Control.Monad

main = do
    t <- readLn :: IO Int
    replicateM_ t solve

solve = do
    n <- readLn :: IO Int
    s0 <- getLine
    s1 <- getLine
    let s = zip s0 s1
    let block = ('1', '1') `elem` s
    putStrLn $ if block
        then "NO"
        else "YES"

import Control.Monad

main = do
  t <- readLn :: IO Int
  replicateM_ t printSolve

printSolve = do
  n <- readLn :: IO Int
  a <- getLine
  b <- getLine
  putStrLn $ checkPossible ((tail . init) a) ((tail . init) b)

checkPossible [] [] = "YES"
checkPossible (x:xs) (y:ys)
  | x == '1' && y == '1' = "NO"
  | otherwise = checkPossible xs ys

import Data.Function (on)

yesNo False = "NO"
yesNo True = "YES"

solve input = let (t:tasks) = lines input
                  get_ans [] = []
                  get_ans (n:s1:s2:xs) = task_ans s1 s2 : get_ans xs where
                                         task_ans s1 s2 = (and $ zipWith ((||) `on` (=='0')) (init s1) (init s2)) && last s2 == '0'
              in unlines . map yesNo $ get_ans tasks

main = interact solve

import Control.Monad
import Data.List

calc :: [(Char,Char)] -> String
calc str =
  let ans = all (\(i,j) ->
         (i=='0') || (j=='0')
         ) str
  in
    if ans then "YES" else "NO"

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    unused <- getLine
    line1 <- getLine
    line2 <- getLine
    putStrLn $ calc $ zip line1 line2


Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.

The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of different pebble types and number of pebbles Anastasia can place in one pocket. The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 104) — number of pebbles of each type.

The only line of output contains one integer — the minimum number of days Anastasia needs to collect all the pebbles.

NoteIn the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type — on the second day, and of third type — on the third day.Optimal sequence of actions in the second sample case:   In the first day Anastasia collects 8 pebbles of the third type.  In the second day she collects 8 pebbles of the fourth type.  In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type.  In the fourth day she collects 7 pebbles of the fifth type.  In the fifth day she collects 1 pebble of the second type.

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as B
import Text.Printf

readInt = ( readLn :: IO Int )
readInts = map ( read :: String -> Int ) . words <$> getLine

getList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

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

main = do
	[ n, k ] <- readInts
	as <- getList
	print $ ( `div` 2 ) $ succ $ sum $ map ( \m -> ( m + k - 1 ) `div` k ) as

main :: IO ()
main = print . solve 0 0 . tail . map read . words =<< getContents

solve :: Int -> Int -> [Int] -> Int
solve sum single [_]      = sum + (single + 1) `div` 2
solve sum single (k:w:ws) = let pockets = (w + k - 1) `div` k
                            in solve (sum + pockets `div` 2) (single + pockets `mod` 2) (k:ws)

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

main = getInts >>= \[n, k] -> getInts >>= print . ql 2.  sum . fmap (ql k) where
  ql k x = quot (x + k - 1) k
  getInts = fmap (unfoldr readOne) BS.getLine where
    readOne s = do
      (x , s') <- BS.readInt s
      return (x, BS.drop 1 s')

import Data.List
import Data.Array
import Data.Ord

srt x=reverse $ sort x

takeMax n k
	|n>k = n-k
	|otherwise = 0

solve [] k day = day
solve [x] k day
	|mod x (2*k) ==0 = day + (div x (2*k))
	|otherwise = day + (div x (2*k) + 1)
solve (x:y:xs) k day
	|x==0 && y==0 = solve xs k day
	|x==0 = solve (y:xs) k day
	|y==0 = solve (x:xs) k day
	|x>=2*k = solve ((mod x (2*k)):y:xs) k (day+(div x (2*k)))
	|y>=2*k  = solve (x:(mod y (2*k)):xs) k (day+(div y (2*k)))
	|otherwise = solve ((takeMax x k):(takeMax y k):xs) k (day+1)

res (k,x) = solve (srt x) k 0

extract (x:y:_) = (k,num) where
	(_:k:_)=map (\n->read n::Integer) $ words x
	num=map (\n->read n::Integer) $ words y

main=interact$show.res.extract.lines

import Data.List
import Data.Array
import Data.Ord
import Data.Char

rd x = read x::Integer
getNumbers=map rd.words
extract (x:y:_) = (k,num) where
	(_:k:_)=getNumbers x
	num=getNumbers y

solve x k=(\(x,y)->x+(div y 2)+(mod y 2)) $ foldr (\(a,b) (x,y)->(a+x,b+y)) (0,0) pairs
	where
		ones n
			|n==0 = 0
			|n>k = 2
			|otherwise = 1
		pairs = map (\n->(div n (2*k),ones (mod n (2*k)))) x

res (k,x) = solve x k

main=interact$show.res.extract.lines

import Data.List
import Data.Array
import Data.Ord
import Data.Char

rd x = read x::Integer
getNumbers=map rd.words
extract (x:y:_) = (k,num) where
	(_:k:_)=getNumbers x
	num=getNumbers y
divm x k=(\(a,b)->[a,b])$ quotRem x k
solve x k=(\(x,y)->x+sum(divm y 2)) $ foldr (\(a,b) (x,y)->(a+x,b+y)) (0,0) pairs
	where
		ones n
			|n==0 = 0
			|n>k = 2
			|otherwise = 1
		f n k=(a,ones b) where
			[a,b]=divm n (2*k)
		pairs = map (\n->f n k) x

res (k,x) = solve x k

main=interact$show.res.extract.lines

main = getContents >>= print . solve 0 . map read . words

solve rtn (n:k:ws)
  |null ws = (rtn + 1) `div` 2
  |otherwise = solve (rtn + ((head ws + k - 1)`div` k)) (n:k:(tail ws))

import Data.List( sort)
import Control.Applicative( (<$>))
import Control.Monad.State( evalState, get, modify)
main = do
    [_n_, k_] <- map read . words <$> getLine
    ws_ <- map read . words <$> getLine
    print $ slotTakingStep 2 k_ $ sort ws_

slotTakingStep numSlots slotSize list = (process list)
					    `evalState` (0,numSlots)
  where
    stepSize =  numSlots * slotSize

    process []	    = do
	    (value,idleSlots) <- get
	    return $ value + (if idleSlots==numSlots then 0 else 1)
    process (e:es) = do
	let
	    modifySlot f = modify (f <$>)
	    modifyValue f = modify $ \(value, idles) ->
					 (f value, idles)
	    getIdleSlots = snd <$> get

	idleSlots <- getIdleSlots
	if idleSlots==numSlots
	then case e `quotRem` stepSize of
		(0, stepRem)	    -> do
		    let
			(q,r) = stepRem `quotRem` slotSize
			slotsNeeded =	if r==0 then q else q+1
		    if numSlots==slotsNeeded
		    then do
			modifyValue (+1)
			process es
		    else do
			modifySlot (subtract slotsNeeded)
			process es

		(steps, 0)	-> do
				    modifyValue (+steps)
				    process es
		(steps,stepRem) -> do
				    modifyValue (+steps)
				    process (stepRem:es)
	else let
		(q,r) = e `quotRem` slotSize
		slotsNeeded =    if r==0 then q else q+1
		flushSlot = modifySlot (const numSlots)

	    in if idleSlots < slotsNeeded
	    then do
		flushSlot
		modifyValue (+1)
		process (e - idleSlots * slotSize   :es)
	    else if idleSlots==slotsNeeded
		then do
		    flushSlot
		    modifyValue (+1)
		    process es
		else do
		    modifySlot (subtract slotsNeeded)
		    process es

import Control.Applicative( (<$>))
main = do
    [_n_, k_] <- map read . words <$> getLine
    ws_ <- map read . words <$> getLine
    print $ slotTakingStep 2 k_ ws_

slotTakingStep numSlots szSlot list =
    let
	divBox i k = 1 + ((i-1)`div`k)
	boxes = sum $ (`divBox` szSlot) <$> list
    in
	boxes `divBox` numSlots

import Data.List( sort)
import Control.Applicative( (<$>))
import Control.Monad.Reader( runReader, ask, Reader)
main = do
    [_n_, k_] <- map read . words <$> getLine
    ws_ <- map read . words <$> getLine
    print $ slotTakingStep 2 k_ $ sort ws_

slotTakingStep	::Integral i
		=> Int -> i -> [i] -> i
slotTakingStep numSlots szSlot list = process 0 list
  where
    process step []  = step
    process step [n] =
	let
	    (q,r) = n `quotRem` (fromIntegral numSlots * szSlot)
	in
	    step + (if r==0 then q else q+1)

    process step list =
	let
	    (h:tl, remain) = splitAt numSlots list
	    (q,r) = h `quotRem` szSlot
	    q' =	if r==0 then q else q+1
	    processedSlot = (subtract $ q' * szSlot) <$> tl
	    positiveFiltered = dropWhile (<=0) processedSlot
	in
	    process (step+q') (positiveFiltered++remain)

{-# OPTIONS_GHC -O3 #-}
{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}

import Control.Monad (forM_, forM)
import Data.List (sort)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Maybe (fromJust)

readint = fst. fromJust . C.readInt

ddiv k x | x `mod` k == 0 = x `div` k
         | otherwise      = x `div` k + 1

main = do
    (map readint . C.words -> [n, k]) <- B.getLine
    (map readint . C.words -> xs) <- B.getLine
    putStrLn $ show $ ddiv 2 (sum (map (ddiv k) xs))

import Control.Applicative

solve _ [] = 0
solve k (l:ls) = if l<=k then 1+solve k ls else ceiling (l/k)+solve k ls

main = do
   [n,k] <- map read.words <$> getLine
   suma <- map read.words <$> getLine
   putStrLn.show $ ceiling (fromInteger (solve k suma)/2)

import Data.List
import Data.Array
import Data.Ord

srt x=reverse $ sort x

takeMax n k
	|n>k = n-k
	|otherwise = 0

solve [x] k day
	|mod x (2*k) ==0 = day + (div x (2*k))
	|otherwise = day + (div x (2*k) + 1)
solve (x:y:xs) k day
	|x==0 = solve (y:xs) k day
	|x>=2*k = solve ((mod x (2*k)):y:xs) k (day+(div x (2*k)))
	|y>=2*k && (mod y (2*k))/=0 = solve (x:(mod y (2*k)):xs) k (day+(div y (2*k)))
	|y>=2*k  = solve (x:xs) k (day+(div y (2*k)))
	|otherwise = solve ((takeMax x k):(takeMax y k):xs) k (day+1)

res (k,x) = solve (srt x) k 0

extract (x:y:_) = (k,num) where
	(_:k:_)=map (\n->read n::Integer) $ words x
	num=map (\n->read n::Integer) $ words y

main=interact$show.res.extract.lines

import Data.List
import Data.Array
import Data.Ord

srt x=reverse $ sort x

takeMax n k
	|n>k = n-k
	|otherwise = 0

solve [x] k day
	|mod x k ==0 = day + (div x k)
	|otherwise = day + (div x k + 1)
solve (x:y:xs) k day
	|x==0 = solve (y:xs) k day
	|x>=2*k = solve ((mod x k):y:xs) k (day+(div x (2*k)))
	|otherwise = solve ((takeMax x k):(takeMax y k):xs) k (day+1)

res (k,x) = solve (srt x) k 0

extract (x:y:_) = (k,num) where
	(_:k:_)=map (\n->read n::Integer) $ words x
	num=map (\n->read n::Integer) $ words y

main=interact$show.res.extract.lines

import Data.List
import Data.Array
import Data.Ord

srt x=reverse $ sort x

takeMax n k
	|n>k = n-k
	|otherwise = 0

solve [x] k day
	|mod x (2*k) ==0 = day + (div x (2*k))
	|otherwise = day + (div x (2*k) + 1)
solve (x:y:xs) k day
	|x==0 = solve (y:xs) k day
	|x>=2*k = solve ((mod x (2*k)):y:xs) k (day+(div x (2*k)))
	|y>=2*k = solve (x:(mod y (2*k)):xs) k (day+(div y (2*k)))
	|otherwise = solve ((takeMax x k):(takeMax y k):xs) k (day+1)

res (k,x) = solve (srt x) k 0

extract (x:y:_) = (k,num) where
	(_:k:_)=map (\n->read n::Integer) $ words x
	num=map (\n->read n::Integer) $ words y

main=interact$show.res.extract.lines

import Data.List
import Data.Array
import Data.Ord
import Data.Char

rd x = read x::Integer
getNumbers=map rd.words
extract (x:y:_) = (k,num) where
	(_:k:_)=getNumbers x
	num=getNumbers y

solve x k=foldr (\(_,b) n->n+b) 0 pairs
	where
		ones n
			|n==0 = 0
			|n>k = 2
			|otherwise = 1
		pairs = map (\n->(div n (2*k),ones (mod n (2*k)))) x

res (k,x) = solve x k

main=interact$show.res.extract.lines

import Data.List
import Data.Array
import Data.Ord

srt x=reverse $ sort x

takeMax n k
	|n>k = n-k
	|otherwise = 0

solve [x] k day
	|mod x k ==0 = day + (div x k)
	|otherwise = day + (div x k + 1)
solve (x:y:xs) k day
	|x==0 = solve (y:xs) k day
	|x>=2*k = solve ((mod x (2*k)):y:xs) k (day+(div x (2*k)))
	|otherwise = solve ((takeMax x k):(takeMax y k):xs) k (day+1)

res (k,x) = solve (srt x) k 0

extract (x:y:_) = (k,num) where
	(_:k:_)=map (\n->read n::Integer) $ words x
	num=map (\n->read n::Integer) $ words y

main=interact$show.res.extract.lines

import Data.List
import Data.Array
import Data.Ord

srt x=reverse $ sort x

takeMax n k
	|n>k = n-k
	|otherwise = 0

solve [x] k day
	|mod x (2*k) ==0 = day + (div x (2*k))
	|otherwise = day + (div x (2*k) + 1)
solve (x:y:xs) k day
	|x==0 = solve (y:xs) k day
	|x>=2*k = solve ((mod x (2*k)):y:xs) k (day+(div x (2*k)))
	|otherwise = solve ((takeMax x k):(takeMax y k):xs) k (day+1)

res (k,x) = solve (srt x) k 0

extract (x:y:_) = (k,num) where
	(_:k:_)=map (\n->read n::Integer) $ words x
	num=map (\n->read n::Integer) $ words y

main=interact$show.res.extract.lines

import Data.List( sortBy)
import Control.Applicative( (<$>))
import Data.Bool( bool)
main = do
    [n_, k_] <- map read . words <$> getLine
    ws <- map read . words <$> getLine
    let
	sortedWs = sortBy (flip compare) ws
	k2 = 2*k_
	collect day [] = day
	collect day [w] = let
				(qu,re) = w`quotRem`k2
				addition = bool 0 1 (re/=0)
			  in
			    day + qu + addition
	collect day (w1:w2:ws)= let
				(q,r) = w1`quotRem`k2
				nextW = w2-k_
	  in if k_<=r
	    then collect (day+q+1) (w2:ws)
	    else if 0 < nextW
		    then collect (day+q+1) (nextW:ws)
		    else collect (day+q+1) ws
    print $ collect 0 sortedWs

import Data.List( sortBy)
import Control.Applicative( (<$>))
import Data.Bool( bool)
main = do
    [n_, k_] <- map read . words <$> getLine
    ws <- map read . words <$> getLine
    let
	sortedWs = sortBy (flip compare) ws
	k2 = 2*k_
	collect day [] = day
	collect day [w] = let
			    (q,r) = w`quotRem`k2
			in
			    day + q + (if r/=0 then 1 else 0)

	collect day (w1:w2:ws) = let
				    w1' = max w1 w2
				    w2' = min w1 w2
				    (q,r) = w2'`quotRem`k_
				    head' = w1' - q * k_
		in case (q,r) of
		    (0,r)   -> if w1'==w2'
				then collect (day+1) ws
				else collect (day+1) ((w1'-k_):ws)
		    (q,0)   -> if w1'==w2'
				then collect (day+q) ws
				else collect (day+q) (head':ws)
		    (q,r)   -> collect (day+q) (head':r:ws)
    print $ collect 0 sortedWs


Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integers: the number of the starting vertex, the number of the final vertex and the edge's weight. So, as Vasya was trying to represent characteristics of a recently invented robot in his program, he faced the following problem.Vasya is not a programmer, so he asked his friend Gena, what the convenient way to store n integers is. Gena used to code in language X-- and so he can use only the types that occur in this language. Let's define, what a "type" is in language X--:  First, a type is a string "int".  Second, a type is a string that starts with "pair", then followed by angle brackets listing exactly two comma-separated other types of language X--. This record contains no spaces.  No other strings can be regarded as types. More formally: type := int | pair<type,type>. For example, Gena uses the following type for graph edges: pair<int,pair<int,int>>.Gena was pleased to help Vasya, he dictated to Vasya a type of language X--, that stores n integers. Unfortunately, Gena was in a hurry, so he omitted the punctuation. Now Gena has already left and Vasya can't find the correct punctuation, resulting in a type of language X--, however hard he tries.Help Vasya and add the punctuation marks so as to receive the valid type of language X--. Otherwise say that the task is impossible to perform.

The first line contains a single integer n (1 ≤ n ≤ 105), showing how many numbers the type dictated by Gena contains. The second line contains space-separated words, said by Gena. Each of them is either "pair" or "int" (without the quotes). It is guaranteed that the total number of words does not exceed 105 and that among all the words that Gena said, there are exactly n words "int".

If it is possible to add the punctuation marks so as to get a correct type of language X-- as a result, print a single line that represents the resulting type. Otherwise, print "Error occurred" (without the quotes). Inside the record of a type should not be any extra spaces and other characters.  It is guaranteed that if such type exists, then it is unique. Note that you should print the type dictated by Gena (if such type exists) and not any type that can contain n values.

import Monad (MonadPlus, liftM, mzero)
import Prelude hiding (print)

data Type  =  Int | Pair Type Type

nameInt   =  "int"
namePair  =  "pair"

mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a
mfilter pred ma  =  do
    a  <-  ma
    if pred a then return a else mzero

parse :: [String] -> Maybe Type
parse  =  liftM fst . mfilter (null . snd) . parse'
  where
    parse' (w:ws)
      | w == nameInt  =  return (Int, ws)
      | w == namePair  =  do
        (t1, ws')  <-  parse' ws
        (t2, ws'')  <-  parse' ws'
        return (Pair t1 t2, ws'')
    parse' _  =  fail ""

print :: Maybe Type -> IO ()
print res  =  maybe (putStr "Error occurred") print' res >> putStrLn ""
  where
    print' Int  =  putStr "int"
    print' (Pair t1 t2)  =  sequence_
        [putStr "pair<", print' t1, putStr ",", print' t2, putStr ">"]

main :: IO ()
main  =  getLine >> getLine >>= print . parse . words

{-# LANGUAGE OverloadedStrings #-}

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

main = B.getContents >>= print.solve.tail.B.words

solve :: [B.ByteString] -> Expr
solve bss = evalParser (expr <* end)  bss

type State = [Elem]
type Elem = B.ByteString

data Expr = I | P Expr Expr | Error

instance Show Expr where
  showsPrec _ I = showString "int"
  showsPrec _ (P x y) = showString "pair<"
                      . shows x
                      . showChar ','
                      . shows y
                      . showChar '>'
  showsPrec _ Error = showString "Error occurred"

evalParser :: Parser Expr -> State -> Expr
evalParser expr st = case runParser expr st of
                       Just (result,_) -> result
                       Nothing -> Error

getElem :: Parser Elem
getElem = Parser $ \st -> if null st
                              then Nothing
                              else Just (head st,st)
getState :: Parser State
getState = Parser $ \st -> Just (st,st)
putState :: State -> Parser ()
putState st = Parser $ const $ Just ((),st)
modifyState :: (State -> State) -> Parser ()
modifyState f = Parser $ \st -> Just ((),f st)

expr = int <|> pair

int = do
  bs <- getElem
  guard (bs=="int")
  modifyState tail
  return I

pair = do
  bs <- getElem
  guard (bs=="pair")
  modifyState tail
  x <- expr
  y <- expr
  return $ P x y

end = do
  rest <- getState
  guard (null rest)

data Parser t = Parser {runParser :: State -> Maybe (t, State)}

instance Monad Parser where
  return t = Parser $ \st -> Just (t,st)
  m >>= f = Parser $ \st -> do
    (t,rest) <- runParser m st
    runParser (f t) rest

instance MonadPlus Parser where
  mzero = Parser $ const Nothing
  mplus p q = Parser $ \st ->
    runParser p st `mplus` runParser q st

instance Functor Parser where
  fmap f m = Parser $ \st ->
    fmap (\(t,rest) -> (f t,rest)) $ runParser m st

instance Applicative Parser where
  pure = return
  (<*>) = ap

instance Alternative Parser where
  empty = mzero
  (<|>) = mplus

main = getLine >> getLine >>= putStrLn.solve [] [].words

solve [] [] ["int"] = "int"
solve ans [] [] = concat.reverse $ ans
solve ans s ("pair":ws) = solve ("pair<":ans) (",>"++s) ws
solve ans (',':s) ("int":ws) = solve ("int,":ans) s ws
solve ans ('>':s) ("int":ws) =
  case span ('>'==) s of
    (xs,',':ys) -> solve (",":xs:"int>":ans) ys ws
    (xs,[])     -> solve (xs:"int>":ans) [] ws
solve _ _ _  = "Error occurred"

import Control.Monad
import Data.List
data Type = IntT | PairT Type Type

printType :: Type -> IO ()
printType IntT = putStr "int"
printType (PairT t1 t2) = do
  putStr "pair<"
  printType t1
  putStr ","
  printType t2
  putStr ">"

data Parser a = Parser {run :: String -> (Maybe a, String)}
instance Monad Parser where
    return x = Parser $ \inp -> (Just x, inp)
    p >>= q = Parser $ \inp ->
              case run p inp of
                (Nothing, _) -> (Nothing, "")
                (Just x, rest) -> run (q x) rest

(<|>) :: Parser a -> Parser a -> Parser a
p <|> q = Parser $ \inp ->
          case run p inp of
            ok@(Just x, rest) -> ok
            (Nothing, _) -> run q inp

int :: Parser Type
int = Parser $ \inp -> if "int " `isPrefixOf` inp then (Just IntT, drop 4 inp) else (Nothing, "")

pairCons :: Parser ()
pairCons = Parser $ \inp -> if "pair " `isPrefixOf` inp then (Just (), drop 5 inp) else (Nothing, "")

typ :: Parser Type
typ = do
  int <|> do
        pairCons
        t1 <- typ
        t2 <- typ
        return $ PairT t1 t2

main = do
  n_ <- getLine
  let n = read n_
  inp_ <- getLine
  let inp = inp_ ++ " "
  if length (filter (=='t') inp) == n then
      case run typ inp of
        (Just typ, "") -> printType typ >> putStrLn ""
        _ -> putStrLn "Error occurred"
   else putStrLn "Error occurred"

import System.IO

readType ("int":xs) acc = ("int":acc, xs)
readType ("pair":xs) acc = let (la, lc) = readType xs ("<":"pair":acc);
                               (ra, rc) = readType lc (",":la)
                           in (">":ra, rc)
readType _ _ = (["!"], [])

checkElem xs = if elem "!" xs then ["Error occurred"] else xs
checkLen (res, xs) = if xs /= [] then (["Error occurred"], []) else (res, xs)

solve text = concat $ reverse $ checkElem $ fst $ checkLen $ readType lexs []
             where lexs = words text

main = do
--    content <- readFile "input.txt"
--    ([intCount, ttypes]) <- return $ lines content
    ttypes <- getLine >> getLine
    putStrLn (solve ttypes)

loop :: [String] -> [String] -> [String] -> String

solve t = loop (words t) [] []

solve' t = loop t [] []

loop ["int"] [] [] = "int"
loop [] [] res = concat . reverse $ res
loop [] (">":stack) (",":res) =
    "Error occurred"

loop task (">":stack) res@(">":_) =
    loop task stack (">":res)
loop task (",":stack) res@(">":_) =
    loop task stack (",":res)

loop ("pair":task) stack res =
    loop task (",":">":stack) ("pair<":res)

loop ("int":task) (s:stack) res@(",":_) =
    loop task stack (s:"int":res)
loop ("int":task) (s:stack) res@("pair<":_) =
    loop task stack (s:"int":res)

loop task stack res =
    "Error occurred"
--   error $ show task ++ ";" ++ show stack++ ";"++show res

parse foo = case lines foo of
              [_, x] -> words x

main = (putStrLn . solve' . parse =<< getContents)

loop :: [String] -> [String] -> [String] -> String

solve t = loop (words t) [] []

solve' t = loop t [] []

loop ["int"] [] [] = "int"
loop [] [] res = concat . reverse $ res
loop [] (">":stack) (",":res) =
    "Error occurred"

loop task (">":stack) res@(">":_) =
    loop task stack (">":res)
loop task (",":stack) res@(">":_) =
    loop task stack (",":res)

loop ("pair":task) stack res =
    loop task (",":">":stack) ("pair<":res)

loop ("int":task) (s:stack) res@(",":_) =
    loop task stack (s:"int":res)
loop ("int":task) (s:stack) res@("pair<":_) =
    loop task stack (s:"int":res)

loop task stack res =
    "Error occurred"
--   error $ show task ++ ";" ++ show stack++ ";"++show res

parse foo = case lines foo of
              [_, x] -> words $! x

main = (putStrLn . solve' . parse =<< getContents)

import Monad (MonadPlus, liftM, mzero)
import Prelude hiding (print)

data Type  =  Int | Pair Type Type

nameInt   =  "int"
namePair  =  "pair"

mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a
mfilter pred ma  =  do
    a  <-  ma
    if pred a then return a else mzero

parse :: [String] -> Maybe Type
parse  =  liftM fst . mfilter (null . snd) . parse'
  where
    parse' (w:ws)
      | w == nameInt  =  return (Int, ws)
      | w == namePair  =  do
        (t1, ws')  <-  parse' ws
        (t2, ws'')  <-  parse' ws'
        return (Pair t1 t2, ws'')
    parse' _  =  fail ""

print :: Maybe Type -> IO ()
print res  =  maybe (putStr "Error occured") print' res >> putStrLn ""
  where
    print' Int  =  putStr "int"
    print' (Pair t1 t2)  =  sequence_
        [putStr "pair<", print' t1, putStr ",", print' t2, putStr ">"]

main :: IO ()
main  =  getLine >> getLine >>= print . parse . words

import Control.Monad
import Data.List
data Type = IntT | PairT Type Type
instance Show Type where
    show IntT = "Int"
    show (PairT t1 t2) = "pair<" ++ show t1 ++ "," ++ show t2 ++ ">"

data Parser a = Parser {run :: String -> (Maybe a, String)}
instance Monad Parser where
    return x = Parser $ \inp -> (Just x, inp)
    p >>= q = Parser $ \inp ->
              case run p inp of
                (Nothing, _) -> (Nothing, "")
                (Just x, rest) -> run (q x) rest

(<|>) :: Parser a -> Parser a -> Parser a
p <|> q = Parser $ \inp ->
          case run p inp of
            ok@(Just x, rest) -> ok
            (Nothing, _) -> run q inp

int :: Parser Type
int = Parser $ \inp -> if "int " `isPrefixOf` inp then (Just IntT, drop 4 inp) else (Nothing, "")

pairCons :: Parser ()
pairCons = Parser $ \inp -> if "pair " `isPrefixOf` inp then (Just (), drop 5 inp) else (Nothing, "")

typ :: Parser Type
typ = do
  int <|> do
        pairCons
        t1 <- typ
        t2 <- typ
        return $ PairT t1 t2

main = do
  n_ <- getLine
  let n = read n_
  inp_ <- getLine
  let inp = inp_ ++ " "
  if length (filter (=='t') inp) == n then
      case run typ inp of
        (Just typ, "") -> print typ
        _ -> putStrLn "Error occurred"
   else putStrLn "Error occurred"

loop :: [String] -> [String] -> [String] -> String

solve t = loop (words t) [] []

solve' t = loop t [] []

loop [] [] res = concat . reverse $ res
loop task (",":stack) res@(">":_) =
    loop task stack (",":res)
loop task@("pair":_) stack (">":res) =
    loop task (">":stack) res
loop task@("pair":_) stack ("int":res) =
    "Error occurred"
loop ("pair":task) stack res =
    loop task (",":">":stack) ("pair<":res)
loop ("int":task) (s:stack) res@(",":_) =
    loop task stack (s:"int":res)
loop ("int":task) (s:stack) res@("pair<":_) =
    loop task stack (s:"int":res)
loop task@("int":_) (">":stack) res =
    loop task stack (">":res)
loop ("int":task) [] [] =
    loop task [] ["int"]
-- loop task (s:stack) res@("<":_) =
--     loop task stack (s:res)
loop [] (">":stack) (",":res) =
    "Error occurred"
loop [] (">":stack) (res) =
    loop [] stack (">":res)
loop task stack res =
    "Error occurred"
--    error $ show task ++ ";" ++ show stack++ ";"++show res

parse foo = case lines foo of
              [_, x] -> words $! x

main = (putStrLn . solve' . parse =<< getContents)

loop :: [String] -> [String] -> [String] -> String

solve t = loop (words t) [] []

solve' t = loop t [] []

loop [] [] res = concat . reverse $ res
loop task (",":stack) res@(">":_) =
    loop task stack (",":res)
loop ("pair":task) stack res =
    loop task (",":">":stack) ("pair<":res)
loop ("int":task) (s:stack) res@(",":_) =
    loop task stack (s:"int":res)
loop ("int":task) (s:stack) res@("pair<":_) =
    loop task stack (s:"int":res)
loop task@("int":_) (">":stack) res =
    loop task stack (">":res)
loop ("int":task) [] [] =
    loop task [] ["int"]
-- loop task (s:stack) res@("<":_) =
--     loop task stack (s:res)
loop [] (">":stack) (",":res) =
    "Error occurred"
loop [] (">":stack) (res) =
    loop [] stack (">":res)
loop task stack res =
    "Error occurred"
    -- error $ show task ++ ";" ++ show stack++ ";"++show res

parse foo = case lines foo of
              [_, x] -> words $! x

main = (putStrLn . solve' . parse =<< getContents)

loop :: [String] -> [String] -> [String] -> String

solve t = loop (words t) [] []

solve' t = loop t [] []

loop [] [] res = concat . reverse $ res
loop task (",":stack) res@(">":_) =
    loop task stack (",":res)
loop ("pair":task) stack res =
    loop task (",":">":stack) ("pair<":res)
loop ("int":task) (s:stack) res@(",":_) =
    loop task stack (s:"int":res)
loop ("int":task) (s:stack) res@("pair<":_) =
    loop task stack (s:"int":res)
loop ("int":task) [] [] =
    loop task [] ["int"]
-- loop task (s:stack) res@("<":_) =
--     loop task stack (s:res)
loop [] (">":stack) (",":res) =
    "Error occurred"
loop [] (">":stack) (res) =
    loop [] stack (">":res)
loop task stack res = show task ++ ";" ++ show stack++ ";"++show res

parse foo = case lines foo of
              [_, x] -> words $! x

main = (putStrLn . solve' . parse =<< getContents)


The m-floor (m > 1) office of international corporation CodeForces has the advanced elevator control system established. It works as follows.All office floors are sequentially numbered with integers from 1 to m. At time t = 0, the elevator is on the first floor, the elevator is empty and nobody is waiting for the elevator on other floors. Next, at times ti (ti > 0) people come to the elevator. For simplicity, we assume that one person uses the elevator only once during the reported interval. For every person we know three parameters: the time at which the person comes to the elevator, the floor on which the person is initially, and the floor to which he wants to go.The movement of the elevator between the floors is as follows. At time t (t ≥ 0, t is an integer) the elevator is always at some floor. First the elevator releases all people who are in the elevator and want to get to the current floor. Then it lets in all the people waiting for the elevator on this floor. If a person comes to the elevator exactly at time t, then he has enough time to get into it. We can assume that all of these actions (going in or out from the elevator) are made instantly. After that the elevator decides, which way to move and at time (t + 1) the elevator gets to the selected floor.The elevator selects the direction of moving by the following algorithm.   If the elevator is empty and at the current time no one is waiting for the elevator on any floor, then the elevator remains at the current floor.  Otherwise, let's assume that the elevator is on the floor number x (1 ≤ x ≤ m). Then elevator calculates the directions' "priorities" pup and pdown: pup is the sum of the number of people waiting for the elevator on the floors with numbers greater than x, and the number of people in the elevator, who want to get to the floors with the numbers greater than x; pdown is the sum of the number of people waiting for the elevator on the floors with numbers less than x, and the number of people in the elevator, who want to get to the floors with the numbers less than x. If pup ≥ pdown, then the elevator goes one floor above the current one (that is, from floor x to floor x + 1), otherwise the elevator goes one floor below the current one (that is, from floor x to floor x - 1). Your task is to simulate the work of the elevator and for each person to tell the time when the elevator will get to the floor this person needs. Please note that the elevator is large enough to accommodate all the people at once.

The first line contains two space-separated integers: n, m (1 ≤ n ≤ 105, 2 ≤ m ≤ 105) — the number of people and floors in the building, correspondingly. Next n lines each contain three space-separated integers: ti, si, fi (1 ≤ ti ≤ 109, 1 ≤ si, fi ≤ m, si ≠ fi) — the time when the i-th person begins waiting for the elevator, the floor number, where the i-th person was initially located, and the number of the floor, where he wants to go.

Print n lines. In the i-th line print a single number — the moment of time, when the i-th person gets to the floor he needs. The people are numbered in the order, in which they are given in the input.  Please don't use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample the elevator worked as follows:   t = 1. The elevator is on the floor number 1. The elevator is empty. The floor number 2 has one person waiting. pup = 1 + 0 = 1, pdown = 0 + 0 = 0, pup ≥ pdown. So the elevator goes to the floor number 2.  t = 2. The elevator is on the floor number 2. One person enters the elevator, he wants to go to the floor number 7. pup = 0 + 1 = 1, pdown = 0 + 0 = 0, pup ≥ pdown. So the elevator goes to the floor number 3.  t = 3. The elevator is on the floor number 3. There is one person in the elevator, he wants to go to floor 7. The floors number 4 and 6 have two people waiting for the elevator. pup = 2 + 1 = 3, pdown = 0 + 0 = 0, pup ≥ pdown. So the elevator goes to the floor number 4.  t = 4. The elevator is on the floor number 4. There is one person in the elevator who wants to go to the floor number 7. One person goes into the elevator, he wants to get to the floor number 8. The floor number 6 has one man waiting. pup = 1 + 2 = 3, pdown = 0 + 0 = 0, pup ≥ pdown. So the elevator goes to the floor number 5.  t = 5. The elevator is on the floor number 5. There are two people in the elevator, they want to get to the floors number 7 and 8, correspondingly. There is one person waiting for the elevator on the floor number 6. pup = 1 + 2 = 3, pdown = 0 + 0 = 0, pup ≥ pdown. So the elevator goes to the floor number 6.  t = 6. The elevator is on the floor number 6. There are two people in the elevator, they want to get to the floors number 7 and 8, correspondingly. One man enters the elevator, he wants to get to the floor number 5. pup = 0 + 2 = 2, pdown = 0 + 1 = 1, pup ≥ pdown. So the elevator goes to the floor number 7.  t = 7. The elevator is on the floor number 7. One person leaves the elevator, this person wanted to get to the floor number 7. There are two people in the elevator, they want to get to the floors with numbers 8 and 5, correspondingly. pup = 0 + 1 = 1, pdown = 0 + 1 = 1, pup ≥ pdown. So the elevator goes to the floor number 8.  t = 8. The elevator is on the floor number 8. One person leaves the elevator, this person wanted to go to the floor number 8. There is one person in the elevator, he wants to go to the floor number 5. pup = 0 + 0 = 0, pdown = 0 + 1 = 1, pup < pdown. So the elevator goes to the floor number 7.  t = 9. The elevator is on the floor number 7. There is one person in the elevator, this person wants to get to the floor number 5. pup = 0 + 0 = 0, pdown = 0 + 1 = 1, pup < pdown. So the elevator goes to the floor number 6.  t = 10. The elevator is on the floor number 6. There is one person in the elevator, he wants to get to the floor number 5. pup = 0 + 0 = 0, pdown = 0 + 1 = 1, pup < pdown. So the elevator goes to the floor number 5.  t = 11. The elevator is on the floor number 5. One person leaves the elevator, this person initially wanted to get to the floor number 5. The elevator is empty and nobody needs it, so the elevator remains at the floor number 5.

{-# OPTIONS_GHC -O2 -optc-Ofast -ignore-errors #-}
{-# LANGUAGE FlexibleInstances #-}
import Control.Monad
import Data.Array.Unboxed
import Data.Int
import Data.List (sort, sortBy)
import Data.Maybe
import Data.Ord
-- import Debug.Trace
import qualified Data.IntMap as M
import qualified Data.ByteString.Char8 as C

type Map = M.IntMap ([Int] -> [Int])

insert :: Int -> Int -> Map -> Map
insert k v s = M.insertWith (.) k (v:) s

query :: Int -> Map -> [Int]
query k s = maybe [] ($[]) $ M.lookup k s

delete :: Int -> Map -> ([Int], Map)
delete k s = (maybe [] ($[]) v, s')
  where
    (v, s') = M.updateLookupWithKey (const $ const Nothing) k s

lt :: Int -> Map -> Int
lt k s = maybe 1 fst $ M.lookupLT k s

gt :: Int -> Map -> Int
gt k s = maybe 1000000007 fst $ M.lookupGT k s

instance Show ([Int] -> [Int]) where
  show = show . ($[])

data Info = Info {
    todo    :: [Int],
    outside :: Map,
    inside  :: Map,
    pup     :: Int,
    pdown   :: Int,
    now     :: Int64,
    pos     :: Int,
    ans     :: [[(Int, Int64)]]
  }
  deriving(Show)

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

solve :: Int -> [[Int]] -> [Int64]
solve n tsf = map snd $ sort $ concat $ ans $ snd $
    runState gao $ Info k M.empty M.empty 0 0 1 1 []
  where
    t = listArray (1, n) $ map (fromIntegral . (!!0)) tsf :: UArray Int Int64
    s = listArray (1, n) $ map (!!1) tsf :: UArray Int Int
    f = listArray (1, n) $ map (!!2) tsf :: UArray Int Int
    k = sortBy (comparing (t!)) [1 .. n]

    gao :: State Info ()
    gao = do
      -- debug <- gets show
      -- trace debug $ return ()
      at <- gets now
      cur <- gets pos
      -- todo -> outside
      (up, todo') <- gets $ span ((<=at) . (t!)) . todo
      modify $ \info -> info {
          outside = foldl (\i j -> insert (s!j) j i) (outside info) up,
          todo    = todo',
          pup     = pup   info + count ((>cur) . (s!)) up,
          pdown   = pdown info + count ((<cur) . (s!)) up
        }
      -- outside -> inside
      (down, outside') <- gets $ delete cur . outside
      modify $ \info -> info {
          inside  = foldl (\i j -> insert (f!j) j i) (inside info) down,
          outside = outside',
          pup     = pup   info + count ((>cur) . (f!)) down,
          pdown   = pdown info + count ((<cur) . (f!)) down
        }
      -- inside -> done
      (done, inside') <- gets $ delete cur . inside
      modify $ \info -> info {
          ans = zip done (repeat at): ans info,
          inside = inside'
        }
      -- next
      if M.null outside' && M.null inside'
        then
          when (not $ null todo') $ do
            modify $ \info -> info{now = t!head todo'}
            gao
        else do
          goup <- gets $ \info -> pup info >= pdown info
          let sub x = (length $ query x outside') + (length $ query x inside')
              minit x = if null todo'
                          then x
                          else min x $ fromIntegral $ t!head todo' - at
          if goup
            then do
              let delta = minit $ min (gt cur outside') (gt cur inside') - cur
              modify $ \info -> info {
                  now = at + fromIntegral delta,
                  pos = cur + delta,
                  pup = pup info - sub (cur + delta)
                }
            else do
              let delta = minit $ cur - max (lt cur outside') (lt cur inside')
              modify $ \info -> info {
                  now   = at + fromIntegral delta,
                  pos   = cur - delta,
                  pdown = pdown info - sub (cur - delta)
                }
          gao

main :: IO ()
main = do
  (n:_:r) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents
  let tsf = take n $ map (take 3) $ iterate (drop 3) r
  putStr $ unlines $ map show $ solve n tsf

-- Control.Monad.State
newtype State s a = State {
  runState :: s -> (a, s)
}

instance Monad (State s) where
  return a = State $ \s -> (a, s)
  m >>= f  = State $ \s -> let (a', s') = runState m s in runState (f a') s'

get :: State s s
get = State $ \s -> (s, s)

put :: s -> State s ()
put s = State $ \_ -> ((), s)

modify :: (s -> s) -> State s ()
modify f = State $ \s -> ((), f s)

gets :: (s -> a) -> State s a
gets f = State $ \s -> (f s, s)


Sensation, sensation in the two-dimensional kingdom! The police have caught a highly dangerous outlaw, member of the notorious "Pihters" gang. The law department states that the outlaw was driving from the gang's headquarters in his car when he crashed into an ice cream stall. The stall, the car, and the headquarters each occupies exactly one point on the two-dimensional kingdom.The outlaw's car was equipped with a GPS transmitter. The transmitter showed that the car made exactly n movements on its way from the headquarters to the stall. A movement can move the car from point (x, y) to one of these four points: to point (x - 1, y) which we will mark by letter "L", to point (x + 1, y) — "R", to point (x, y - 1) — "D", to point (x, y + 1) — "U".The GPS transmitter is very inaccurate and it doesn't preserve the exact sequence of the car's movements. Instead, it keeps records of the car's possible movements. Each record is a string of one of these types: "UL", "UR", "DL", "DR" or "ULDR". Each such string means that the car made a single movement corresponding to one of the characters of the string. For example, string "UL" means that the car moved either "U", or "L".You've received the journal with the outlaw's possible movements from the headquarters to the stall. The journal records are given in a chronological order. Given that the ice-cream stall is located at point (0, 0), your task is to print the number of different points that can contain the gang headquarters (that is, the number of different possible locations of the car's origin).

The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of the car's movements from the headquarters to the stall. Each of the following n lines describes the car's possible movements. It is guaranteed that each possible movement is one of the following strings: "UL", "UR", "DL", "DR" or "ULDR".  All movements are given in chronological order.  Please do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin and cout stream or the %I64d specifier.

Print a single integer — the number of different possible locations of the gang's headquarters.

NoteThe figure below shows the nine possible positions of the gang headquarters from the first sample:   For example, the following movements can get the car from point (1, 0) to point (0, 0):

import Control.Monad (liftM)

solve :: Int -> [String] -> Integer
solve n xs  =  solve' (0::Int) (0::Int) xs
  where
    solve' k l []  =  fromIntegral (n - k + 1) * fromIntegral (n - l + 1)
    solve' k l ("UL":xs)  =  solve' (k + 1) l xs
    solve' k l ("DR":xs)  =  solve' (k + 1) l xs
    solve' k l ("UR":xs)  =  solve' k (l + 1) xs
    solve' k l ("DL":xs)  =  solve' k (l + 1) xs
    solve' k l (_ : xs)  =  solve' k l xs

main :: IO ()
main  =  do
    lines'  <-  liftM lines getContents
    let n  =  (read . head) lines'
    let xs  =  (take n . tail) lines'
    print $ solve n xs

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, OverloadedStrings #-}
{-# OPTIONS_GHC -O2 #-}

import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
--import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph

parseInput = do
    n <- readInt
    dir <- replicateM n readString
    let ul = length $ filter (=="UL") dir
    let ur = length $ filter (=="UR") dir
    let dl = length $ filter (=="DL") dir
    let dr = length $ filter (=="DR") dir
    let all = (n - ul - ur - dl - dr)
    return (ul, ur, dl, dr, all)
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

main = print =<< solve . evalState parseInput <$> BS.getContents

solve (ul, ur, dl, dr, all) = fromIntegral x * fromIntegral y :: Integer
  where
    x = 1 + ul + dr + all
    y = 1 + ur + dl + all

-- {{{ A minimal State Monad
class (Monad m) => MonadState s m | m -> s where
    get :: m s
    put :: s -> m ()

modify :: (MonadState s m) => (s -> s) -> m ()
modify f = do
    s <- get
    put (f s)

gets :: (MonadState s m) => (s -> a) -> m a
gets f = do
    s <- get
    return (f s)

newtype State s a = State { runState :: s -> (a, s) }

instance Functor (State s) where
    fmap f m = State $ \s -> let
        (a, s') = runState m s
        in (f a, s')

instance Applicative (State s) where
    pure = return
    (<*>) = ap

instance Monad (State s) where
    return a = State $ \s -> (a, s)
    m >>= k  = State $ \s -> let
        (a, s') = runState m s
        in runState (k a) s'

instance MonadState s (State s) where
    get   = State $ \s -> (s, s)
    put s = State $ \_ -> ((), s)

evalState :: State s a -> s -> a
evalState m s = fst (runState m s)

execState :: State s a -> s -> s
execState m s = snd (runState m s)

mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
mapState f m = State $ f . runState m

withState :: (s -> s) -> State s a -> State s a
withState f m = State $ runState m . f

state = State
-- }}}

import Data.List

parse :: String -> [String]
parse = tail . lines

solve :: [String] -> Integer
solve = loop (1, 1)

loop (a, b) [] = a * b
loop (a, b) ("UL":rest) = loop (a + 1, b) rest
loop (a, b) ("DR":rest) = loop (a + 1, b) rest
loop (a, b) ("UR":rest) = loop (a, b + 1) rest
loop (a, b) ("DL":rest) = loop (a, b + 1) rest
loop (a, b) ("ULDR":rest) = loop (a + 1, b + 1) rest

main = interact (show . solve . parse)
  -- stuff <- getContents
  -- print . solve . parse $ stuff

import CPUTime

solve :: [String] -> Integer
solve xs  =  solve' (1::Int) (1::Int) xs
  where
    solve' n m []  =  fromIntegral n * fromIntegral m
    solve' n m ("UL":xs)  =  solve' (succ n) m xs
    solve' n m ("UR":xs)  =  solve' n (succ m) xs
    solve' n m ("DR":xs)  =  solve' (succ n) m xs
    solve' n m ("DL":xs)  =  solve' n (succ m) xs
    solve' n m (_:xs)  =  solve' (succ n) (succ m) xs

main :: IO ()
main  =  do
    t0  <-  getCPUTime

    n  <-  readLn
    xs  <-  mapM (const getLine) [1..n]
    print $ solve xs

    t1 <- getCPUTime
    putStr "Time = "
    print (fromIntegral (t1 - t0) * 1e-12)


Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?

The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i < i$$$).  The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).

Print a single integer — the number of citizens the bandit will catch if both sides act optimally.

NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.

import Data.Array.ST.Safe
import Control.Monad.ST
import Control.Monad
import Data.Int

import qualified Data.ByteString.Lazy as R
import qualified Data.ByteString.Lazy.Char8 as P

type ByteString = P.ByteString

parseInts :: ByteString -> [Int]
parseInts s = [v | Just (v, _) <- map P.readInt $ P.words s]

ceilDiv :: Int64 -> Int64 -> Int64
ceilDiv n k = div (n + k - 1) k

newSTUArray :: (Int, Int) -> Int -> ST s (STUArray s Int Int)
newSTUArray = newArray

newSTUListArray :: (Int, Int) -> [Int] -> ST s (STUArray s Int Int)
newSTUListArray = newListArray

newSTUListArray64 :: (Int, Int) -> [Int64] -> ST s (STUArray s Int Int64)
newSTUListArray64 = newListArray

solve :: Int -> [Int] -> [Int] -> Int64
solve n pli ali = runST $ do
  p <- newSTUListArray (2, n) pli
  a <- newSTUListArray64 (1, n) $ map fromIntegral ali
  slc <- newSTUArray (1, n) 0 -- subtree leaf count
  constraints <- forM (reverse [2..n]) $ \ix -> do
    currPar <- readArray p ix
    currPop <- readArray a ix
    parPop <- readArray a currPar
    writeArray a currPar (currPop + parPop)
    currlc <- max 1 <$> readArray slc ix
    parlc <- readArray slc currPar
    writeArray slc currPar (currlc + parlc)
    pure $ ceilDiv currPop (fromIntegral currlc)
  rootConstraint <- do
    rootPop <- readArray a   1
    rootlc  <- readArray slc 1
    pure $ ceilDiv rootPop (fromIntegral rootlc)
  pure $ maximum (rootConstraint : constraints)

main :: IO ()
main = do
  [[n], p, a] <- map parseInts . P.lines <$> R.getContents
  print $ solve n p a


You are given a table $$$a$$$ of size $$$n \times m$$$. We will consider the table rows numbered from top to bottom from $$$1$$$ to $$$n$$$, and the columns numbered from left to right from $$$1$$$ to $$$m$$$. We will denote a cell that is in the $$$i$$$-th row and in the $$$j$$$-th column as $$$(i, j)$$$. In the cell $$$(i, j)$$$ there is written a number $$$(i - 1) \cdot m + j$$$, that is $$$a_{ij} = (i - 1) \cdot m + j$$$.A turtle initially stands in the cell $$$(1, 1)$$$ and it wants to come to the cell $$$(n, m)$$$. From the cell $$$(i, j)$$$ it can in one step go to one of the cells $$$(i + 1, j)$$$ or $$$(i, j + 1)$$$, if it exists. A path is a sequence of cells in which for every two adjacent in the sequence cells the following satisfies: the turtle can reach from the first cell to the second cell in one step. A cost of a path is the sum of numbers that are written in the cells of the path.  For example, with $$$n = 2$$$ and $$$m = 3$$$ the table will look as shown above. The turtle can take the following path: $$$(1, 1) \rightarrow (1, 2) \rightarrow (1, 3) \rightarrow (2, 3)$$$. The cost of such way is equal to $$$a_{11} + a_{12} + a_{13} + a_{23} = 12$$$. On the other hand, the paths $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (2, 1)$$$ and $$$(1, 1) \rightarrow (1, 3)$$$ are incorrect, because in the first path the turtle can't make a step $$$(2, 2) \rightarrow (2, 1)$$$, and in the second path it can't make a step $$$(1, 1) \rightarrow (1, 3)$$$.You are asked to tell the turtle a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$. Please note that the cells $$$(1, 1)$$$ and $$$(n, m)$$$ are a part of the way.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of test cases follows. A single line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^4$$$) — the number of rows and columns of the table $$$a$$$ respectively.

For each test case output a single integer — a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$.

NoteIn the first test case the only possible path consists of a single cell $$$(1, 1)$$$.The path with the minimal cost in the second test case is shown in the statement.In the fourth and the fifth test cases there is only one path from $$$(1, 1)$$$ to $$$(n, m)$$$. Both paths visit every cell in the table.

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language Safe                      #-}
{-# language ImportQualifiedPost       #-}
{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [n,m] <- ri
        return (n,m)
    mapM_ (putStrLn.show.solve) tcs

solve (n,m) = sum $ [1..m] ++ [2*m,3*m..n*m]

readLines :: Int -> IO [String]
readLines 0 = do
  return []
readLines n = do
  line <- getLine

  lines <- readLines (n - 1)

  return (line:lines)

writeLines :: Show a => [a] -> IO ()
writeLines [] = return ()
writeLines (line:rest) = do
  putStrLn (show line)
  writeLines rest

deserializeTestCases :: [String] -> [(Int, Int)]
deserializeTestCases = map deserializeItem

calculateAllSolutions :: [String] -> [Int]
calculateAllSolutions = (map calculateSolution) . deserializeTestCases

deserializeItem :: String -> (Int, Int)
deserializeItem = deserializeInternal . words

calculateSolution :: (Int, Int) -> Int
calculateSolution (n, m) = m*(m + 1) `div` 2 + (if n > 1 then (m*(n - 1)*(n + 2) `div` 2) else 0)

deserializeInternal :: [String] -> (Int, Int)
deserializeInternal (first:second:rest) = if length rest > 0 then error "Expected two values." else (read first :: Int, read second :: Int)
deserializeInternal _ = error "Wrong number of values."

main = do
  testCasesNumStr <- getLine

  let testCasesNum = read testCasesNumStr :: Int

  testCasesStr <- readLines testCasesNum

  let solutions = calculateAllSolutions testCasesStr

  writeLines solutions


Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!For example, if you provide $$$3$$$ red, $$$3$$$ green and $$$3$$$ blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.However, if you provide, say, $$$1$$$ red, $$$10$$$ green and $$$2$$$ blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of sets of lamps Polycarp has bought. Each of the next $$$t$$$ lines contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^9$$$) — the number of red, green and blue lamps in the set, respectively.

Print $$$t$$$ lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.

NoteThe first two sets are desribed in the statement.The third set produces garland "RBRG", for example.

import Control.Monad

solve :: [Int] -> String
solve l = if b then "Yes" else "No"
  where
    b = maximum l<=(1+(sum l - maximum l))

routine :: IO ()
routine = do
  l <-(map read . words) <$> getLine
  putStrLn $ solve l

main :: IO ()
main = do
  n <- readLn
  replicateM_ n routine

import Control.Monad
import Prelude

testCase = do
    line <- getLine
    putStrLn $ solution (map read (words line))

solution :: [Integer] -> String
solution [r, g, b] = result where
    mx = maximum [r, g, b]
    rest = r + g + b - mx
    result = case rest < (mx - 1) of
        True -> "No"
        False -> "Yes"

main = do
    testCases <- getLine
    strNums <- replicateM (read testCases) testCase
    return ()


Little Vlad is fond of popular computer game Bota-2. Recently, the developers announced the new add-on named Bota-3. Of course, Vlad immediately bought only to find out his computer is too old for the new game and needs to be updated.There are n video cards in the shop, the power of the i-th video card is equal to integer value ai. As Vlad wants to be sure the new game will work he wants to buy not one, but several video cards and unite their powers using the cutting-edge technology. To use this technology one of the cards is chosen as the leading one and other video cards are attached to it as secondary. For this new technology to work it's required that the power of each of the secondary video cards is divisible by the power of the leading video card. In order to achieve that the power of any secondary video card can be reduced to any integer value less or equal than the current power. However, the power of the leading video card should remain unchanged, i.e. it can't be reduced.Vlad has an infinite amount of money so he can buy any set of video cards. Help him determine which video cards he should buy such that after picking the leading video card and may be reducing some powers of others to make them work together he will get the maximum total value of video power.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of video cards in the shop. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 200 000) — powers of video cards.

The only line of the output should contain one integer value — the maximum possible total power of video cards working together.

NoteIn the first sample, it would be optimal to buy video cards with powers 3, 15 and 9. The video card with power 3 should be chosen as the leading one and all other video cards will be compatible with it. Thus, the total power would be 3 + 15 + 9 = 27. If he buys all the video cards and pick the one with the power 2 as the leading, the powers of all other video cards should be reduced by 1, thus the total power would be 2 + 2 + 14 + 8 = 26, that is less than 27. Please note, that it's not allowed to reduce the power of the leading video card, i.e. one can't get the total power 3 + 1 + 15 + 9 = 28.In the second sample, the optimal answer is to buy all video cards and pick the one with the power 2 as the leading. The video card with the power 7 needs it power to be reduced down to 6. The total power would be 8 + 2 + 2 + 6 = 18.

{-# LANGUAGE TupleSections #-}

import           Control.Applicative
import           Control.Monad
import           Data.Array.IArray
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8 as BS
import           Data.Int
import qualified Data.IntSet           as IntSet
import           Data.List             (sort, unfoldr)

aggregate::[Int]-> UArray Int Int64
aggregate nums = listArray (0, limit) $ go 0 0 sorted where
  sorted = sort nums
  limit = maximum nums
  go idx cnt (el:rest) | idx == el = go idx (cnt + 1) rest
                       | otherwise = cnt : go (idx + 1) cnt (el : rest)
  go _ cnt []                      = [cnt]

solution :: [Int] -> Int64
solution nums = result where
  result = maximum $ power <$> IntSet.toList (IntSet.fromList nums)
  limit = maximum nums
  sums   = aggregate nums
  rng i j = (sums ! (j - 1) ) - (sums ! (i - 1))
  rangePower x u = rng u (min (u + x) (limit + 1)) * fromIntegral u
  power x = sum $ fmap (rangePower x) [x, x + x..limit]

getInts::IO [Int]
getInts = fmap (unfoldr readOne) BS.getLine where
  readOne s = do
    (x , s') <- BS.readInt s
    return (x, BS.drop 1 s')

main::IO ()
main = do
  -- print $ solution [3,2,15,9]
  void BS.getLine
  xs <- getInts
  print $ solution xs

import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST.Safe
import Data.Array.Unboxed
import Data.Array.ST.Safe
import Data.Int
import Data.List
readInt s = let Just (a,_) = BS.readInt s in fromIntegral a

main = BS.interact $ BS.pack . show . solve . map readInt . tail . BS.words

solve ns = maximum $ map res $ unique ns
  where pref = build ns :: UArray Int64 Int64
        (ml, mr) = bounds pref
        getsum l r
          | pl > ml = (pref ! pr) - (pref ! (pl - 1))
          | otherwise = pref ! pr
          where pl = max l ml
                pr = min r mr
        res base = sum [i * (getsum i $ i + base - 1) | i <- [base, 2 * base .. mr]]

build ns = runSTUArray $ do
  let l = minimum ns
      r = maximum ns
  a <- newArray (l, r) 0 :: ST s (STUArray s Int64 Int64)
  forM_ ns $ \n -> do
    v <- readArray a n
    writeArray a n $ v + 1
  forM_ [l + 1..r] $ \i -> do
    ni <- readArray a i
    np <- readArray a $ i - 1
    writeArray a i $ ni + np
  return a

unique ns = unique_ sorted
    where sorted = sort ns
          unique_ [] = []
          unique_ a@[_] = a
          unique_ (a:b:r)
            | a == b = unique_ (b:r)
            | otherwise = a : unique_ (b:r)

{-# LANGUAGE TupleSections #-}

import           Control.Applicative
import           Control.Monad
import qualified Data.ByteString.Char8 as BS
import qualified Data.IntMap           as IntMap
import           Data.List             (unfoldr)

solution :: [Int] -> Int
solution nums = result where
  result = maximum $ power <$> IntMap.keys sums
  limit = maximum nums
  counts = IntMap.fromListWith (+) $ fmap (, 1:: Int)  nums
  sums   = IntMap.fromAscList $ tail $ scanl collect (undefined,0)  $ IntMap.toAscList counts
  collect (_, acc) (i, x ) = (i, x + acc)
  upTo = maybe 0 snd . flip IntMap.lookupLE sums
  range i j = upTo (j - 1) - upTo (i - 1)
  rangePower x u = range u (u + x) *  u
  power x = sum $ fmap (rangePower x) [x, x + x..limit]

getInts::IO [Int]
getInts = fmap (unfoldr readOne) BS.getLine where
  readOne s = do
    (x , s') <- BS.readInt s
    return (x, BS.drop 1 s')

main::IO ()
main = do
  void BS.getLine
  xs <- getInts
  print $ solution xs

import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST.Safe
import Data.Array
import Data.Array.ST.Safe
readInt s = let Just (a,_) = BS.readInt s in a

main = BS.interact $ BS.pack . show . solve . map readInt . tail . BS.words

solve ns = maximum $ map res ns
  where pref = prefs $ build ns :: Array Int Int
        (ml, mr) = bounds pref
        getsum l r
          | pl > ml = (pref ! pr) - (pref ! (pl - 1))
          | otherwise = pref ! pr
          where pl = max l ml
                pr = min r mr
        res base = sum [i * (getsum i $ i + base - 1) | i <- [base, 2 * base .. mr]]

build ns = runSTArray $ do
  a <- newArray (minimum ns, maximum ns) 0
  forM_ ns $ \n -> do
    v <- readArray a n
    writeArray a n $ v + 1
  return a

prefs a = let p = listArray (l, r) $ (a ! l) : [(p ! (i - 1)) + (a ! i) | i <- [l + 1..r]]
          in p
  where (l, r) = bounds a


Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...The string $$$s$$$ he found is a binary string of length $$$n$$$ (i. e. string consists only of 0-s and 1-s).In one move he can choose two consecutive characters $$$s_i$$$ and $$$s_{i+1}$$$, and if $$$s_i$$$ is 1 and $$$s_{i + 1}$$$ is 0, he can erase exactly one of them (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing.Lee can make an arbitrary number of moves (possibly zero) and he'd like to make the string $$$s$$$ as clean as possible. He thinks for two different strings $$$x$$$ and $$$y$$$, the shorter string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner.Now you should answer $$$t$$$ test cases: for the $$$i$$$-th test case, print the cleanest possible string that Lee can get by doing some number of moves.Small reminder: if we have two strings $$$x$$$ and $$$y$$$ of the same length then $$$x$$$ is lexicographically smaller than $$$y$$$ if there is a position $$$i$$$ such that $$$x_1 = y_1$$$, $$$x_2 = y_2$$$,..., $$$x_{i - 1} = y_{i - 1}$$$ and $$$x_i < y_i$$$.

The first line contains the integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases.  Next $$$2t$$$ lines contain test cases — one per two lines. The first line of each test case contains the integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The second line contains the binary string $$$s$$$. The string $$$s$$$ is a string of length $$$n$$$ which consists only of zeroes and ones. It's guaranteed that sum of $$$n$$$ over test cases doesn't exceed $$$10^5$$$.

Print $$$t$$$ answers — one per test case. The answer to the $$$i$$$-th test case is the cleanest string Lee can get after doing some number of moves (possibly zero).

NoteIn the first test case, Lee can't perform any moves.In the second test case, Lee should erase $$$s_2$$$.In the third test case, Lee can make moves, for example, in the following order: 11001101 $$$\rightarrow$$$ 1100101 $$$\rightarrow$$$ 110101 $$$\rightarrow$$$ 10101 $$$\rightarrow$$$ 1101 $$$\rightarrow$$$ 101 $$$\rightarrow$$$ 01.

import Control.Monad

main = do
  t <- read <$> getLine
  replicateM t routine

routine = do
  _ <- getLine
  s <- getLine
  let l = takeWhile (== '0') s
  let r = takeWhile (== '1') $ reverse s
  let rest =
        if (length l + length r == length s)
          then ""
          else "0"
  putStrLn (l ++ rest ++ r)

solve :: String -> String
solve line = let
    len = length line
    countZero = length $ takeWhile (=='0') line
    countOnes = length $ takeWhile (=='1') $ reverse line
    begin = take countZero $ repeat '0'
    end = take countOnes $ repeat '1'
    middle = if len == (countOnes+countZero) then [] else ['0']
    in begin++middle++end

getInt::IO Integer
getInt=do
    line <- getLine
    let i = read line :: Integer
    return (i)

main :: IO ()
main = do
    t <- getInt
    for t where
        for 0 = return ()
        for t = do
            _ <- getInt
            line <- getLine
            putStrLn $ solve line
            for (t-1)

skip :: [a] -> [a]
skip [] = []
skip (x : []) = [x]
skip (x1 : (x2 : xs)) = x1 : (skip xs)

pref :: Char -> String -> String
pref _ "" = ""
pref d (c : cs)
  | c == d = c : (pref d cs)
  | otherwise = ""

suff :: Char -> String -> String
suff c s = pref c $ reverse s

solve :: String -> String
solve s
  | length (pref '0' s ++ (suff '1' s)) == length s = s
  | otherwise = pref '0' s ++ "0" ++ (suff '1' s)

io :: String -> String
io s = unlines $ map solve $ skip $ drop 2 $ lines s

main :: IO ()
main = do
  interact io

import Control.Monad (replicateM_)
main = readLn >>= flip replicateM_ ioSolve

ioSolve :: IO ()
ioSolve = getLine >> getLine >>= putStrLn . solve

solve :: String -> String
solve s = a ++ x ++ b where
  (a,s') = span (=='0') s
  (b,s'') = span (=='1') $ reverse s'
  x = if null s'' then "" else "0"

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}

import Data.List
import Data.Tuple

_split acc "" [] = reverse acc
_split acc curr [] = reverse $ reverse curr : acc
_split acc curr (ch:rest)
  | (any (== ch) [' ', '\n']) = _split (reverse curr : acc) "" rest
  | otherwise = _split acc (ch:curr) rest

split = _split [] ""

(|>) = flip ($)

readInt = read :: String -> Int

reduce [] = []
reduce [x] = [x]
reduce ('1':'0':'0':xs) = reduce ('1':'0':xs)
reduce ('1':'0':xs) = '0':xs
reduce ls = ls

solve [] = []
solve (x:xs) =
  let sub = solve xs
  in reduce $ x:sub

main = do
  input <- getContents
  let _:tokens = split input
      res = tokens |> unfoldr (\case
        []  -> Nothing
        _:str:rest  -> Just (solve str, rest)
        )
  sequence $ putStrLn <$> res

import Data.List
main = interact $ unlines . map (process . snd) . filter (odd . fst) . zip [0..] . tail . lines
process s = process' s x y
    where
        x = elemIndices '1' s
        y = elemIndices '0' s
process' s _ [] = s
process' s [] _ = s
process' s x y = process'' s (head x) (last y)
process'' s x y
    | x > y = s
    | otherwise = (take x s) ++ (drop y s)

skip :: [a] -> [a]
skip [] = []
skip (x : []) = [x]
skip (x1 : (x2 : xs)) = x1 : (skip xs)

pref :: Char -> String -> String
pref _ "" = ""
pref d (c : cs)
  | c == d = c : (pref d cs)
  | otherwise = ""

suff :: Char -> String -> String
suff c s = pref c $ reverse s

solve :: String -> String
solve s
  | length (pref '0' s ++ (suff '1' s)) == length s = s
  | otherwise = pref '0' s ++ "1" ++ (suff '1' s)

io :: String -> String
io s = unlines $ map solve $ skip $ drop 2 $ lines s

main :: IO ()
main = do
  interact io


Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.

The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.

In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them.

NoteIn the first example the only network is shown on the left picture.In the second example one of optimal networks is shown on the right picture.Exit-nodes are highlighted.

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Char8 as B

showB :: Show a => a -> B.ByteString
showB = B.pack . show

main = do
  [n, k] <- fmap readInts B.getLine
  let (q, r) = n `quotRem` k
  print $ if k == 2 && r == 0 then 2 * (q - 1) + 1 else 2 * (q + fromEnum (r > 2)) + fromEnum (r == 2)
  sequence_ [B.putStrLn $ showB i `B.append` " " `B.append` showB (max 1 (i - k)) | i <- [2..n]]

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Char8 as B

main = do
  [n, k] <- fmap readInts B.getLine
  let (q, r) = n `quotRem` k
  print $ if k == 2 && r == 0 then 2 * (q - 1) + 1 else 2 * (q + fromEnum (r > 2)) + fromEnum (r == 2)
  sequence_ [putStrLn $ show i ++ " " ++ show (max 1 (i - k)) | i <- [2..n]]

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Char8 as B

main = do
  [n, k] <- fmap readInts B.getLine
  let (q, r) = n `quotRem` k
  print $ if r == 0 then 2 * (q - 1) + fromEnum (k == 2) else 2 * q + r - 1
  sequence_ [putStrLn $ show i ++ " " ++ show (max 1 (i - k)) | i <- [2..n]]

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Char8 as B

main = do
  [n, k] <- fmap readInts B.getLine
  let (q, r) = n `quotRem` k
  print $ if k == 2 && r == 0 then 2 * (q - 1) + 1 else 2 * q + max 0 (r - 1)
  sequence_ [putStrLn $ show i ++ " " ++ show (max 1 (i - k)) | i <- [2..n]]

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words


Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you.Let's assume that S(n) is the sum of digits of number n, for example, S(4098) = 4 + 0 + 9 + 8 = 21. Then the digital root of number n equals to:   dr(n) = S(n), if S(n) < 10;  dr(n) = dr( S(n) ), if S(n) ≥ 10. For example, dr(4098)  =  dr(21)  =  3.Vasya is afraid of large numbers, so the numbers he works with are at most 101000. For all such numbers, he has proved that dr(n)  =  S( S( S( S(n) ) ) ) (n ≤ 101000).Now Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. You task is, given numbers k and d, find the number consisting of exactly k digits (the leading zeroes are not allowed), with digital root equal to d, or else state that such number does not exist.

The first line contains two integers k and d (1 ≤ k ≤ 1000; 0 ≤ d ≤ 9).

In a single line print either any number that meets the requirements (without the leading zeroes) or "No solution" (without the quotes), if the corresponding number does not exist. The chosen number must consist of exactly k digits. We assume that number 0 doesn't contain any leading zeroes.

NoteFor the first test sample dr(5881)  =  dr(22)  =  4.For the second test sample dr(36172)  =  dr(19)  =  dr(10)  =  1.

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import Text.Printf

main = do
	[ k, d ] <- map read . words <$> getLine
	putStrLn $ if d == 0 && 1 < k
		then "No solution"
		else show d ++ replicate ( k - 1 ) '0'

import Control.Applicative
main :: IO ()
main = do
    inp <- map read <$> words <$> getLine
    let k = inp !! 0
        d = inp !! 1
    if d == 0 && k > 1
        then putStrLn $ "No solution"
        else putStrLn $ show d ++ replicate (k-1) '0'

import Data.Functor

main = do
     [k,d] <- (map read) <$> (words <$> getLine) :: IO [Int]
     putStrLn $ solve k d
     return ()

solve k d
      | 1<k && d==0 = "No solution"
      | otherwise   = show d ++ replicate (k-1) '0'

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array.IArray
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Array.IO.Safe
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

getInts = fmap (map read . words) getLine
-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

main = do
  [k, d] <- getInts
  putStrLn $ if d == 0 && k /= 1 then "No solution" else show d ++ replicate (k-1) '0'

import Data.Char

solve :: Int -> Int -> String

solve d k = (replicate (k-1) '1')  ++ [ intToDigit d0 ]
  where d0 = head [ d0 | d0 <- [0..9], dr ((k-1)+d0) == d ]

dr :: (Show a, Integral a) => a -> Int
dr n | n < 10 = fromIntegral n
     | otherwise = dr $ sum $ map digitToInt $ show n

test d k = let n = solve d k in dr ((read n) :: Integer) == d

testAll = all (uncurry test) [ (d,k) | k <-  [1..1000], d <- [1..9] ]

solve' 0 1 = Just "0"
solve' 0 _ = Nothing
solve' d k = Just $ solve d k

main = do
  (k:d:_) <- fmap (map read . words) getLine
  case solve' d k of
    Nothing -> putStrLn "No solution"
    Just n  -> putStrLn n

import Control.Monad (liftM)
import Data.Char (ord)
import Data.List (intercalate)

solve :: [Int] -> String
solve [1, 0]  =  "0"
solve [_, 0]  =  "No solution"
solve [k, d]  =  show d ++ replicate (k-1) '0'

main :: IO ()
main  =  reads >>= putStrLn . solve

  where
    reads :: Num a => IO [a]
    reads  =  liftM (map read . words) getLine
      where
        read ('-':s)  =  (-1) * read s
        read s  =  read' 0 s
        read' a ""  =  a
        read' a (c:s)  =  read' (10 * a + fromIntegral (ord c - ord '0')) s

    prints :: Show a => [a] -> IO ()
    prints  =  putStrLn . intercalate " " . map show

#!/usr/bin/env runghc
import Data.List
main = do
  c <- getContents
  putStr . unlines . solve . lines $ c

solve::[String]->[String]
solve [] = []
solve (kd:cs) = (if k<2 || d/=0 then (replicate m (head $ show (n+1)) ++ replicate (k-m) (head $ show n)) else "No solution"): solve cs
  where
    [k,d] = map read . words $ kd
    (n,m) = d `divMod` k

minNum k n
	| n == 0 && k == 1 = 0
	| n == 0 = -1
	| otherwise = (10 ^ (k-1) ) + (n-1)

find x
	| x>=0  = show x
	| otherwise = "No solution"

parse l = map read $ words l

cal fn kn = fn (head kn) (head $ tail kn)

main = do
	l <- getLine
	putStr $ find $ cal minNum $ parse l

import Control.Applicative
main :: IO ()
main = do
    inp <- map read <$> words <$> getLine
    let k = inp !! 0
        d = inp !! 1
    if d == 0 || k > 1
        then putStrLn $ "No solution"
        else putStrLn $ show d ++ replicate (k-1) '0'

import Control.Applicative
main :: IO ()
main = do
    inp <- map read <$> words <$> getLine
    let k = inp !! 0
        d = inp !! 1
    if d == 0
        then print 0
        else putStrLn $ show d ++ replicate (k-1) '0'

import Control.Applicative
main :: IO ()
main = do
    inp <- map read <$> words <$> getLine
    let k = inp !! 0
        d = inp !! 1
    if d == 0
        then putStrLn $ "No solution"
        else putStrLn $ show d ++ replicate (k-1) '0'

import Control.Applicative
main :: IO ()
main = do
    inp <- map read <$> words <$> getLine
    let k = inp !! 0
        d = inp !! 1
    putStrLn $ show d ++ replicate (k-1) '0'

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array.IArray
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Array.IO.Safe
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

getInts = fmap (map read . words) getLine
-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

main = do
  [k, d] <- getInts
  putStrLn $ show d ++ replicate (k-1) '0'

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array.IArray
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Array.IO.Safe
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

getInts = fmap (map read . words) getLine
-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

main = do
  [k, d] <- getInts
  putStrLn $ if d == 0 then "No solution" else show d ++ replicate (k-1) '0'

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array.IArray
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Array.IO.Safe
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

getInts = fmap (map read . words) getLine
-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

main = do
  [k, d] <- getInts
  putStrLn $ if d == 0 then show 0 else show d ++ replicate (k-1) '0'

#!/usr/bin/env runghc
import Data.List
main = do
  c <- getContents
  putStr . unlines . solve . lines $ c

solve::[String]->[String]
solve [] = []
solve (kd:cs) = (replicate m (head $ show (n+1)) ++ replicate (k-m) (head $ show n)): solve cs
  where
    [k,d] = map read . words $ kd
    (n,m) = (if k<2 || d/=0 then d else 10) `divMod` k

#!/usr/bin/env runghc
import Data.List
main = do
  c <- getContents
  putStr . unlines . solve . lines $ c

solve::[String]->[String]
solve [] = []
solve (kd:cs) = (replicate m (head $ show (n+1)) ++ replicate (k-m) (head $ show n)): solve cs
  where
    [k,d] = map read . words $ kd
    (n,m) = d `divMod` k

import Data.Char
sum' [] = 0
sum' (x:xs) = (digitToInt x) + (sum' xs)

dr n
	| s<10 =  s
	| otherwise = dr s
	where s = sum' $ show n

rg n = [10 ^ (n-1) .. 10^n]

minNum k n = filter (\x -> (dr x) == n) $ rg k

find [] = "No solution"
find (x:_) = show x

parse l = map read $ words l

cal fn kn = fn (head kn) (head $ tail kn)

main = do
	l <- getLine
	print $ find $ cal minNum $ parse l