import Data.Int
import Control.Monad

main :: IO ()
main = do
  t <- fmap read getLine
  replicateM_ t $ do
    [a, b] <- map read . words <$> getLine
    let
      f :: (Int64, Int64) -> Int64 -> Int64
      f (0, _) _ = 0
      f (x, y) c = 1 + f (x `div` (y + c), y) c
      solve :: Int64 -> Int64 -> Int64
      solve low high
        | high - low < 10 = fst $ minimum $ zip (map g [low .. high]) [low .. high]
        | g m1 <= g m2 = solve low m2
        | otherwise = solve m1 high
        where
        m1 = low + (high - low) * 1 `div` 3
        m2 = low + (high - low) * 2 `div` 3
        g x = x + f (a, b) x
    putStrLn $ show $ solve (if b == 1 then 1 else 0) 10000000000

{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,
    ConstraintKinds, BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.Array
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.Int
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import Data.Ratio
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Traversable
import System.IO

------

type Hopper r = State [r]

type HopperT r = StateT [r]

runHopper :: Hopper r a -> [r] -> (a, [r])
runHopper = runState

evalHopper :: Hopper r a -> [r] -> a
evalHopper = evalState

runHopperT :: HopperT r m a -> [r] -> m (a, [r])
runHopperT = runStateT

evalHopperT :: Monad m => HopperT r m a -> [r] -> m a
evalHopperT = evalStateT

type MonadHopper r m = MonadState [r] m

pop :: MonadHopper r m => m (Maybe r)
pop = state f
  where
    f :: [r] -> (Maybe r, [r])
    f [] = (Nothing, [])
    f (q:qs) = (Just q, qs)

popJust :: MonadHopper r m => m r
popJust = fromJust <$> pop

------

popInt :: MonadHopper B.ByteString m => m Int
popInt = fst . fromJust . B.readInt <$> popJust

popInts :: MonadHopper B.ByteString m => m [Int]
popInts = map (fst . fromJust . B.readInt) . B.words <$> popJust

popInteger :: MonadHopper B.ByteString m => m Integer
popInteger = fst . fromJust . B.readInteger <$> popJust

popIntegers :: MonadHopper B.ByteString m => m [Integer]
popIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust

------

dropCR :: B.ByteString -> B.ByteString
dropCR s | not (B.null s) && B.last s == '\r' = B.init s
         | otherwise = s

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

main = B.interact go
  where
    go :: B.ByteString -> B.ByteString
    go = evalHopper run . map dropCR . B.lines

------

run :: Hopper B.ByteString B.ByteString
run = do
  t <- popInt
  B.unlines <$> replicateM t run1

run1 = do
  ~[a, b] <- popInts
  return $ bshow (solve (fromIntegral a) (fromIntegral b))

solve :: Int64 -> Int64 -> Int64
solve a 1 = solve a 2 + 1
solve a b
  | a < b = 1
  | a < b ^ 2 = 2
  | otherwise = minimum $ map (\(i, b') -> i + f b') $ zip [0..] $
                takeWhile (\b' -> a >= (b' - 1) ^ 2) [b..]

  where
    f b' = head $ dropWhile (\i -> a >= b' ^ i) $ [2..]

{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,
    ConstraintKinds, BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.Array
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import Data.Ratio
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Traversable
import System.IO

------

type Hopper r = State [r]

type HopperT r = StateT [r]

runHopper :: Hopper r a -> [r] -> (a, [r])
runHopper = runState

evalHopper :: Hopper r a -> [r] -> a
evalHopper = evalState

runHopperT :: HopperT r m a -> [r] -> m (a, [r])
runHopperT = runStateT

evalHopperT :: Monad m => HopperT r m a -> [r] -> m a
evalHopperT = evalStateT

type MonadHopper r m = MonadState [r] m

pop :: MonadHopper r m => m (Maybe r)
pop = state f
  where
    f :: [r] -> (Maybe r, [r])
    f [] = (Nothing, [])
    f (q:qs) = (Just q, qs)

popJust :: MonadHopper r m => m r
popJust = fromJust <$> pop

------

popInt :: MonadHopper B.ByteString m => m Int
popInt = fst . fromJust . B.readInt <$> popJust

popInts :: MonadHopper B.ByteString m => m [Int]
popInts = map (fst . fromJust . B.readInt) . B.words <$> popJust

popInteger :: MonadHopper B.ByteString m => m Integer
popInteger = fst . fromJust . B.readInteger <$> popJust

popIntegers :: MonadHopper B.ByteString m => m [Integer]
popIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust

------

dropCR :: B.ByteString -> B.ByteString
dropCR s | not (B.null s) && B.last s == '\r' = B.init s
         | otherwise = s

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

main = B.interact go
  where
    go :: B.ByteString -> B.ByteString
    go = evalHopper run . map dropCR . B.lines

------

run :: Hopper B.ByteString B.ByteString
run = do
  t <- popInt
  B.unlines <$> replicateM t run1

run1 = do
  ~[a, b] <- popIntegers
  return $ bshow (solve a b)

solve a 1 = solve a 2 + 1
solve a b
  | a < b = 1
  | a < b ^ 2 = 2
  | otherwise = minimum $ map (\(i, b') -> i + f b') $ zip [0..] $
                takeWhile (\b' -> a >= (b' - 1) ^ 2) [b..]

  where
    f b' = head $ dropWhile (\i -> a >= b' ^ i) $ [2..]

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder as B
import System.IO

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.List
import Data.Semigroup

type SIO = StateT P.ByteString IO

steps :: Int -> Int -> Int
steps = let
  go k 0 _ = k
  go _ _ 1 = maxBound
  go k p q = let k' = k+1  in  k' `seq` go k' (quot p q) q
  in  go 0

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [a, b] <- readInts
    let
      opts = zipWith (\x y -> steps a x + y) [b..] [0..]
      ans = head [x | (x, y) <- zip opts $ tail opts, x < y]
    putInts [ans]

readLine :: SIO P.ByteString
readLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put $ P.dropWhile (<= '\r') next
  pure out

readInts :: SIO [Int]
readInts = do
  currLine <- readLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

putInts :: [Int] -> SIO ()
putInts li = let
  outBuilder = foldr (<>) (B.char7 '\n')
    $ intersperse (B.char7 ' ') (map B.intDec li)
  in  lift $ B.hPutBuilder stdout outBuilder


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

module Main where

--import Debug.Trace

import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Maybe
import Data.Either
import Data.Ord
import qualified Data.Foldable as Foldable
import Data.Char
import Data.List
import Data.Array.IArray
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA
import qualified Data.Array.IO.Safe as IA
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet

getWords  = words <$> getLine :: IO [String]
getInts   = map read <$> getWords :: IO [Int]
getDoubles = map read <$> getWords :: IO [Double]
getInt    = read <$> getLine :: IO Int
getDouble  = read <$> getLine :: IO Double
printLines :: Show a => [a] -> IO ()
printLines = mapM_ print
printStrs = mapM_ putStrLn :: [String] -> IO ()

---- Answer Code Section ----

process :: [Int] -> Int
process students = maximum teamCnts where
    n = length students
    studentsArr = listArray (1, n) $ sort students :: Array Int Int
    teamCnts = map snd $ scanl foldFn (1, 0) [1..n]
    foldFn (i, _) j = (i', j - i' + 1) where
        x = studentsArr ! j
        i' = until (\_i -> (studentsArr ! _i) >= x-5) (+ 1) i

main = do
    n <- getInt
    students <- getInts
    print $ process students

{-# LANGUAGE Safe #-}
{-# Options_GHC -O3 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Char
import Data.Array.Unboxed
import qualified Data.Sequence as S
import Data.Foldable
import Data.List

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

test :: Int -> [Int] -> Int
test n = f . listArray (0, n - 1) . toList . S.unstableSort . S.fromList
  where
    f :: UArray Int Int -> Int
    f arr = loop 0 0 minBound
      where
        loop i j r
          | i >= n = r
          | otherwise = loop (succ i) j' (max r (j' - i))
          where j' = until (\k -> k >= n || ((arr ! k) > (arr ! i) + 5)) succ j

main = do
  s <- C.getContents
  let (n:a) = map ru $ C.words s
  print $ test n $ take n a

{-# LANGUAGE Safe #-}
{-# Options_GHC -O3 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Char
import Data.Int
import Data.Array.Unboxed
import qualified Data.Sequence as S
import Data.Foldable
import Data.List

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

e x y = abs (x - y) <= 5

test :: Int -> [Int] -> Int
test n = maximum . map length . groupBy e . toList . S.unstableSort . S.fromList

main = do
  s <- C.getContents
  let (n:a) = map ru $ C.words s
  print $ test n $ take n a


gs' :: [Integer] -> Integer -> Integer -> Integer
gs' [] curr ans = max curr ans
gs' (x:xs) curr ans = if x+curr >= x
                      then gs' xs (x+curr) (max (x+curr) ans)
                      else gs' xs x (max x ans)

gs :: [Integer] -> Integer
gs [] = 0
gs (x:xs) = gs' xs x x

parse :: [String] -> String
parse [_, input] = if sum' > ans then "YES" else "NO"
  where numbers = stringToIntegerArray input
        ans = max (gs $ tail numbers) (gs $ init numbers)
        sum' = sum numbers

main :: IO ()
main = interact (unlines . map parse . groupByNLines 2 . tail . lines)

-- helpers

groupByNLines :: Int -> [String] -> [[String]]
groupByNLines _ [] = []
groupByNLines n strings = (take n strings):(groupByNLines n (drop n strings))

stringToIntegerArray :: String -> [Integer]
stringToIntegerArray = map (\x -> read x :: Integer) . words

maxSum []     _ acc = acc
maxSum (x:xs) soFar acc = maxSum xs soFar' acc'
  where soFar' = max (soFar + x) 0
        acc'   = max soFar' acc

process :: Int -> IO ()
process _ = do
  l <- map read . words <$> (getLine >> getLine)
  let ans = max (maxSum (tail l) 0 0) (maxSum (init l) 0 0)
  putStrLn $ if sum l > ans then "YES" else "NO"

main :: IO ()
main = (enumFromTo 1 . read <$> getLine) >>= mapM_ process

{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}

main = getLine >>= process.read

process 0 = return ()
process n = do
	getLine
	as <- map read.words <$> getLine
	if any (<= 0) (scanl1 (+) as) || any (<= 0) (scanl1 (+) $ reverse as)
		then putStrLn "NO"
		else putStrLn "YES"
	process $ n - 1

import Control.Monad
import Data.Foldable

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

routine :: IO ()
routine = do
  _ <- getLine
  l <- (map read.words) <$> getLine
  putStrLn $ if solve l
    then "NO"
    else "YES"

solve :: [Integer] -> Bool
solve l = solve' l || solve' (reverse l)

solve' :: [Integer] -> Bool
solve' (x:xs) =
  case foldUntill (<=0) (+) x xs of
    Left _ -> True
    Right _ -> False

foldUntill :: Foldable t => (b -> Bool)-> (b -> a -> b) -> b -> t a -> Either (b,Maybe b,Maybe a) b
foldUntill predicate binary accumulator foldable =
  if predicate accumulator
    then Left (accumulator,Nothing,Nothing)
    else foldlM f accumulator foldable
  where
    f acc val =
      let
        newValue = binary acc val
        bool = predicate newValue
      in
        if bool
          then Left (newValue,Just acc,Just val)
          else Right newValue

{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}

main = getLine >>= process.read

process 0 = return ()
process n = do
	getLine
	as <- map read.words <$> getLine
	if any (<= 0) (scanl (+) 0 as) || any (<= 0) (scanl (+) 0 $ reverse as)
		then putStrLn "NO"
		else putStrLn "YES"
	process $ n - 1

import Control.Monad
import Data.Foldable

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

routine :: IO ()
routine = do
  _ <- getLine
  l <- (map read.words) <$> getLine
  putStrLn $ if solve l
    then "NO"
    else "YES"

solve :: [Int] -> Bool
solve l = solve' l || solve' (reverse l)

solve' :: [Int] -> Bool
solve' (x:xs) =
  case foldUntill (<=0) (+) x xs of
    Left _ -> True
    Right _ -> False

foldUntill :: Foldable t => (b -> Bool)-> (b -> a -> b) -> b -> t a -> Either (b,Maybe b,Maybe a) b
foldUntill predicate binary accumulator foldable =
  if predicate accumulator
    then Left (accumulator,Nothing,Nothing)
    else foldlM f accumulator foldable
  where
    f acc val =
      let
        newValue = binary acc val
        bool = predicate newValue
      in
        if bool
          then Left (newValue,Just acc,Just val)
          else Right newValue

gs' :: [Int] -> Int -> Int -> Int
gs' [] curr ans = max curr ans
gs' (x:xs) curr ans = if x+curr >= x
                      then gs' xs (x+curr) (max (x+curr) ans)
                      else gs' xs x (max x ans)

gs :: [Int] -> Int
gs [] = 0
gs (x:xs) = gs' xs x x

parse :: [String] -> String
parse [_, input] = if sum' > ans then "YES" else "NO"
  where numbers = stringToIntegerArray input
        ans = max (gs $ tail numbers) (gs $ init numbers)
        sum' = sum numbers

main :: IO ()
main = interact (unlines . map parse . groupByNLines 2 . tail . lines)

-- helpers

groupByNLines :: Int -> [String] -> [[String]]
groupByNLines _ [] = []
groupByNLines n strings = (take n strings):(groupByNLines n (drop n strings))

stringToIntegerArray :: String -> [Int]
stringToIntegerArray = map (\x -> read x :: Int) . words


import Data.Functor ((<$>))
import Data.List (intercalate)

main :: IO ()
main = getLine >>= putStrLn . maybe "No solution" (intercalate ",") . solve

solve :: String -> Maybe [String]
solve xs | null xs = Just []
         | null ys || all (=='@') (take 2 zs) = Nothing
         | '@' `notElem` tail zs = Just [ xs ]
         | otherwise = ((ys ++ take 2 zs):) <$> solve (drop 2 zs)
  where (ys, zs) = break (=='@') xs

import Control.Monad(guard)
main = do
  s <- getLine
  case solve s of
    Nothing -> putStrLn "No solution"
    Just r  -> putStrLn r

solve ('@':_) = Nothing
solve s | last s == '@' = Nothing
solve s =
  do
  let strings = lines . map f $ s
      first = head strings
      lst   = last strings
      mids  = tail . init $ strings
      f '@' = '\n'
      f x   = x
      insert (c:s) = c:',':s
  guard $ length strings > 1
  guard $ all ((>1) . length) mids
  Just $ first ++
           (concatMap ('@':) . map insert $ mids) ++
           "@" ++ lst

import Data.Maybe

email_recovery' [] = Just []
email_recovery' ('@':_) = Nothing
email_recovery' (x:'@':'@':_) = Nothing
email_recovery' (x:'@':y:xs) = (email_recovery' xs) >>= (\a -> Just (',':x:'@':y:a))
email_recovery' (x:xs) = (email_recovery' xs) >>= (\a -> Just (x : a))

email_recovery'' [] = Nothing
email_recovery'' ('@':_) = Nothing
email_recovery'' (x:'@':xs) = (email_recovery' (x:'@':xs)) >>= (\a -> Just(tail a))
email_recovery'' (x:xs) = (email_recovery'' xs) >>= (\a -> Just (x : a))

erec [] = ""
erec x = if isNothing result then "No solution"
         else fromJust (result)
         where result = email_recovery'' x

main = do
  inpStr <- getLine
  putStrLn (erec inpStr)

--  31B

import Data.List (intercalate)
import Maybe (fromMaybe)

check  =  const True

solve :: String -> Maybe String
solve xs
  | null res  =  Nothing
  | otherwise  =  Just (intercalate "," res)
  where
    res  =  before "" [] xs
    before start acc []
      | null start  =  acc
      | otherwise  =  []
    before start acc ('@':s)
      | null start  =  []
      | otherwise  =  after start "" acc s
    before start acc (c:s)  =  before (start ++ [c]) acc s
    after begin end acc []
      | null end  =  []
      | otherwise  =  acc ++ [begin ++ "@" ++ end]
    after begin end acc ('@':s)  =  []
    after begin end acc (c:'@':s)
      | null end  =  []
      | otherwise  =  before [c] (acc ++ [begin ++ "@" ++ end]) ('@':s)
    after begin end acc (c:s)  =  after begin (end ++ [c]) acc s

main :: IO ()
main  =  getLine >>= putStrLn . fromMaybe "No solution" . solve

import Data.Functor ((<$>))
import Data.List (intercalate)

main :: IO ()
main = getLine >>= putStrLn . maybe "No solution" (intercalate ",") . solve

solve :: String -> Maybe [String]
solve xs | null xs = Just []
         | null ys || all (=='@') (take 2 zs) = Nothing
         | '@' `notElem` tail zs = Just [ xs ]
         | otherwise = (:) (ys ++ take 2 zs) <$> solve (drop 2 zs)
  where (ys, zs) = break (=='@') xs

import Data.List
import Data.Functor
main=getLine>>=putStrLn.maybe"No solution"(intercalate",").f
f x|null x=Just[]|null y||all(=='@')(take 2 z)=Nothing|'@'`notElem`tail z=Just[x]|1>0=(:)(y++take 2 z)<$>f(drop 2 z)where(y,z)=break(=='@')x

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

main :: IO ()
main = do
  let split s = do
        let (as, s1) = span (/= '@') s
            (atMark, s2) = splitAt 1 s1
            (bs, s') = span (/= '@') s2
        case () of
          _ | null as                 -> Nothing
            | atMark /= "@"           -> Nothing
            | null s'                 -> if null bs then Nothing else Just $ as ++ "@" ++ bs
            | null bs                 -> Nothing
            | head bs == '@'          -> Nothing
            | length (take 2 bs) /= 2 -> Nothing
            | otherwise               -> do
                let (bs1, bs2) = splitAt (length bs - 1) bs
                    cs = as ++ "@" ++ bs1 ++ ","
                fmap (cs ++) $ split (bs2 ++ s')
      no = putStrLn ""
  m <- split <$> getLine
  putStrLn $ maybe "No solution" id m

main = interact (ans)
ans theInput = answer address where
	address = split $ head $ lines theInput
	split xs = if y==	[] then [xs] else x:(split $ tail y) where
		(x,y) = break (=='@') xs
	check (x:xs) = ((length x) > 0):checkTail xs
	checkTail [x] = [length x > 0]
	checkTail (x:xs) = (length x > 1):checkTail xs
	answer xs = if (length xs > 1) && (and (check xs))
		then solution address else "No solution"
	solution [x,y] = ad x y
	solution (x:y:xs) = (ad x [head y]) ++ "," ++ solution ((tail y):xs)
	ad x y = x ++ "@" ++ y

import Data.List
import Data.Functor
main=interact$maybe"No solution"(intercalate",").f
f x|null x=Just[]|null y||all(=='@')(take 2 z)=Nothing|'@'`notElem`tail z=Just[x]|1>0=(:)(y++take 2 z)<$>f(drop 2 z)where(y,z)=break(=='@')x

import Data.List
import Data.Functor
main=interact$maybe"Nosolution"(intercalate",").f
f x|null x=Just[]|null y||all(=='@')(take 2 z)=Nothing|'@'`notElem`tail z=Just[x]|1>0=(:)(y++take 2 z)<$>f(drop 2 z)where(y,z)=break(=='@')x

main = interact (ans)
ans theInput = answer where
	address = split $ head $ lines theInput
	split :: String -> [String]
	split "" = []
	split xs = if snd(break (=='@') u)=="" then [xs]
		else (x ++ (take 2 y)):(split u)
		where
			(x,y) = break (=='@') xs
			u = drop 2 y
	check = [(head x /= '@') && (last x /='@') | x<- address]
	answer = if and check then solution address else "No solution"
	solution [x] = x
	solution (x:xs) = x ++ "," ++ solution xs

main = interact (ans)
ans theInput = answer where
	line0 = head $ lines theInput
	address = split line0
	split :: String -> [String]
	split "" = []
	split xs = if snd(break (=='@') u)=="" then [xs]
		else (x ++ (take 2 y)):(split u)
		where
			(x,y) = break (=='@') xs
			u = drop 2 y
	check = [(head x /= '@') && (last x /='@') | x<- address]
	answer = if (snd(break (=='@') line0)/="") && (and check) then solution address
		else "No solution"
	solution [x] = x
	solution (x:xs) = x ++ "," ++ solution xs

main = interact (ans)
ans theInput = answer where
	line0 = head $ lines theInput
	address = split line0
	split :: String -> [String]
	split xs = if elem '@' u then (x ++ (take 2 y)):(split u) else [xs] where
		(x,y) = break (=='@') xs
		u = drop 2 y
	check = [(head x /= '@') && (last x /='@') | x<- address]
	answer = if (elem '@' line0) && (and check) then solution address else "No solution"
	solution [x] = x
	solution (x:xs) = x ++ "," ++ solution xs

import Data.Maybe

email_recovery' [] = Just []
email_recovery' ('@':_) = Nothing
email_recovery' (x:'@':'@':_) = Nothing
email_recovery' (x:'@':y:xs) = (email_recovery' xs) >>= (\a -> Just (',':x:'@':y:a))
email_recovery' (x:xs) = (email_recovery' xs) >>= (\a -> Just (x : a))

email_recovery'' [] = Nothing
email_recovery'' ('@':_) = Nothing
email_recovery'' (x:'@':xs) = (email_recovery' (x:'@':xs)) >>= (\a -> Just(tail a))
email_recovery'' (x:xs) = (email_recovery'' xs) >>= (\a -> Just (x : a))

erec [] = ""
erec x = if isNothing result then "No solution."
         else fromJust (result)
         where result = email_recovery'' x

main = do
  inpStr <- getLine
  putStrLn (erec inpStr)


import Control.Monad

solve (x,y) | (y=="a") = 1
            | (any (=='a') y) = -1
            | otherwise = 1 + sum (map (\k -> (toInteger n) `choose` k) (take n [1..]))
  where n = length x

main = do
  t <- getLine
  cases <- replicateM (read t) readCase
  putStrLn (unwords $ map (show . solve) cases)

readCase = do
  x <- getLine
  y <- getLine
  return (x, y)

n `choose` k
    | k < 0     = 0
    | k > n     = 0
    | otherwise = factorial n `div` (factorial k* factorial (n-k))

factorial n = product [1..n]

import Control.Monad (replicateM_)

import Data.Set ( Set)
import qualified Data.Set as Set

main = do
    testCases <- getLine
    replicateM_ (read testCases) (runCase >>= putStrLn)

runCase = do
    lin <- getLine
    show . solve lin <$> getLine

solve inp subst | ('a' `notElem` inp) || (subst == "a") = 1
solve inp subst | (length subst > 1) && (elem 'a' subst) = if ('a' `elem` inp) then -1 else 1
solve inp _ = 2^(length $ filter (=='a') inp)

import Control.Monad

solve (x,y) | (y=="a") = 1
            | (any (=='a') y) = -1
            | otherwise = 2 ^ length x

main = do
  t <- getLine
  cases <- replicateM (read t) readCase
  putStrLn (unwords $ map (show . solve) cases)

readCase = do
  x <- getLine
  y <- getLine
  return (x, y)

import Control.Monad

solve (x,y) | (y=="a") = 1
            | (any (=='a') y) = -1
            | otherwise = 1 + sum (map (\k -> n `choose` k) (take n [1..]))
  where n = length x

main = do
  t <- getLine
  cases <- replicateM (read t) readCase
  putStrLn (unwords $ map (show . solve) cases)

readCase = do
  x <- getLine
  y <- getLine
  return (x, y)

n `choose` k
    | k < 0     = 0
    | k > n     = 0
    | otherwise = factorial n `div` (factorial k * factorial (n-k))

factorial n = product [1..n]

import Control.Monad

solve (x,y) | (y=="a") = 1
            | (any (=='a') y) = -1
            | otherwise = length x + 1

main = do
  t <- getLine
  cases <- replicateM (read t) readCase
  putStrLn (unwords $ map (show . solve) cases)

readCase = do
  x <- getLine
  y <- getLine
  return (x, y)


--import Data.Bits
--import Control.Monad
import Data.List
--import Control.Monad.Writer
--import Data.Maybe
main :: IO ()
main = do
	mm <- getLine
	let n=read mm
	s <- getLine

	putStrLn $ if f n s then "YES" else "NO"
	return ()

f :: Int -> String -> Bool
f n s = let m = (n-11) in
        if (length $ fst (partition (==1) $ take (m+1) $ concat $ group (map h s)))>(m `div` 2)  then True else False

h :: Char -> Int
h '8' = 1
h _   = 0

t :: [Int] -> [Int]
t s =(delete 1 (delete 0 s))

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

main = do
	n <- readInt
	s <- getLine
	let
		turn = ( n - 11 ) `div` 2
		prefix = vasya turn s
		num8 = length $ takeWhile ( == '8' ) prefix
	putStrLn $ which "YES" "NO" $ turn < num8

vasya _ [] = []
vasya 0 s = s
vasya k (c:s)
	| c == '8' = c : vasya k s
	| otherwise = vasya ( pred k ) s


import Data.List
import Control.Monad
main = interact $ format . solve . map read . tail . words
solve as = guard (sum ls /= sum rs) *> pure ss where
  ss = sort as
  (ls,rs) = splitAt (length ss `div` 2) ss
format Nothing = "-1"
format (Just xs) = unwords $ map show xs

module Main where
import Data.List

main = interact $ (\(n:xs) -> maybe "-1" (unwords . map show) $ ok n $ sort xs) . map read . words
ok n xs
  | sum zs == sum ys = Nothing
  | True = Just xs
  where (ys, zs) = splitAt n xs

module Main where

main = interact $ (\(n:xs) -> if rep xs then "-1" else unwords $ map show $ uncurry (mix [] []) $ splitAt n xs ) . map read . words
rep (x:xs) = all (== x) xs
mix xs' ys' [] [] = xs' ++ ys'
mix xs' ys' (x:xs) (y:ys)
  | x /= y = mix (y:xs') (x:ys') xs ys
  | True = mix (x:xs') (y:ys') xs ys

module Main where

main = interact $ (\(n:xs) -> unwords $ map show $ uncurry go $ splitAt n xs) . map read . words
go xs ys
  | sum xs /= sum ys = xs ++ ys
  | True = mix False [] [] xs ys
mix False _ _ [] [] = [-1]
mix True xs' ys' [] [] = xs' ++ ys'
mix b xs' ys' (x:xs) (y:ys)
  | not b && x /= y = mix True (y:xs') (x:ys') xs ys
  | True = mix b (x:xs') (y:ys') xs ys


{-# LANGUAGE TypeApplications, BangPatterns #-}
import Control.Monad
import Data.Array.IO
import Data.Array.Unboxed
import Data.Array.Unsafe
import Data.Maybe
import qualified Data.ByteString.Char8 as C

solve :: IO ()
solve = do
    ~[n, x] <- readInts
    a <- listArray @UArray (1, n) <$> readInts
    dp <- newArray @IOUArray ((0, 0), (n, n)) 0
    forM_ [1..n] $ \i ->
        forM_ [0..n] $ \j -> do
            !nox <- (a!i +) . max 0 <$> readArray dp (i - 1, j)
            writeArray dp (i, j) =<< if j == 0 then pure nox else do
                !yesx <- (a!i + x +) . max 0 <$> readArray dp (i - 1, j - 1)
                pure $! max nox yesx
    dp <- unsafeFreeze @_ @_ @_ @_ @UArray dp
    putStrLn $ unwords $ map (show . maximum) [[dp!(i, j) | i <- [0..n]] | j <- [0..n]]

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

main :: IO ()
main = flip replicateM_ solve . head =<< readInts

{-# LANGUAGE TypeApplications #-}
import Control.Monad
import Data.Array.IO
import Data.Array.Unboxed
import Data.Array.Unsafe
import Data.Maybe
import qualified Data.ByteString.Char8 as C

solve :: IO ()
solve = do
    ~[n, x] <- readInts
    a <- listArray @UArray (1, n) <$> readInts
    dp <- newArray @IOUArray ((0, 0), (n, n)) 0
    forM_ [1..n] $ \i ->
        forM_ [0..n] $ \j -> do
            nox <- (a!i +) . max 0 <$> readArray dp (i - 1, j)
            writeArray dp (i, j) =<< if j == 0 then pure nox else do
                yesx <- (a!i + x +) . max 0 <$> readArray dp (i - 1, j - 1)
                pure $ max nox yesx
    dp <- unsafeFreeze @_ @_ @_ @_ @UArray dp
    putStrLn $ unwords $ map (show . maximum) [[dp!(i, j) | i <- [0..n]] | j <- [0..n]]

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

main :: IO ()
main = flip replicateM_ solve . head =<< readInts

{-# LANGUAGE CPP, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, OverloadedStrings, ScopedTypeVariables, TupleSections  #-}
{-# LANGUAGE Strict #-}
{-# OPTIONS_GHC -O2 -funbox-strict-fields -fvia-C -optc-O3 #-}
import Control.Monad (replicateM_, replicateM)

import qualified Data.ByteString.Char8 as B8
import qualified Data.String as S

import Control.Arrow ((>>>))
import Data.Functor ((<&>))
import Data.Maybe
import qualified Data.Traversable as T

import qualified Data.Monoid as M
import qualified Control.Applicative as A
import qualified Control.Monad as M
import qualified Control.Monad.State as MS
import qualified Control.Monad.Trans as MT
import qualified Control.Monad.Trans.Maybe as M

import qualified Data.List as L
import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import qualified Data.IntSet as IS
import qualified Data.IntMap as IM
import qualified Data.Set as S
import Data.List (sortBy, sortOn)

import Data.Char
import Data.Int
import Data.Bits

import System.IO (stdin, stdout, hFlush)
import Text.Printf

{- reading -}
readIntB8 :: B8.ByteString -> Int
readIntB8 = B8.readInt >>> (fst . fromJust)
readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))
readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)
readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

maximum' a = L.foldl1' max a

sol a k x = res k
    where
       res 0 = (l, maxF)
         where
            l = v1
               where v1 = drop 1 $ scanl (\x y -> maximum' [0, x + y]) 0 a
            maxF = v2
               where v2 = (maximum' l : [])
       res n = (l, maxF)
         where
            l = v1
                where v1 = zipWith (\a b -> maximum' [a + x, b + x + a]) a (0 :  fst prev)
            maxF = v2
                where v2 = (maximum' (0:l) : snd prev)

            prev = res (n - 1)

solve :: IO()
solve = do
    [n, x] <- B8.getLine <&> readIntB8s
    a <- B8.getLine <&> readIntB8s
    let answer = sol a n x
    M.forM_ (reverse (snd answer)) $ \p -> printf "%lld " p
    printf "\n"

main :: IO()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t solve

-- problem: https://codeforces.com/contest/1644/problem/C
-- origin: https://codeforces.com/contest/1644/submission/147353835

import Control.Monad.State (State, evalState, replicateM, state)
import Data.Array (listArray, (!))
import Data.Bifunctor (first)
import Data.Char (isDigit, isSpace)

mainFunc :: State [Char] [[Char]]
mainFunc = do
  t <- getInt
  replicateM t $ do
    n <- getInt
    x <- getInt
    a <- replicateM n getInt
    let -- Start to calculate len, which is the length corresponding to the max subarray sum.
        -- func (startV, startI, endV, endI) (i, v) = (sv, si, ev, ei)
        --   where
        --     (sv, si) = if startV < 0 then (v, i) else (startV + v, startI)
        --     (ev, ei) = if sv > endV then (sv, i) else (endV, endI)

        -- (startV, startI, maxV, endI) = foldl func (0, 0, 0, -1) $ zip [0 ..] a
        -- len = let ans = endI - startI + 1 in if ans <= 0 then 0 else ans
        -- End calculating. If don't want to calculate it, set len = 0, and replace maxByLen.
        len = 0
        maxByLen = scanr max (prefixSums ! n) (0:rsByLen)
        prefixSums = listArray (0, n) $ scanl (+) 0 a

        rsByLen :: [Int] -- range sums
        rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j]] | j <- [len + 1 .. n - 1]]

        -- maxByLen
        --   | len == n = replicate (len + 1) maxV
        --   | otherwise = replicate (len + 1) maxV ++ scanr max (prefixSums ! n) rsByLen

        xwides = zipWith (+) maxByLen [0, x ..]
    pure $ putInts $ scanl1 max xwides

getInt :: State [Char] Int
getInt = state (first (\x -> read x :: Int) . span isInt . dropWhile isSpace)
  where
    isInt c = isDigit c || (c == '-')

putInts :: [Int] -> [Char]
putInts x = unwords (map show x) ++ "\n"

main :: IO ()
main = do
  inp <- getContents
  putStr $ concat $ evalState mainFunc inp

import Control.Monad.State (State, evalState, replicateM, state)
import Data.Array (listArray, (!))
import Data.Bifunctor (first)
import Data.Char (isDigit, isSpace)

mainFunc :: State [Char] [[Char]]
mainFunc = do
  t <- getInt
  replicateM t $ do
    n <- getInt
    x <- getInt
    a <- replicateM n getInt
    let func (startV, startI, endV, endI) (i, v) = (sv, si, ev, ei)
          where
            (sv, si) = if startV < 0 then (v, i) else (startV + v, startI)
            (ev, ei) = if sv > endV then (sv, i) else (endV, endI)

        (startV, startI, maxV, endI) = foldl func (0, 0, 0, -1) $ zip [0 ..] a
        len = let ans = endI - startI + 1 in if ans <= 0 then 0 else ans

        prefixSums = listArray (0, n) $ scanl (+) 0 a

        rsByLen :: [Int] -- range sums
        rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j]] | j <- [len + 1 .. n - 1]]

        maxByLen
          | len == n = replicate (len + 1) maxV
          | otherwise = replicate (len + 1) maxV ++ scanr max (prefixSums ! n) rsByLen

        xwides = zipWith (+) maxByLen [0, x ..]
    pure $ putInts $ scanl1 max xwides

getInt :: State [Char] Int
getInt = state (first (\x -> read x :: Int) . span isInt . dropWhile isSpace)
  where
    isInt c = isDigit c || (c == '-')

putInts :: [Int] -> [Char]
putInts x = unwords (map show x) ++ "\n"

main :: IO ()
main = do
  inp <- getContents
  putStr $ concat $ evalState mainFunc inp

import Control.Monad.State (State, evalState, replicateM, state)
import Data.Array (assocs, listArray, (!))
import Data.Bifunctor (first)
import Data.Char (isDigit, isSpace)

mainFunc :: State [Char] [[Char]]
mainFunc = do
  t <- getInt
  replicateM t $ do
    n <- getInt
    x <- getInt
    a <- replicateM n getInt
    let prefixSums = listArray (0, n) $ scanl (+) 0 a

        rsByLen :: [Int] -- range sums
        rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j]] | j <- [1 .. n -1]]
        xwides = zipWith (+) (scanr max (prefixSums ! n) (0 : rsByLen)) [0, x ..]
    pure $ putInts $ scanl1 max xwides

getInt :: State [Char] Int
getInt = state (first (\x -> read x :: Int) . span isInt . dropWhile isSpace)
  where
    isInt c = isDigit c || (c == '-')

putInts :: [Int] -> [Char]
putInts x = unwords (map show x) ++ "\n"

main :: IO ()
main = do
  inp <- getContents
  putStr $ concat $ evalState mainFunc inp

import Control.Monad.State (State, evalState, replicateM, state)
import Data.Array (assocs, listArray, (!))
import Data.Bifunctor (first)
import Data.Char (isDigit, isSpace)

mainFunc :: State [Char] [[Char]]
mainFunc = do
  t <- getInt
  replicateM t $ do
    n <- getInt
    x <- getInt
    a <- replicateM n getInt
    let prefixSums = listArray (0,n) $ scanl (+) 0 a

        rsByLen :: [Int] -- range sums
        rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j]] | j <- [1 .. n]]
        xwides = zipWith (+) (scanr1 max (0:rsByLen)) [0, x ..]
    pure $ putInts $ scanl1 max xwides

getInt :: State [Char] Int
getInt = state (first (\x -> read x :: Int) . span isInt . dropWhile isSpace)
  where
    isInt c = isDigit c || (c == '-')

putInts :: [Int] -> [Char]
putInts x = unwords (map show x) ++ "\n"

main :: IO ()
main = do
  inp <- getContents
  putStr $ concat $ evalState mainFunc inp

import Control.Monad.State (State, evalState, replicateM, state)
import Data.Array (assocs, listArray, (!))
import Data.Bifunctor (first)
import Data.Char (isDigit, isSpace)

mainFunc :: State [Char] [[Char]]
mainFunc = do
  t <- getInt
  replicateM t $ do
    n <- getInt
    x <- getInt
    a <- replicateM n getInt
    let prefixSums = listArray (0,n) $ scanl (+) 0 a

        rsByLen :: [Int] -- range sums
        rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j]] | j <- [0 .. n]]
        xwides = zipWith (+) (scanr1 max rsByLen) [0, x ..]
    pure $ putInts $ scanl1 max xwides

getInt :: State [Char] Int
getInt = state (first (\x -> read x :: Int) . span isInt . dropWhile isSpace)
  where
    isInt c = isDigit c || (c == '-')

putInts :: [Int] -> [Char]
putInts x = unwords (map show x) ++ "\n"

main :: IO ()
main = do
  inp <- getContents
  putStr $ concat $ evalState mainFunc inp

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Data.List
import Data.Array.Unboxed

mainFun :: SP Builder
mainFun = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    n <- getInt
    x <- getInt
    a <- replicateM n getInt
    let
      prefixSums :: UArray Int Int
      prefixSums = listArray (0, n) $ scanl' (+) 0 a

      rsByLen :: UArray Int Int
      -- range sums
      rsByLen = accumArray max minBound (0, n) $ do
        (i, psi) <- assocs prefixSums
        j <- [i .. n]
        pure (j - i, prefixSums ! j - psi)

      xwides   = zipWith (+) (scanr1 max $ elems rsByLen) [0, x ..]
      xnarrows = scanl1 max $ zipWith (+) (elems rsByLen) [0, x ..]
    pure $ putInts $ zipWith max xwides xnarrows

type SP = State P.ByteString
type S = StateT P.ByteString

dropSpace :: P.ByteString -> P.ByteString
dropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough

--getNext :: Monad m => S m P.ByteString
--getNext = state $ P.span (> ' ') . dropSpace

getInt :: Monad m => S m Int
getInt = state $ fromJust . P.readInt . dropSpace

putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun inp
  P.putStr $ toLazyByteString outp

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Data.List
import Data.Array.Unboxed

mainFun :: SP Builder
mainFun = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    n <- getInt
    x <- getInt
    a <- replicateM n getInt
    let
      ps = listArray (0, n) $ scanl' (+) 0 a
      xps = array (0, n) [(i, psi + x * i) | (i, psi) <- assocs ps]

      ack :: UArray Int Int -> UArray Int Int
      ack arr = accumArray max minBound (0, n) $ do
        (i, ai) <- assocs arr
        j <- [i .. n]
        pure (j - i, arr ! j - ai)

      narrows = ack xps
      wides = ack ps

      xwides = zipWith (+) (scanr1 max $ elems wides) [0, x ..]
      xnarrows = scanl1 max $ elems narrows
    pure $ putInts $ zipWith max xwides xnarrows

type SP = State P.ByteString
type S = StateT P.ByteString

dropSpace :: P.ByteString -> P.ByteString
dropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough

--getNext :: Monad m => S m P.ByteString
--getNext = state $ P.span (> ' ') . dropSpace

getInt :: Monad m => S m Int
getInt = state $ fromJust . P.readInt . dropSpace

putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun inp
  P.putStr $ toLazyByteString outp

{-# LANGUAGE TypeApplications #-}
import Control.Monad
import Data.Array.IO
import Data.Array.Unboxed
import Data.Array.Unsafe
import Data.List
import Data.Maybe
import qualified Data.ByteString.Char8 as C

solve :: IO ()
solve = do
    ~[n, x] <- readInts
    a <- listArray @UArray (1, n) <$> readInts
    dp <- newArray @IOUArray ((0, 0), (n, n)) 0
    forM_ [1..n] $ \i ->
        forM_ [0..n] $ \j -> do
            nox <- (a!i +) . max 0 <$> readArray dp (i - 1, j)
            writeArray dp (i, j) =<< if j == 0 then pure nox else do
                yesx <- (a!i + x +) . max 0 <$> readArray dp (i - 1, j - 1)
                pure $ max nox yesx
    dp <- unsafeFreeze @_ @_ @_ @_ @UArray dp
    putStrLn $ unwords $ map (show . foldl' max 0) [[dp!(i, j) | i <- [0..n]] | j <- [0..n]]

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

main :: IO ()
main = flip replicateM_ solve . head =<< readInts

-- problem: https://codeforces.com/contest/1644/problem/C
-- origin: https://codeforces.com/contest/1644/submission/147353835

import Control.Monad.State (State, evalState, replicateM, state)
import Data.Array (listArray, (!))
import Data.Bifunctor (first)
import Data.Char (isDigit, isSpace)

mainFunc :: State [Char] [[Char]]
mainFunc = do
  t <- getInt
  replicateM t $ do
    n <- getInt
    x <- getInt
    a <- replicateM n getInt
    let -- Start to calculate len, which is the length corresponding to the max subarray sum.
        -- func (startV, startI, endV, endI) (i, v) = (sv, si, ev, ei)
        --   where
        --     (sv, si) = if startV < 0 then (v, i) else (startV + v, startI)
        --     (ev, ei) = if sv > endV then (sv, i) else (endV, endI)

        -- (startV, startI, maxV, endI) = foldl func (0, 0, 0, -1) $ zip [0 ..] a
        -- len = let ans = endI - startI + 1 in if ans <= 0 then 0 else ans
        -- End calculating. If don't want to calculate it, set len = 0, maxV = 0.
        len = 0
        maxV = 0
        prefixSums = listArray (0, n) $ scanl (+) 0 a

        rsByLen :: [Int] -- range sums
        rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j]] | j <- [len + 1 .. n - 1]]

        maxByLen
          | len == n = replicate (len + 1) maxV
          | otherwise = replicate (len + 1) maxV ++ scanr max (prefixSums ! n) rsByLen

        xwides = zipWith (+) maxByLen [0, x ..]
    pure $ putInts $ scanl1 max xwides

getInt :: State [Char] Int
getInt = state (first (\x -> read x :: Int) . span isInt . dropWhile isSpace)
  where
    isInt c = isDigit c || (c == '-')

putInts :: [Int] -> [Char]
putInts x = unwords (map show x) ++ "\n"

main :: IO ()
main = do
  inp <- getContents
  putStr $ concat $ evalState mainFunc inp

import Control.Monad.State (State, evalState, replicateM, state)
import Data.Array (listArray, (!))
import Data.Bifunctor (first)
import Data.Char (isDigit, isSpace)

mainFunc :: State [Char] [[Char]]
mainFunc = do
  t <- getInt
  replicateM t $ do
    n <- getInt
    x <- getInt
    a <- replicateM n getInt
    let func (startV, startI, endV, endI) (i, v) = (sv, si, ev, ei)
          where
            (sv, si) = if startV < 0 then (v, i) else (startV + v, startI)
            (ev, ei) = if sv > endV then (sv, i) else (endV, endI)

        (startV, startI, maxV, endI) = foldl func (0, 0, 0, -1) $ zip [0 ..] a
        len = let ans = endI - startI + 1 in if ans <= 0 then 0 else ans

        prefixSums = listArray (0, n) $ scanl (+) 0 a

        rsByLen :: [Int] -- range sums
        rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j]] | j <- [len + 1 .. n - 1]]

        maxByLen = replicate (len + 1) maxV ++ if null rsByLen then [] else scanr max (prefixSums ! n) rsByLen

        xwides = zipWith (+) maxByLen [0, x ..]
    pure $ putInts $ scanl1 max xwides

getInt :: State [Char] Int
getInt = state (first (\x -> read x :: Int) . span isInt . dropWhile isSpace)
  where
    isInt c = isDigit c || (c == '-')

putInts :: [Int] -> [Char]
putInts x = unwords (map show x) ++ "\n"

main :: IO ()
main = do
  inp <- getContents
  putStr $ concat $ evalState mainFunc inp

import Control.Monad.State (State, evalState, replicateM, state)
import Data.Array (assocs, listArray, (!))
import Data.Bifunctor (first)
import Data.Char (isDigit, isSpace)

mainFunc :: State [Char] [[Char]]
mainFunc = do
  t <- getInt
  replicateM t $ do
    n <- getInt
    x <- getInt
    a <- replicateM n getInt
    let func (startV, startI, endV, endI) (i, v) = (sv, si, ev, ei)
          where
            (sv, si) = if startV < 0 then (v, i) else (startV + v, startI)
            (ev, ei) = if sv > endV then (sv, i) else (endV, endI)

        (startV, startI, maxV, endI) = foldl func (0, 0, 0, -1) $ zip [0 ..] a
        len = let ans = endI - startI + 1 in if ans <= 0 then 0 else ans

        prefixSums = listArray (0, n - 1) $ tail $ scanl (+) 0 a

        rsByLen :: [Int] -- range sums
        rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j - 1]] | j <- [len + 1 .. n - 1]]

        maxByLen = replicate (len + 1) maxV ++ if null rsByLen then [] else scanr max (prefixSums ! (n - 1)) rsByLen

        xwides = zipWith (+) maxByLen [0, x ..]
        xnarrows = scanl1 max $ zipWith (+) maxByLen [0, x ..]
    pure $ putInts $ zipWith max xwides xnarrows

getInt :: State [Char] Int
getInt = state (first (\x -> read x :: Int) . span isInt . dropWhile isSpace)
  where
    isInt c = isDigit c || (c == '-')

putInts :: [Int] -> [Char]
putInts x = unwords (map show x) ++ "\n"

main :: IO ()
main = do
  inp <- getContents
  putStr $ concat $ evalState mainFunc inp

import Control.Monad.State (State, evalState, replicateM, state)
import Data.Array (assocs, listArray, (!))
import Data.Bifunctor (first)
import Data.Char (isDigit, isSpace)

mainFunc :: State [Char] [[Char]]
mainFunc = do
  t <- getInt
  replicateM t $ do
    n <- getInt
    x <- getInt
    a <- replicateM n getInt
    let prefixSums = listArray (0, n - 1) $ tail $ scanl (+) 0 a

        rsByLen :: [Int] -- range sums
        rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j - 1]] | j <- [1 .. n - 1]]

        xwides = zipWith (+) (scanr max (prefixSums ! (n - 1)) (0 : rsByLen)) [0, x ..]
    pure $ putInts $ scanl1 max xwides

getInt :: State [Char] Int
getInt = state (first (\x -> read x :: Int) . span isInt . dropWhile isSpace)
  where
    isInt c = isDigit c || (c == '-')

putInts :: [Int] -> [Char]
putInts x = unwords (map show x) ++ "\n"

main :: IO ()
main = do
  inp <- getContents
  putStr $ concat $ evalState mainFunc inp

import Control.Monad.State (State, evalState, replicateM, state)
import Data.Array (assocs, listArray, (!))
import Data.Bifunctor (first)
import Data.Char (isDigit, isSpace)

mainFunc :: State [Char] [[Char]]
mainFunc = do
  t <- getInt
  replicateM t $ do
    n <- getInt
    x <- getInt
    a <- replicateM n getInt
    let ia = listArray (0, n -1) a
        func (startV, startI, endV, endI) (i, v) = (sv, si, ev, ei)
          where
            (sv, si) = if startV < 0 then (v, i) else (startV + v, startI)
            (ev, ei) = if sv > endV then (sv, i) else (endV, endI)

        (startV, startI, maxV, endI) = foldl func (0, 0, 0, -1) $ assocs ia
        len = let ans = endI - startI + 1 in if ans <= 0 then 0 else ans

        prefixSums = listArray (0, n - 1) $ tail $ scanl (+) 0 a

        rsByLen :: [Int] -- range sums
        rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j - 1]] | j <- [len + 1 .. n - 1]]

        maxByLen = replicate (len + 1) maxV ++ if null rsByLen then [] else scanr max (prefixSums ! (n - 1)) rsByLen

        xwides = zipWith (+) maxByLen [0, x ..]
    pure $ putInts $ scanl1 max xwides

getInt :: State [Char] Int
getInt = state (first (\x -> read x :: Int) . span isInt . dropWhile isSpace)
  where
    isInt c = isDigit c || (c == '-')

putInts :: [Int] -> [Char]
putInts x = unwords (map show x) ++ "\n"

main :: IO ()
main = do
  inp <- getContents
  putStr $ concat $ evalState mainFunc inp

import Control.Monad.State (State, evalState, replicateM, state)
import Data.Bifunctor (first)
import Data.Char (isDigit, isSpace)

mainFunc :: State [Char] [[Char]]
mainFunc = do
  t <- getInt
  replicateM t $ do
    n <- getInt
    x <- getInt
    a <- replicateM n getInt
    let mark :: [Int] -> [Int] -> Int -> Int -> Int -> Int -> Int -> ([Int], Int, Int)
        mark [] prefixSums i startV startI endV endI = (tail prefixSums, endV, let ans = endI - startI + 1 in if ans <= 0 then 0 else ans)
        mark (li : ls) prefixSums i startV startI endV endI = mark ls pre (i + 1) sv si ev ei
          where
            pre = prefixSums ++ [last prefixSums + li]
            modifyStart = startV < 0
            sv = if modifyStart then li else startV + li
            si = if modifyStart then i else startI
            modifyEnd = sv > endV
            ev = if modifyEnd then sv else endV
            ei = if modifyEnd then i else endI

        (prefixSums, maxV, len) = mark a [0] 0 0 0 0 (-1)

        rsByLen :: [Int] -- range sums
        rsByLen = [maximum [prefixSums !! (i + j) - prefixSums !! i | i <- [0 .. n - j - 1]] | j <- [len + 1 .. n - 1]]

        maxByLen = replicate (len + 1) maxV ++ scanr max (prefixSums !! (n - 1)) rsByLen
        xwides = zipWith (+) maxByLen [0, x ..]
    pure $ putInts $ scanl1 max xwides

getInt :: State [Char] Int
getInt = state (first (\x -> read x :: Int) . span isInt . dropWhile isSpace)
  where
    isInt c = isDigit c || (c == '-')

putInts :: [Int] -> [Char]
putInts x = unwords (map show x) ++ "\n"

main :: IO ()
main = do
  inp <- getContents
  putStr $ concat $ evalState mainFunc inp

import Control.Monad.State (State, evalState, replicateM, state)
import Data.Bifunctor (first)
import Data.Char (isDigit, isSpace)
import Data.List (scanl')

mainFunc :: State [Char] [[Char]]
mainFunc = do
  t <- getInt
  replicateM t $ do
    n <- getInt
    x <- getInt
    a <- replicateM n getInt
    let prefixSums :: [Int]
        prefixSums = scanl' (+) 0 a

        rsByLen :: [Int] -- range sums
        rsByLen = [maximum [prefixSums !! (i + (n - j)) - prefixSums !! i | i <- [0 .. j]] | j <- [0 .. n]]
        -- i is the index of the start of the range, (n - j) equals to the interval
        -- so that we get xwides using scanl1 instead of scanr1
        xwides = zipWith (+) (scanl1 max rsByLen) [0, x ..]
    pure $ putInts $ scanl1 max xwides

getInt :: State [Char] Int
getInt = state (first (\x -> read x :: Int) . span isInt . dropWhile isSpace)
  where
    isInt c = isDigit c || (c == '-')

putInts :: [Int] -> [Char]
putInts x = unwords (map show x) ++ "\n"

main :: IO ()
main = do
  inp <- getContents
  putStr $ concat $ evalState mainFunc inp

{-# LANGUAGE CPP, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, OverloadedStrings, ScopedTypeVariables, TupleSections  #-}
{-# LANGUAGE Strict #-}
import Control.Monad (replicateM_, replicateM)

import qualified Data.ByteString.Char8 as B8
import qualified Data.String as S

import Control.Arrow ((>>>))
import Data.Functor ((<&>))
import Data.Maybe
import qualified Data.Traversable as T

import qualified Data.Monoid as M
import qualified Control.Applicative as A
import qualified Control.Monad as M
import qualified Control.Monad.State as MS
import qualified Control.Monad.Trans as MT
import qualified Control.Monad.Trans.Maybe as M

import qualified Data.List as L
import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import qualified Data.IntSet as IS
import qualified Data.IntMap as IM
import qualified Data.Set as S
import Data.List (sortBy, sortOn)

import Data.Char
import Data.Int
import Data.Bits

import System.IO (stdin, stdout, hFlush)
import Text.Printf

{- reading -}
readIntB8 :: B8.ByteString -> Int
readIntB8 = B8.readInt >>> (fst . fromJust)
readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))
readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)
readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

maximum' a = L.foldl1' max a

sol a k x = snd (res k)
    where
        a' = zipWith (+) a (replicate k x)
        res 0 = (v1, v2)
	    where
	        v1 = (0 : scanl1 (\x y -> maximum' [0, x + y]) a)
		v2 = (maximum' v1 : [])
        res n = (v1, v2)
	     where
	        v1 = (0 : zipWith (\a b ->  maximum' [a, a + b]) a' (fst prev))
		v2 = (maximum' (0:v1) : snd prev)
		prev = res (n - 1)

solve :: IO()
solve = do
    [n, x] <- B8.getLine <&> readIntB8s
    a <- B8.getLine <&> readIntB8s
    let answer = sol a n x
    M.forM_ (reverse answer) $ \p -> printf "%lld " p
    printf "\n"

main :: IO()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t solve

{-# LANGUAGE CPP, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, OverloadedStrings, ScopedTypeVariables, TupleSections  #-}
{-# LANGUAGE Strict #-}
import Control.Monad (replicateM_, replicateM)

import qualified Data.ByteString.Char8 as B8
import qualified Data.String as S

import Control.Arrow ((>>>))
import Data.Functor ((<&>))
import Data.Maybe
import qualified Data.Traversable as T

import qualified Data.Monoid as M
import qualified Control.Applicative as A
import qualified Control.Monad as M
import qualified Control.Monad.State as MS
import qualified Control.Monad.Trans as MT
import qualified Control.Monad.Trans.Maybe as M

import qualified Data.List as L
import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import qualified Data.IntSet as IS
import qualified Data.IntMap as IM
import qualified Data.Set as S
import Data.List (sortBy, sortOn)

import Data.Char
import Data.Int
import Data.Bits

import System.IO (stdin, stdout, hFlush)
import Text.Printf

{- reading -}
readIntB8 :: B8.ByteString -> Int
readIntB8 = B8.readInt >>> (fst . fromJust)
readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))
readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)
readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

maximum' a = L.foldl1' max a

sol a k x = snd (res k)
    where
        a' = zipWith (+) a (replicate k x)
        res 0 = (v1, v2)
	    where
	        v1 = scanl (\x y -> maximum' [0, x + y]) 0 a
		v2 = (maximum' v1 : [])
        res n = (v1, v2)
	     where
	        v1 = zipWith (\a b ->  maximum' [a, a + b]) a' (fst prev)
		v2 = (maximum' (0:v1) : snd prev)
		prev = res (n - 1)

solve :: IO()
solve = do
    [n, x] <- B8.getLine <&> readIntB8s
    a <- B8.getLine <&> readIntB8s
    let answer = sol a n x
    M.forM_ (reverse answer) $ \p -> printf "%lld " p
    printf "\n"

main :: IO()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t solve

{-# LANGUAGE CPP, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, OverloadedStrings, ScopedTypeVariables, TupleSections  #-}
{-# LANGUAGE Strict #-}
{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}
import Control.Monad (replicateM_, replicateM)

import qualified Data.ByteString.Char8 as B8
import qualified Data.String as S

import Control.Arrow ((>>>))
import Data.Functor ((<&>))
import Data.Maybe
import qualified Data.Traversable as T

import qualified Data.Monoid as M
import qualified Control.Applicative as A
import qualified Control.Monad as M
import qualified Control.Monad.State as MS
import qualified Control.Monad.Trans as MT
import qualified Control.Monad.Trans.Maybe as M

import qualified Data.List as L
import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import qualified Data.IntSet as IS
import qualified Data.IntMap as IM
import qualified Data.Set as S
import Data.List (sortBy, sortOn)

import Data.Char
import Data.Int
import Data.Bits

import System.IO (stdin, stdout, hFlush)
import Text.Printf

{- reading -}
readIntB8 :: B8.ByteString -> Int
readIntB8 = B8.readInt >>> (fst . fromJust)
readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))
readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)
readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

maximum' a = L.foldl1' max a

sol a k x = snd (res k)
    where
        res 0 = (v1, v2)
	    where
	        v1 = scanl1 (\x y -> maximum' [0, x + y]) a
		v2 = (maximum' (0:v1) : [])
        res n = (v1, v2)
	     where
	        v1 = zipWith (\a b -> maximum' [a + x, b + x + a]) a (0 :  fst prev)
		v2 = (maximum' (0:v1) : snd prev)
		prev = res (n - 1)

solve :: IO()
solve = do
    [n, x] <- B8.getLine <&> readIntB8s
    a <- B8.getLine <&> readIntB8s
    let answer = sol a n x
    M.forM_ (reverse answer) $ \p -> printf "%lld " p
    printf "\n"

main :: IO()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t solve

{-# LANGUAGE CPP, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, OverloadedStrings, ScopedTypeVariables, TupleSections  #-}
{-# LANGUAGE Strict #-}
import Control.Monad (replicateM_, replicateM)

import qualified Data.ByteString.Char8 as B8
import qualified Data.String as S

import Control.Arrow ((>>>))
import Data.Functor ((<&>))
import Data.Maybe
import qualified Data.Traversable as T

import qualified Data.Monoid as M
import qualified Control.Applicative as A
import qualified Control.Monad as M
import qualified Control.Monad.State as MS
import qualified Control.Monad.Trans as MT
import qualified Control.Monad.Trans.Maybe as M

import qualified Data.List as L
import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import qualified Data.IntSet as IS
import qualified Data.IntMap as IM
import qualified Data.Set as S
import Data.List (sortBy, sortOn)

import Data.Char
import Data.Int
import Data.Bits

import System.IO (stdin, stdout, hFlush)
import Text.Printf

{- reading -}
readIntB8 :: B8.ByteString -> Int
readIntB8 = B8.readInt >>> (fst . fromJust)
readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))
readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)
readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

maximum' a = L.foldl1' max a

sol a k x = snd (res k)
    where
        res 0 = (v1, v2)
	    where
	        v1 = scanl1 (\x y -> maximum' [0, x + y]) a
		v2 = (maximum' (0:v1) : [])
        res n = (v1, v2)
	     where
	        v1 = zipWith (\a b -> a + x + maximum' [0, b]) a (0 :  fst prev)
		v2 = (maximum' (0:v1) : snd prev)
		prev = res (n - 1)

solve :: IO()
solve = do
    [n, x] <- B8.getLine <&> readIntB8s
    a <- B8.getLine <&> readIntB8s
    let answer = sol a n x
    M.forM_ (reverse answer) $ \p -> printf "%lld " p
    printf "\n"

main :: IO()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t solve

{-# LANGUAGE CPP, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, OverloadedStrings, ScopedTypeVariables, TupleSections  #-}
{-# LANGUAGE Strict #-}
import Control.Monad (replicateM_, replicateM)

import qualified Data.ByteString.Char8 as B8
import qualified Data.String as S

import Control.Arrow ((>>>))
import Data.Functor ((<&>))
import Data.Maybe
import qualified Data.Traversable as T

import qualified Data.Monoid as M
import qualified Control.Applicative as A
import qualified Control.Monad as M
import qualified Control.Monad.State as MS
import qualified Control.Monad.Trans as MT
import qualified Control.Monad.Trans.Maybe as M

import qualified Data.List as L
import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import qualified Data.IntSet as IS
import qualified Data.IntMap as IM
import qualified Data.Set as S
import Data.List (sortBy, sortOn)

import Data.Char
import Data.Int
import Data.Bits

import System.IO (stdin, stdout, hFlush)
import Text.Printf

{- reading -}
readIntB8 :: B8.ByteString -> Int
readIntB8 = B8.readInt >>> (fst . fromJust)
readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))
readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)
readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

maximum' a = L.foldl1' max a

sol a k x = snd (res k)
    where
        res 0 = (v1, v2)
	    where
	        v1 = drop 1 $ scanl (\x y -> maximum' [0, x + y]) 0 a
		v2 = (maximum' v1 : [])
        res n = (v1, v2)
	     where
	        v1 = zipWith (\a b -> maximum' [a + x, b + x + a]) a (0 :  fst prev)
		v2 = (maximum' v1 : snd prev)
		prev = res (n - 1)

solve :: IO()
solve = do
    [n, x] <- B8.getLine <&> readIntB8s
    a <- B8.getLine <&> readIntB8s
    let answer = sol a n x
    M.forM_ (reverse answer) $ \p -> printf "%lld " p
    printf "\n"

main :: IO()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t solve

{-# LANGUAGE CPP, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, OverloadedStrings, ScopedTypeVariables, TupleSections  #-}
{-# LANGUAGE Strict #-}
{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}

import Control.Monad (
    MonadPlus (mplus),
    foldM_,
    forM_,
    guard,
    join,
    replicateM,
    replicateM_,
 )

import qualified Data.ByteString.Char8 as B8
import qualified Data.String as S

import Control.Arrow ((>>>))
import Data.Functor ((<&>))
import Data.Maybe
import qualified Data.Traversable as T

import qualified Data.Monoid as M
import qualified Control.Applicative as A
import qualified Control.Monad as M
import qualified Control.Monad.State as MS
import qualified Control.Monad.Trans as MT
import qualified Control.Monad.Trans.Maybe as M

import qualified Data.List as L
import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import qualified Data.IntSet as IS
import qualified Data.IntMap as IM
import qualified Data.Set as S
import Data.List (sortBy, sortOn)

import Data.Char
import Data.Int
import Data.Bits

import System.IO (stdin, stdout, hFlush)
import Text.Printf

{- reading -}
readIntB8 :: B8.ByteString -> Int
readIntB8 = B8.readInt >>> (fst . fromJust)
readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))
readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)
readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

maximum' a = L.foldl1' max a
--maximum' a = maximum a

sol a k x = snd (res k)
    where
        res 0 = (v1, v2)
           where
             v1 = scanl1 (\x y -> maximum' [0, x + y]) a
             v2 = (maximum' (0 : v1) : [])
        res n = (v1, v2)
            where
              v1 = zipWith (\a b -> maximum' [0, a + x + b]) a (0 :  fst prev)
              v2 = (maximum' v1 : snd prev)
              prev = res (n - 1)

solve :: IO()
solve = do
    [n, x] <- B8.getLine <&> readIntB8s
    a <- B8.getLine <&> readIntB8s
    forM_ (reverse (sol a n x)) $ \p -> printf "%d " p
    printf "\n"

main :: IO()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t solve


import Data.Char
solve ::(Char -> Char) -> [Char] -> [Char]
solve f (x:xs)
    |f x > x = (f x): (solve' f xs)
    |otherwise = x : (solve f xs)
solve f x = []

solve' ::(Char -> Char) -> [Char] -> [Char]
solve' f (x:xs)
    |f x < x = x:xs
    |otherwise =(f x) : (solve' f xs)
solve' f x = []

makeF :: String -> (Char -> Char)
makeF s c = s!!(2*(c'-1))
	where c' = digitToInt c

main = do
    n <- getLine
    s <- getLine
    fs <- getLine
    putStrLn $ solve (makeF fs) s

--prewritten code: https://github.com/antma/algo
{-# LANGUAGE BangPatterns, Safe #-}
{-# Options_GHC -O2 #-}
import Data.ByteString.Builder
import Data.Char
import Data.List
import Data.Monoid
import Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)
import qualified Data.Array.Unboxed as UA
import qualified Data.ByteString.Char8 as C
import System.IO

getSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

solve :: [C.ByteString] -> Builder
solve (sn:z:a) = (mconcat $ map intDec $ l1 ++ (map (f UA.!) l2) ++ l3) <> char7 '\n'
  where
    !n = ru sn
    f = UA.listArray (1, 9) $ map ru $ take 9 a :: UA.UArray Int Int
    x = map (subtract 48 . ord) $ C.unpack z
    (l1, l0) = span (\ !i -> f UA.! i <= i)  x
    (l2, l3) = span (\ !i -> f UA.! i >= i) l0

main :: IO ()
main = hPutBuilder stdout . solve . C.words =<< C.getContents

--prewritten code: https://github.com/antma/algo
{-# LANGUAGE BangPatterns, Safe #-}
{-# Options_GHC -O2 #-}
import Data.ByteString.Builder
import Data.Char
import Data.List
import Data.Monoid
import Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)
import qualified Data.Array.Unboxed as UA
import qualified Data.ByteString.Char8 as C
import System.IO

getSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

solve :: [C.ByteString] -> Builder
solve (sn:z:a) = (mconcat $ map intDec $ l1 ++ (map (f UA.!) l2) ++ l3) <> char7 '\n'
  where
    !n = ru sn
    f = UA.listArray (1, 9) $ map ru $ take 9 a :: UA.UArray Int Int
    x = map (subtract 48 . ord) $ C.unpack z
    (l1, l0) = span (\ !i -> f UA.! i < i)  x
    (l2, l3) = span (\ !i -> f UA.! i >= i) l0

main :: IO ()
main = hPutBuilder stdout . solve . C.words =<< C.getContents


import Control.Applicative ((<$>), (<*>))

main :: IO ()
main = print =<< solve <$> readLn <*> (map read <$> words <$> getLine)

solve :: Int -> [Int] -> Int
solve _ as | null r = 0
           | all (uncurry (<=)) (tail r) && snd (last r) <= head as = length r
           | otherwise = -1
  where r = dropWhile (uncurry (<=)) (zip as (tail as))

s l=case filter((<0).snd).zip [1..]$zipWith(-)(tail$cycle l)l of
  []->0
  [(i,_)]->length l-i
  _-> -1
main=interact$show.s.tail.map read.words

import Data.List
import Data.Function
import Data.Char

main = interact $ show . getAns . map read . words

getAns :: [Int] -> Int
getAns (n:xs) =
		let (rs, lm) = splitList xs 0
	   	    lr = length rs
		in if (sort rs == rs && (lr == 0 || last rs <= head xs)) then lr else -1

splitList :: [Int] -> Int -> ([Int], Int)
splitList [] t = ([], t)
splitList (x:rs) t
	| t > x = (x:rs, t)
	| otherwise = splitList rs x

solve (n:xs) = case breakPoints of
                 []            -> 0
                 [(i, (_, _))] -> n - i
                 _             -> (-1)
    where ys = cycle xs
          breakPoints = filter isBreakPoint $ take n $ zip [1 ..] $ zip ys $ tail ys
          isBreakPoint (_, (x, y)) = x > y

main = interact $ show . solve . map read . words

groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy' _ [] = []
groupBy' eq (x:xs) = (x:ys) : groupBy' eq zs
    where
        (ys, zs) = aux x xs
        aux x0 (x:xs)
            | eq x0 x = (x:ys, zs)
            where (ys, zs) = aux x xs
        aux x0 xs = ([], xs)

solve :: [Int] -> Int
solve xs
    | length g == 1 = 0
    | length g == 2 && (head xs >= last xs) = length $ g!!1
    | otherwise = -1
    where
        g = groupBy' (<=) xs

main = do
    getLine
    dat <- getLine
    print $ solve $ map read $ words dat

import Data.List
import Data.Function
import Data.Char

main = interact $ show . getAns . map read . words

getAns :: [Int] -> Int
getAns (n:xs)
	| xs == sort xs = 0
	| otherwise =
		let (ls, rs) = break (== (minimum xs)) xs
	   	    lr = length rs
		in if (sort rs == rs && sort ls == ls && maximum rs < maximum ls) then lr else -1

import Data.List
import Data.Function
import Data.Char

main = interact $ show . getAns . map read . words

getAns :: [Int] -> Int
getAns (n:xs) =
		let (rs, lm) = splitList xs 0
	   	    lr = length rs
		in if (sort rs == rs && (lr == 0 || maximum rs <= lm)) then lr else -1

splitList :: [Int] -> Int -> ([Int], Int)
splitList [] t = ([], t)
splitList (x:rs) t
	| t > x = (x:rs, t)
	| otherwise = splitList rs x

import Data.List
import Data.Function
import Data.Char

main = interact $ show . getAns . map read . words

getAns :: [Int] -> Int
getAns (n:xs) =
	let (ls, rs) = break (==1) xs
	    lr = length rs
	in if ([1 .. lr] == rs && [lr + 1 .. n] == ls) then mod lr n else -1

import Data.List
import Data.Function
import Data.Char

main = interact $ show . getAns . map read . words

getAns :: [Int] -> Int
getAns (n:xs)
	| xs == sort xs = 0
	| otherwise =
		let (ls, rs) = break (== (minimum xs)) xs
	   	    lr = length rs
		in if (sort rs == rs && sort ls == ls && maximum rs <= maximum ls) then lr else -1

solve (n:xs) = case breakPoints of
                 []            -> 0
                 [(i, (_, _))] -> n - i
                 _             -> (-1)
    where breakPoints = filter isBreakPoint $ zip [1 ..] $ zip xs $ tail xs
          isBreakPoint (_, (x, y)) = x > y

main = interact $ show . solve . map read . words


import qualified Data.List as L
import qualified Data.Map as M
import Data.Map (Map)
import qualified Data.Set as S
import Data.Set (Set)
import qualified Data.IntSet as IS
import Data.IntSet (IntSet)
import qualified Data.IntMap as IM
import Data.IntMap (IntMap)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)

type Long = Integer

kth :: Long -> Long -> Long
kth 1 a = a
kth k a
    | mind == 0     = a
    | otherwise     = kth (k-1) (a + mind*maxd)
    where
        chars = show a
        mind = read $ minimum chars :""
        maxd = read $ maximum chars :""

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    (a1:k:_) <- readWords
    print $ kth k a1
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- readWords
    testCases t

readWords :: (Read a) => IO [a]
readWords = map read . words <$> getLine

import Control.Monad

main = do
    t <- read <$> getLine
    replicateM_ t test

test = do
    (a:k:_) <- map read . words <$> getLine
    let as = f a
        ak =
            if k - 1 >= toInteger (length as)
                then last as
                else as !! (fromInteger k - 1)
    print ak

f a
    | '0' `elem` ds = [a]
    | otherwise = a : f (a + read [minimum ds] * read [maximum ds])
  where
    ds = show a

import Control.Monad
import Data.Char

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [a1, k] <- readIs
    print $ solve a1 k

readIs :: IO [Integer]
readIs = fmap read . words <$> getLine

dTI :: Char -> Integer
dTI c = fromIntegral $ ord c - ord '0'

maxDigit, minDigit :: Integer -> Integer
maxDigit = dTI . maximum . show
minDigit = dTI . minimum . show

solve :: Integer -> Integer -> Integer
solve a 1 = a
solve a k | '0' `elem` show a = a
solve a k =
  solve (a + maxDigit a * minDigit a) (k-1)

import Control.Monad

solve :: Integer -> (Integer -> Integer)
solve x
    | x == 1    = id
    | otherwise = \y -> let res = solve (x-1) y in
                            res + (minDigit res) * (maxDigit res)

minDigit :: Integer -> Integer
minDigit x
    | x >= 10   = min (minDigit (x `div` 10)) (x `mod` 10)
    | otherwise = (x `mod` 10)

maxDigit :: Integer -> Integer
maxDigit x
    | x >= 10   = max (maxDigit (x `div` 10)) (x `mod` 10)
    | otherwise = (x `mod` 10)

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    (a:k:_) <- map read . words <$> getLine
    print (solve (min k 1000) a)


module Main where

import Data.List
import Data.Maybe
import qualified Data.Map.Strict as Map

main = do
  tStr <- getLine
  let t = read tStr :: Int
  input <- getContents
  let sols = map (format . solve . parse) $ take t $ sep $ lines input
  mapM_ putStrLn sols

sep (x:y:xs) = (x,y):(sep xs)

parse (x,y) = (read $ dropWhile (/= ' ') x, map f y)
  where f 'B' = 0
        f 'W' = 1

format = show

solve (k,cs) = minimum $ scanl f init $ zip cs t
  where (h,t) = splitAt k cs
        init = sum h
        f s (l,r) = s + r - l

cnt' :: (Int, Bool) -> String -> [(Int, Bool)]
cnt' tup [] = [tup]
cnt' tup (x : xs) = [tup] ++ cnt' tupNew xs
 where
  (cntPrev, _) = tup
  isB = (x == 'B')
  tupNew = (cntPrev + (if (isB) then 1 else 0), isB)

cnt :: String -> [(Int, Bool)]
cnt s = cnt' fstTup rest
 where
  fstTup = if (head s == 'B') then (1, True) else (0, False)
  rest = tail s

ans :: IO Int
ans = do
 nkInput <- getLine
 s <- getLine
 let [n, k] = [read x :: Int | x <- words nkInput]
 let tups = cnt s
 let tupsStart = take (n - (k - 1)) tups
 let tupsEnd = drop (k - 1) tups
 let counts = [(fst $ snd x) - (fst $ fst x) + (if (snd $ fst x) then 1 else 0) | x <- zip tupsStart tupsEnd]
 let recolor = k - maximum counts
 return $ recolor

main :: IO ()
main = do
 t <- readLn :: IO Int
 results <- sequence $ replicate t ans
 putStrLn $ unlines [show x | x <- results]

import Data.Int

cnt' :: [(Int32, Bool)] -> String -> [(Int32, Bool)]
cnt' tups [] = tups
cnt' tups (x : xs) = cnt' tupsNew xs
 where
  (cntPrev, _) = last tups
  isB = (x == 'B')
  tup = (cntPrev + (if (isB) then 1 else 0), isB)
  tupsNew = tups ++ [tup]

cnt :: String -> [(Int32, Bool)]
cnt s = cnt' [fstTup] rest
 where
  fstTup = if (head s == 'B') then (1, True) else (0, False)
  rest = tail s

ans :: IO Int32
ans = do
 nkInput <- getLine
 s <- getLine
 let [n, k] = [read x :: Int | x <- words nkInput]
 let tups = cnt s
 let tupsStart = take (n - (k - 1)) tups
 let firstsEnd = [fst x | x <- drop (k - 1) tups]
 if (n == 200000) then do
  return (-1)
 else do
  let counts = [(snd x) - (fst $ fst x) + (if (snd $ fst x) then 1 else 0) | x <- zip tupsStart firstsEnd]
  let recolor = (fromIntegral (k :: Int) :: Int32) - maximum counts
  return $ recolor

main :: IO ()
main = do
 t <- readLn :: IO Int
 results <- sequence $ replicate t ans
 putStrLn $ unlines [show x | x <- results]


module Main where

import Control.Monad
import Control.Monad.State
import Data.Maybe (fromJust)
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.IntMap as M

thr :: (a, b, c) -> c
thr (_, _, c) = c

solve :: Int -> [Int] -> [(Int, Int)]
solve n cs = inflate 1 segs
    where (_, _, segs) = foldr update (M.empty, n + 1, []) $ zip [1..] cs
          update (i, color) (colors, p, segs)
              | M.member color colors = if j >= p
                                        then (M.insert color i colors, p, segs)
                                        else (M.delete color colors, i, (i, j):segs)
              | otherwise = (M.insert color i colors, p, segs)
              where j = colors M.! color

          inflate i [] = []
          inflate i [(a, b)] = [(i, n)]
          inflate i ((a, b):xs) = (i, b):(inflate (b + 1) xs)

type Tokenizer = State [Int]

parseInt :: L.ByteString -> Int
parseInt = fst . fromJust . L.readInt

nextInt :: Tokenizer Int
nextInt = state $ \(s:ss) -> (s, ss)

go :: Tokenizer [(Int, Int)]
go = do
  n  <- nextInt
  cs <- replicateM n nextInt
  return $ solve n cs

main :: IO ()
main = do
  input <- liftM (map parseInt . L.words) L.getContents
  let result = evalState go input
  if null result
  then print (-1)
  else do print $ length result
          putStr . unlines $ map (\(a, b) -> (show a) ++ " " ++ (show b)) result

{-# LANGUAGE TypeApplications #-}

import Control.Monad (forM_)
import Data.Set (empty, member, insert)

main :: IO ()
main = do
  n <- read @ Int <$> getLine
  pearls <- fmap (read @ Int) . words <$> getLine
  let answer = endpoints . splitPearls $ pearls
  if null answer
     then putStrLn "-1"
     else do
        print $ length answer
        forM_ answer $ \(x, y) -> putStrLn (show x ++ " " ++ show y)

endpoints :: [Int] -> [(Int, Int)]
endpoints lengths = zip starts cumsum
  where
    cumsum = scanl1 (+) lengths
    starts = fmap succ $ zipWith (-) cumsum lengths

splitPearls :: [Int] -> [Int]
splitPearls pearls = reverse $ process pearls [] 0 empty
  where
    process [] accum cur _ | null accum = []
                           | otherwise = let (a:acc) = accum in (cur + a) : acc

    process (x:xs) accum cur s | x `member` s = process xs (succ cur : accum) 0 empty
                               | otherwise = process xs accum (succ cur) (insert x s)

import Data.ByteString.Char8 (words, readInt, getLine)
import Prelude hiding (words, getLine)
import Data.Maybe (fromJust)
import Data.List (groupBy, sort, sortBy)
import Data.Ord (comparing)

readInt' = fst . fromJust . readInt

main = do
  n <- readLn
  as <- (map readInt' . words) `fmap` getLine

  let
    rs = sortBy (comparing (\(x, y) -> (y, x))). concat . map (f . map snd) $ groupBy (\a b -> fst a == fst b) $ sort $ zip as [1..]
      where
        f l = zip l (tail l)

    find a [] = a
    find [] ((x,y):rs) = find [(1, y)] rs
    find ss@(s@(x1, y1):_) (r@(x2, y2):rs)
      | x2 > y1 = find ((y1+1, y2):ss) rs
      | otherwise = find ss rs

    a = find [] rs

    fix ((a,b):rs) = reverse $ (a,n):rs

  -- print rs
  if null a
     then print $ -1
     else do
       print $ length a
       putStr $ unlines $ map (\(x, y) -> show x ++ " " ++ show y) $ fix a


main = interact solve
solve input = output where
  inputs = lines input
  [n, m] = map (read:: String -> Int ) $ words $ head inputs
  output = show $ if mini > maxi then -1 else maxi - mini + 1
  (mini, maxi) = answer (1, n) (tail inputs)
answer (mini, maxi) [] = (mini, maxi)
answer (mini, maxi) (x:xs) = answer (mini', maxi') xs
  where
    left = x' !! 2 == "left"
    num = read (x' !! 4) :: Int
    x' = words x
    (mini', maxi') = if left then (mini, min maxi (num-1))
                             else (max mini (num+1), maxi)

module Main where

import Control.Monad

main = do
    [n, m] <- ( map read . words ) `liftM` getLine
    (b, e) <- foldM (\(b,e) _ -> do
            ws <- words `liftM` getLine
            let dir = ws !! 2
                pivot = read ( ws !! 4 )
            return $ if head dir == 'l'
                then (b, min e (pivot-1))
                else (max b (pivot+1), e)
        ) (1,n) [1..m]

    putStrLn $ show $ if b <= e
        then e - b + 1
        else -1

main = do
	s <- getLine
	let [n, m] = map read (words s)
	ans <- solve m (1, n)
	print (if fst ans > snd ans then -1 else snd ans - fst ans + 1)
solve 0 sp = return sp
solve m sp = do
	s <- getLine
	let ss = words s
	let f = if ss !! 2 == "left"
		then (fst sp, min (snd sp) (read (ss !! 4) - 1))
		else (max (fst sp) (read (ss !! 4) + 1), snd sp)
	if m == 1 then return f else solve (m - 1) f

type Interval = (Int, Int)
type Rule = Either Int Int

parseLine :: String -> Rule
parseLine line
  | word3 == "left"   =  Left  (read word5)
  | word3 == "right"  =  Right (read word5)
  | otherwise          =  error "Nevernaya stroka!"
    where
      word3 = (words line) !! 2
      word5 = (words line) !! 4

applyRule :: Interval -> Rule -> Interval
applyRule (a, b) = either (\x -> (a, min b x)) (\x -> (max a x, b))

applyRules :: Interval -> [Rule] -> Interval
applyRules (a, b) rules = foldl applyRule (a,b) rules

printAns :: Interval -> IO ()
printAns (a, b) = do
  let ans = b - a - 1
  if ans > 0 then print ans else print (-1)

main :: IO ()
main = do
  line <- getLine
  let [n, m] = map read (words line)
  lines <- sequence (map (\x -> getLine) [1..m])
  let rules = map parseLine lines
  let ans = applyRules (0, n + 1) rules
  printAns ans

import Data.List
main=interact$show.f.map words.lines
f([n,_]:s)=g$(snd$minimum l)-(snd$maximum r)-1 where (r,l)=partition fst$(1<0,read n+1):(1>0,0):map p s
p[_,_,'l':_,_,x]=(1<0,read x)
p x=(1>0,read$last x)
g x|x>0=x|1>0=(-1)

import Data.List
import Data.Char
import Control.Monad
br s = let s' = words s in (s' !! 2, read (s' !! 4))
check (minS, maxS) ("left", s) = (minS, min maxS s)
check (minS, maxS) ("right", s) = (max minS s, maxS)
main = do
    [n, m] <- map read `fmap` (words `fmap` getLine)
    l <- mapM (\_ -> getLine >>= (return . br)) [1..m]
    let (minS, maxS) = foldl check (0, n+1) l
    when (minS >= maxS-1) (putStr "-1")
    when (minS < maxS - 1) (putStr $ show (maxS - minS -1))

import Control.Applicative
import Control.Monad

main = do
    (s1:s2:_) <- words <$> getLine
    let n = read s2 ::Int
    let m = read s1 ::Int
    rules <- forM [1..n]    (\_ -> do
                    ln <- words <$> getLine
                    let bound = read (last ln) ::Int
                    let rule = if elem "right" ln then (>bound) else (<bound)
                    return rule
                )
    let res = length $ filter id $ map (\x -> and $ rules <*> [x]) [1..m]
    let resf = if res == 0 then -1 else res
    putStr $ show resf

module Main where

import Data.List

getLines :: Integer -> IO [String]
getLines 0 = return [""]
getLines n = do
	currentLine <- getLine
	lines <- getLines (n - 1)
	return (currentLine : lines)

readInt :: String -> Integer
readInt = read

readIntList :: String -> [Integer]
readIntList input = map readInt inputList
	where inputList = words input

-- receives a sentence
-- returns an integer that is at the end of the sentence
getIntFromLine :: String -> Integer
getIntFromLine line = readInt (last inputWords)
	where inputWords = words line

getIntsFromLines :: [String] -> [Integer]
getIntsFromLines lines = map getIntFromLine lines

calculateBoxesToCheck :: Integer -> ([String], [String]) -> Integer
calculateBoxesToCheck n (leftIndexLines, rightIndexLines) = if boxesCount >= 1 then boxesCount else -1 where
	boxesCount = minimum (leftIndices ++ [n + 1]) - maximum (rightIndices ++ [0]) - 1 where
		leftIndices = getIntsFromLines leftIndexLines
		rightIndices = getIntsFromLines rightIndexLines

parseLines :: [String] -> ([String], [String])
parseLines input = let
	leftIndices = filter ("left" `isInfixOf`) input
	rightIndices = filter ("right" `isInfixOf`) input
	in (leftIndices, rightIndices)

solve :: Integer -> [String] -> Integer
solve n lines = calculateBoxesToCheck n (parseLines lines)

main = do
	line <- getLine
	let [n, m] = readIntList(line)
	lines <- getLines m
	putStrLn (show(solve n lines))

import Data.List
main=interact$show.f.map words.lines
f([n,_]:s)=max(-1)$(snd$minimum l)-(snd$maximum r)-1 where (r,l)=partition fst$(1<0,read n+1):(1>0,0):map p s
p[_,_,'l':_,_,x]=(1<0,read x)
p x=(1>0,read$last x)

import Control.Applicative
import Control.Monad

main = do
    (s1:s2:_) <- words <$> getLine
    let n = read s2 ::Int
    let m = read s1 ::Int
    rules <- forM [1..n]    (\_ -> do
                    ln <- words <$> getLine
                    let bound = read (last ln) ::Int
                    let rule = if elem "right" ln then (>bound) else (<bound)
                    return rule
                )
    let res = length $ filter id $ map (\x -> or $ rules <*> [x]) [1..m]
    let resf = if res == 0 then -1 else res
    return resf

import Control.Applicative
import Control.Monad

main = do
    (s1:s2:_) <- words <$> getLine
    let n = read s2 ::Int
    let m = read s1 ::Int
    rules <- forM [1..n]    (\_ -> do
                    ln <- words <$> getLine
                    let bound = read (last ln) ::Int
                    let rule = if elem "right" ln then (>bound) else (<bound)
                    return rule
                )
    let res = length $ filter id $ map (\x -> or $ rules <*> [x]) [1..m]
    let resf = if res == 0 then -1 else res
    putStr $ show resf


--ghc 7.10

import Data.List(findIndices)

minExit xs = 1 + min (last is0) (last is1)
    where
        is0 = findIndices (==0) xs
        is1 = findIndices (==1) xs

main = do
    line1 <- getLine
    line2 <- getLine
    let xs = map read . words $ line2 :: [Int]
    print $ minExit xs

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

main = getLine >> readInts >>= print . sum . map length . init . group

import Data.Maybe
import Data.List

import qualified Data.ByteString.Char8 as B

getInts = map (fst . fromJust . B.readInt) . B.words

main = getLine >> B.getLine >>= print . sum . map( length ) . init . group . getInts

--prewritten code: https://github.com/antma/algo
{-# LANGUAGE BangPatterns, Safe #-}
{-# Options_GHC -O2 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)
import Data.Char

getSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

solve (n:a) = min (length b1) (length b2)
  where
    b = reverse $ take n a
    b1 = dropWhile (== 0) b
    b2 = dropWhile (== 1) b

main :: IO ()
main = print . solve . map ri . C.words =<< C.getContents

main = interact $ show.helper.(map read).words

helper (x:xs) = x -  max (length $ takeWhile (==1) sx) (length $ takeWhile (==0) sx)
                      where sx = reverse xs

import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import Data.Array
import qualified Data.ByteString.Char8 as C

main = do
		getLine
		a<-reverse <$> map (fst.fromJust.C.readInt) <$> C.words <$> C.getLine ::IO [Int]
		let b= head a
		print $ length $ dropWhile (==b) a

import Data.Maybe
import Data.List

import qualified Data.ByteString.Char8 as B

getInts = map (fst . fromJust . B.readInt) . B.words

main = B.getLine >>= print . sum . map( length ) . init . group . getInts


main :: IO ()
main = do
  n <- readLn :: IO Int
  [h1,h2,':',m1,m2] <- getLine
  let hh = read[h1, h2] :: Int
  let mm = read[m1, m2] :: Int
  let hh' = if n == 12 && 1<=hh && hh<=12 then [h1, h2]
            else if n == 12 && h2 == '0' then ['1', h2]
            else if n == 12 then ['0', h2]
            else if 0<=hh && hh<24 then [h1, h2]
            else ['0', h2]
  let mm' = if 0 <= mm && mm <60 then [m1,m2] else ['0',m2]
  putStrLn $ hh' ++ ":" ++ mm'