main = do
    input <- getContents
    let process = putStrLn . show . maxFrames
    mapM_ process $ cases $ lines input

cases :: [String] -> [[Int]]
cases [] = []
cases (_:x:xs) = list:cases xs
    where
        list = (map read $ words x)::[Int]

maxFrames :: [Int] -> Int
maxFrames list = (maxFrames' list) `div` 2

maxFrames' :: [Int] -> Int
maxFrames' [] = 0
maxFrames' list@(x:_) = ((counter `div` 2) + maxFrames' rest)
    where
        (counter, rest) = countAndClean x list 0

countAndClean :: Int -> [Int] -> Int -> (Int, [Int])
countAndClean _ [] counter = (counter, [])
countAndClean x (y:ys) counter
    | x == y    = countAndClean x ys (counter+1)
    | otherwise = (newCounter, y:list)
    where
        (newCounter, list) = countAndClean x ys counter

import Data.List
import IO

solve :: [Int] -> Int
solve = (`div`2) . sum . map ((`div`2) . length) . group . sort

main = print . solve . map read . words . head . tail . lines =<< hGetContents stdin

-- vim: set expandtab:

import qualified Data.Map as Map
solve :: [Int] -> Int
solve xs = halfsticks `div` 2
    where sticks = foldr step Map.empty xs
              where step x acc = Map.insertWith (+) x 1 acc
          halfsticks = foldl (\acc x -> acc + x `div` 2) 0 (map snd (Map.toList sticks))

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

import Data.List

main = do
	getLine
	xs <- fmap (map read . words) getContents :: IO [Int]
	print $ (sum $ map ((`div` 2) . length) $ group $ sort xs) `div` 2

import Data.List

main = do
	getLine
	a <- fmap (map (read::String->Int) . words) getLine
	print $ (flip div 2) .sum . map ((flip div 2).length) . group . sort $ a

import Data.List

main = do
	n <- fmap (fromInteger.read) getLine
	a <- fmap ((map (fromInteger.read)) . words) getLine
	let b = map length $ group . sort $ a
	let c = sum $ map (flip div 2) b
	print $ c `div` 2

import Data.List

main = do
	n <- fmap (fromInteger.read) getLine
	a <- fmap (map (fromInteger.read) . words) getLine
	let b = map length . group . sort $ a
	let c = sum $ map (flip div 2) b
	print $ c `div` 2

import Control.Applicative
import Data.List

solve a = let arr = [(length $ elemIndices i a) `div` 2 | i <- [1..100]]
          in sum arr `div` 2

main = do
  n <- getLine
  a <- map read <$> (words <$> getLine)
  print $ solve a

module Main where

    -- Java-крестьяне должны страдать!

    import Data.List (sort, foldl', genericLength, group)

    main :: IO ()
    main = do
        n <- fmap read getLine :: IO Int
        sticks <- fmap (map read . words) getLine :: IO [Int]
        putStrLn . show $ flip div 2 $
            foldl' summate 0 (group . sort $ sticks)
            where summate s xs = s + (genericLength xs `div` 2)

import List

readWords :: IO [String]
readWords = getLine >>= return . words

reads :: Read a => IO [a]
reads = readWords >>= return . (map read)

solve :: [Int] -> Int
solve xs = div (countPairs (sort xs)) 2
  where
    countPairs (x:y:xs)
      | x == y     =  1 + countPairs xs
      | otherwise  =  countPairs (y:xs)
    countPairs _ = 0

main :: IO ()
main = do
    getLine >> Main.reads >>= print . solve

import List

pairs :: [Int] -> Int
pairs xs = sum $ map (\xs -> div (length xs) 2) $ group $ sort xs
main = interact $ show.(\x -> x `div` 2).pairs.map read.tail.words

import Data.List
main = do line <- getLine
          line <- getLine
          print $ ((\x -> x `div` 2) . sum . (map (\x -> (length x) `div` 2)) . group . sort . (map (\x -> read x::Int)) . words) line

import Data.List
main = print . (`div` 2) . sum . map ((`div` 2) . length) . group . sort . map (read :: String -> Int) . tail . words =<< getContents

module Main where

import Data.List

main = do
  getLine
  cs <- (map read . words) `fmap` getLine
  print (answer cs)

answer :: [Int] -> Int
answer cs = (pr (sort cs)) `div` 2
  where
    pr (a:b:sp) | a == b = 1 + pr sp
                | True   = pr (b:sp)
    pr _ = 0

{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}
{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-orphans #-}

import Control.Applicative
import Data.List

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

main :: IO ()
main = do
  n <- readLn
  xs :: [Int] <- take n <$> readNums
  let ys = parse $ sort xs
  print $ length ys `quot` 2
 where
  parse (x : y : zs)
    | x == y    = x : parse zs
    | otherwise = parse (y : zs)
  parse _       = []

import System.IO
import Data.List

parse :: Read a => Num a => String -> [a]
parse stuff =
    map read $ words $ dropWhile (/= '\n') stuff

calc :: [Int] -> Int
calc nums =
    let groups = (map length $ group $ sort nums :: [Int])
        edges = (map (\x -> div x 2) groups)
        res = (sum edges) `div` 2
    in res

main = do
    stuff <- getContents
    putStrLn (show $ calc $ parse stuff)

import List

pairs :: [Int] -> Int
pairs xs = pairs' $ sort xs
    where pairs' (a:b:xs) | a == b = 1 + pairs' xs
                          | otherwise = pairs' xs
          pairs' _ = 0

main = interact $ show.(\x -> x `div` 2).pairs.map read.tail.words

import Data.List
main = do line <- getLine
          line <- getLine
          print $ ((\x -> x `div` 2) . sum . (map (\x -> (length x) `div` 2)) . group . sort . concat . words) line


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

process d = do
		let e = sum $ map (\z-> if z >0 then z-1 else if z<0 then (-1-z) else 1) d
		let e1 = if elem 0 d then 0
			    		else
						if even (length ( filter (<0) d)) then 0
								  			else 2
		print $ e+e1

main = do
		getLine
		d<-map read <$> words <$> getLine ::IO [Integer]
		process d

main = do
    n <- getLine
    a <- getLine
    print (solve (read n) (map read $ words a))

count :: [Integer] -> (Integer, Integer, Integer, Integer)
count [] = (0, 0, 0, 0)
count (x:xs)
    | x < 0 = (cn+1, c0, cp, cst + (-1 - x))
    | x == 0 = (cn, c0+1, cp, cst + 1)
    | x > 0 = (cn, c0, cp+1, cst + (x - 1))
    where (cn,c0,cp,cst) = count xs

solve :: Integer -> [Integer] -> Integer
solve n a =
    let (cn, c0, cp, cst) = count a in
    if even cn
        then cst
    else if (c0 > 0)
        then cst
    else (cst + 2)

import Control.Monad
import Data.String
import Data.Maybe
readListRec :: Int -> IO [String]
readListRec lineNumber =
  if (lineNumber == 0)
  then return []
  else
    getLine >>= \newLine ->
    (newLine :) <$> readListRec(lineNumber - 1)

parseLineToInt :: String -> [Integer]
parseLineToInt data_s = do
  (read::String->Integer) <$> (words data_s)

createLists :: Int -> ([Int], [Int])
createLists 0  = ([],[])
createLists n = let
                    (l, r) = createLists (n - 1)
                in ((2 * n) : r, (2 * n - 1) : l)

main = do
  _ <- getLine
  aS <- getLine
  let (a,b) = foldr f (0, Just 0) $ parseLineToInt aS where
      f x (y, Nothing) = (y + abs(1 - abs x),Nothing)
      f 0 (y, _) = (y + 1, Nothing)
      f x (y, Just z) = (y + abs(1 - abs x), Just (if x > 0 then z else (z + 1)))
  putStrLn $ show $ a + 2 * (mod (fromMaybe 0 b) 2)

import Control.Monad
import Data.String
import Data.Maybe
readListRec :: Int -> IO [String]
readListRec lineNumber =
  if (lineNumber == 0)
  then return []
  else
    getLine >>= \newLine ->
    (newLine :) <$> readListRec(lineNumber - 1)

parseLineToInt :: String -> [Int]
parseLineToInt data_s = do
  (read::String->Int) <$> (words data_s)

createLists :: Int -> ([Int], [Int])
createLists 0  = ([],[])
createLists n = let
                    (l, r) = createLists (n - 1)
                in ((2 * n) : r, (2 * n - 1) : l)

main = do
  _ <- getLine
  aS <- getLine
  let (a,b) = foldr f (0, Just 0) $ parseLineToInt aS where
      f x (y, Nothing) = (y + abs(1 - abs x),Nothing)
      f 0 (y, _) = (y + 1, Nothing)
      f x (y, Just z) = (y + abs(1 - abs x), Just (if x > 0 then z else (z + 1)))
  putStrLn $ show $ a + mod (fromMaybe 0 b) 2

import Control.Monad
import Data.String
import Data.Maybe
readListRec :: Int -> IO [String]
readListRec lineNumber =
  if (lineNumber == 0)
  then return []
  else
    getLine >>= \newLine ->
    (newLine :) <$> readListRec(lineNumber - 1)

parseLineToInt :: String -> [Int]
parseLineToInt data_s = do
  (read::String->Int) <$> (words data_s)

createLists :: Int -> ([Int], [Int])
createLists 0  = ([],[])
createLists n = let
                    (l, r) = createLists (n - 1)
                in ((2 * n) : r, (2 * n - 1) : l)

main = do
  _ <- getLine
  aS <- getLine
  let (a,b) = foldr f (0, Just 0) $ parseLineToInt aS where
      f x (y, Nothing) = (y + abs(1 - abs x),Nothing)
      f 0 (y, _) = (y + 1, Nothing)
      f x (y, Just z) = (y + abs(1 - abs x), Just (if x > 0 then z else (z + 1)))
  putStrLn $ show $ a + 2 * (mod (fromMaybe 0 b) 2)

main = do
    n <- getLine
    a <- getLine
    print (solve (read n) (map read $ words a))

count :: [Int] -> (Int, Int, Int, Int)
count [] = (0, 0, 0, 0)
count (x:xs)
    | x < 0 = (cn+1, c0, cp, cst + (-1 - x))
    | x == 0 = (cn, c0+1, cp, cst + 1)
    | x > 0 = (cn, c0, cp+1, cst + (x - 1))
    where (cn,c0,cp,cst) = count xs

solve :: Int -> [Int] -> Int
solve n a =
    let (cn, c0, cp, cst) = count a in
    if even cn
        then cst
    else if (c0 > 0)
        then cst
    else (cst + 2)

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

process d = do
		let e = sum $ map (\z-> if z >0 then z-1 else if z<0 then (-1-z) else 1) d
		let e1 = if elem 0 d then 0
			    		else
						if even (length ( filter (<0) d)) then 0
								  			else 2
		print $ e+e1

main = do
		getLine
		d<-map read <$> words <$> getLine ::IO [Int]
		process d


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

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.Functor.Identity
--import Data.Semigroup

import Data.List
import Data.Int
-- no Data.Bits needed

class  Put t  where
  putit :: BoundedPrim t
instance  Put Int  where
  putit = intDec
instance  Put Char  where
  putit = liftFixedToBounded char7
instance  (Put x, Put y) => Put (x, y)  where
  putit = putit >*< putit

querySum :: BoundedPrim (Int, Int)
-- This is a stupid way to do things
querySum = let
  orp = ('o', ('r', ' '))
  andp = ('a', ('n', ('d', ' ')))
  in
  (\(i, j) ->
    (((((((((orp, i), ' '), j), '\n'), andp), i), ' '), j), '\n')) >$< putit

main :: IO ()
main = (P.words <$> P.getContents >>=) $ evalStateT $ do
  [n, k] <- getInts 2
  let  queries = (1, 2) : (1, 3) : (2, 3) : map ((,) 1) [4 .. n]
  lift $ B.hPutBuilder stdout $ primMapListBounded querySum queries
  lift $ hFlush stdout
  s12 : s13 : s23 : s1ks <- liftPure $ replicateM n $ do
    ~[ov, av] <- getInts 2
    pure $ fromIntegral $  ov + av
  let
    s123 = div (s12 + s13 + s23) 2
    s123 :: Int64
    v1 = s123 - s23
    v2 = s123 - s13
    v3 = s123 - s12
    vs = v1 : v2 : v3 : map (subtract v1) s1ks
  lift $ putStr "finish "
  lift $ print $ sort vs !! (k - 1)

type SP = StateT [P.ByteString]
type SIO = SP IO

liftPure :: Monad m => SP Identity t -> SP m t
liftPure = mapStateT (pure . runIdentity)

getNext :: Monad m => Int -> SP m [P.ByteString]
getNext = state . splitAt

getInts :: Monad m => Int -> SP m [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]

{-# 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
import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import System.IO

solve3 :: (Int,Int,Int) -> (Int,Int,Int)
solve3 (ab,bc,ca) = (a,b,c) where
  a_c=ab-bc
  a2 = ca+a_c
  a = a2`div`2
  b = ab-a
  c = ca-a

askAll :: Int -> Bu.Builder
askAll n = ask3 <> askRestOr <> askRestAnd where
  ask s i j = Bu.string7 (s ++ " " ++ show i ++ " " ++ show j ++ "\n") <> flush
  ask3 = mconcat [ask s i j | i<-[1,2,3],j<-[i+1..3],s<-["or","and"]]
  askRestOr = mconcat [ask "or" 1 j | j<-[4..n]]
  askRestAnd = mconcat [ask "and" 1 j | j<-[4..n]]

tell :: Int -> Bu.Builder
tell x = Bu.string7 ("finish " ++ show x ++ "\n") <> flush

solve :: St Bu.Builder
solve = do
  ~[n,k] <- getIntegrals 2
  ~[aorb,aandb,aorc,aandc,borc,bandc] <- getIntegrals 6
  let (a,b,c) = solve3 ((aorb+aandb), (borc+bandc), (aorc+aandc))
  restOr <- getIntegrals (n-3)
  restAnd <- getIntegrals (n-3)
  let xs = a:b:c: zipWith (\x y->x+y-a) restOr restAnd
  return $ askAll n <> tell (L.sort xs !! (k-1))

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

getByteString :: St B8.ByteString
getByteString = state getNext where
  getNext [] =  (B8.take 0 (B8.pack "."),[])
  getNext (w:ws) =  (w,ws)

getIntegrals :: Num t => Int -> St [t]
getIntegrals n = replicateM n $ convertToNum <$> getByteString where
  convertToNum x =  fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  bytestrings <- B8.words <$> B8.getContents
  B8.putStrLn $ Bu.toLazyByteString $ evalState solve bytestrings

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

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.Functor.Identity
--import Data.Semigroup

import Data.List
import Data.Array.Unboxed
import Data.Array.ST.Safe
import Control.Monad.ST

import Data.Bits -- only for bucket sort

class  Put t  where
  putit :: BoundedPrim t
instance  Put Int  where
  putit = intDec
instance  Put Char  where
  putit = liftFixedToBounded char7
instance  (Put x, Put y) => Put (x, y)  where
  putit = putit >*< putit

querySum :: BoundedPrim (Int, Int)
-- This is a stupid way to do things
querySum = let
  orp = ('o', ('r', ' '))
  andp = ('a', ('n', ('d', ' ')))
  in
  (\(i, j) ->
    (((((((((orp, i), ' '), j), '\n'), andp), i), ' '), j), '\n')) >$< putit

stableBucketSortOn3 :: (Int -> Int) -> (Int, Int) -> [Int] -> UArray Int Int
stableBucketSortOn3 fun bnds li = runSTUArray $ do
  counts <- newArray bnds 0 :: ST s (STUArray s Int Int)
  forM_ li $ \v -> do
    let  bucket = fun v
    ct <- (+ 1) <$> readArray counts bucket
    writeArray counts bucket ct
  totSz <- (\fun -> foldM fun 0 $ range bnds) $ \prevTot bucket -> do
    cct <- readArray counts bucket
    prevTot + cct <$ writeArray counts bucket prevTot
  ansArr <- newArray_ (1, totSz) :: ST s (STUArray s Int Int)
  forM_ li $ \v -> do
    let  bucket = fun v
    ct <- (+ 1) <$> readArray counts bucket
    writeArray counts bucket ct
    writeArray ansArr ct v
  pure ansArr

main :: IO ()
main = (P.words <$> P.getContents >>=) $ evalStateT $ do
  [n, k] <- getInts 2
  let  queries = (2, 3) : map ((,) 1) [2 .. n]
  lift $ P.putStr $ B.toLazyByteString $ primMapListBounded querySum queries
  lift $ hFlush stdout
  s23 : s1ks <- liftPure $ replicateM n $ do
    ~[ov, av] <- getInts 2
    pure $ fromIntegral $  ov + av
  let
    v1 = div (sum (take 2 s1ks) - s23) 2
    vs = v1 : map (subtract v1) s1ks
    mask = bit 15 - 1
    lvs = stableBucketSortOn3 (.&. mask) (0, mask) vs
    svs = stableBucketSortOn3 (`shiftR` 15) (0, mask) $ elems lvs
  lift $ putStr "finish " >> print (svs ! k)

type SP = StateT [P.ByteString]
type SIO = SP IO

liftPure :: Monad m => SP Identity t -> SP m t
liftPure = mapStateT (pure . runIdentity)

getNext :: Monad m => Int -> SP m [P.ByteString]
getNext = state . splitAt

getInts :: Monad m => Int -> SP m [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]

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

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.Functor.Identity
import Data.Semigroup

import Data.List
-- no Data.Bits needed

class  Put t  where
  putit :: BoundedPrim t
instance  Put Int  where
  putit = intDec
instance  Put Char  where
  putit = liftFixedToBounded char7
instance  (Put x, Put y) => Put (x, y)  where
  putit = putit >*< putit

querySum :: BoundedPrim (Int, Int)
querySum = let
  orp = ('o', ('r', ' '))
  andp = ('a', ('n', ('d', ' ')))
  in
  (\(i, j) ->
    (((((((((orp, i), ' '), j), '\n'), andp), i), ' '), j), '\n')) >$< putit

main :: IO ()
main = (P.words <$> P.getContents >>=) $ evalStateT $ do
  [n, k] <- getInts 2
  let  queries = (1, 2) : (1, 3) : (2, 3) : map ((,) 1) [4 .. n]
  lift $ B.hPutBuilder stdout $ primMapListBounded querySum queries
  lift $ hFlush stdout
  s12 : s13 : s23 : s1ks <- liftPure $ replicateM n $ do
    ~[ov, av] <- getInts 2
    pure $ ov + av
  let
    s123 = div (s12 + s13 + s23) 2
    v1 = s123 - s23
    v2 = s123 - s13
    v3 = s123 - s12
    vs = v1 : v2 : v3 : map (subtract v1) s1ks
  lift $ putStr "finish "
  lift $ print $ sort vs !! (k - 1)

type SP = StateT [P.ByteString]
type SIO = SP IO

liftPure :: Monad m => SP Identity t -> SP m t
liftPure = mapStateT (pure . runIdentity)

getNext :: Monad m => Int -> SP m [P.ByteString]
getNext = state . splitAt

getInts :: Monad m => Int -> SP m [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]


{-# LANGUAGE BangPatterns #-}

import Data.Array.Base

main = do
  _ <- getLine
  tape <- getLine
  let query [l,r] = run $ take(r-l+1) $ drop(l-1) tape
  interact $ unlines.map(show.query.map read.words).lines

data Dir = L | R deriving Eq
data M = M String Dir String String

instance Show M where
  show (M ns _ _ _) = unwords $ map (show.unsafeAt arr.fromEnum) ['0'..'9']
   where
     !arr = unsafeAccumArray (+) 0 (0,fromEnum '9') $ map(\c->(fromEnum c,1)) ns :: UArray Int Int

run tape = go $ M [] R [] tape
go (M ns _ ('<':ls) ('<':rs)) = go $ M ns       L ls ('<':rs)
go (M ns _ ('>':ls) ('<':rs)) = go $ M ns       L ls ('>':rs)
go (M ns _ ls ('>':'>':rs))   = go $ M ns       R ls ('>':rs)
go (M ns _ ls ('>':'<':rs))   = go $ M ns       R ls ('<':rs)
go (M ns _ (l:ls) ('<':rs))   = go $ M ns       L ls (l:'<':rs)
go (M ns _ ls ('>':rs))       = go $ M ns       R ('>':ls) rs
go (M ns L (l:ls) ('0':rs))   = go $ M ('0':ns) L ls (l:rs)
go (M ns R ls ('0':rs))       = go $ M ('0':ns) R ls rs
go (M ns L (l:ls) (n:rs))|'0'<=n && n<='9' = go $ M (n:ns) L ls (l:pred n:rs)
go (M ns R ls (n:rs))    |'0'<=n && n<='9' = go $ M (n:ns) R (pred n:ls) rs
go (M ns L [] (n:_))     |'0'<=n && n<='9' = M (n:ns) L [] []
go m = m

main = interact $ unlines . (\(_:s:qs) -> map (unwords . map show . solve s . map read . words) qs) . lines

solve seq [l, r] = step (replicate 10 0) '>' ("", drop (l-1) $ take r seq)

step ans _ (x, '>':'>':y) = step ans '>' (x, '>':y)
step ans _ (x, '>':'<':y) = step ans '<' (x, '<':y)
step ans _ ('>':x, '<':y) = step ans '>' (x, '>':y)
step ans _ ('<':x, '<':y) = step ans '<' (x, '<':y)
step ans _ (x, '>':c:y) = step ans '>' ('>':x, c:y)
step ans _ (c:x, '<':y) = step ans '<' (x, c:'<':y)
step ans _ (x, ">") = ans
step ans _ ([], '<':y) = ans
step ans '>' (x, '0':y) = step (inc 0 ans) '>' (x, y)
step ans '>' (x, c:y) = step (inc (read [c]) ans) '>' (pred c:x, y)
step ans '>' (x, []) = ans
step ans '<' (c:x, '0':y) = step (inc 0 ans) '<' (x, c:y)
step ans '<' (d:x, c:y) = step (inc (read [c]) ans) '<' (x, d:pred c:y)
step ans '<' ([], c:y) = inc (read [c]) ans

inc i ans = take i ans ++ (ans!!i + 1) : drop (i+1) ans

main = interact $ unlines . (\(_:s:qs) -> map (unwords . map show . solve s . map read . words) qs) . lines

solve seq [l, r] = step (replicate 10 0) '>' ("", drop (l-1) $ take r seq)

step ans _ (x, '>':'>':y) = step ans '>' (x, '>':y)
step ans _ (x, '>':'<':y) = step ans '<' (x, '<':y)
step ans _ ('>':x, '<':y) = step ans '>' (x, '>':y)
step ans _ ('<':x, '<':y) = step ans '<' (x, '<':y)
step ans _ (x, '>':c:y) = step ans '>' ('>':x, c:y)
step ans _ (c:x, '<':y) = step ans '<' (x, c:'<':y)
step ans _ (x, ">") = ans
step ans _ ("", '<':y) = ans
step ans '>' (x, '0':y) = step (inc 0 ans) '>' (x, y)
step ans '>' (x, c:y) = step (inc (read [c]) ans) '>' (pred c:x, y)
step ans '<' (c:x, '0':y) = step (inc 0 ans) '<' (x, c:y)
step ans '<' (d:x, c:y) = step (inc (read [c]) ans) '<' (x, d:pred c:y)
step ans _ _ = ans

inc i ans = take i ans ++ (ans!!i + 1) : drop (i+1) ans

main = interact $ unlines . (\(_:s:qs) -> map (unwords . map show . solve s . map read . words) qs) . lines

solve seq [l, r] = step (replicate 10 0) '>' ("", drop (l-1) $ take r seq)

step ans _ (_, []) = ans
step ans '<' ([], _) = ans
step ans _ (x, '>':'>':y) = step ans '>' (x, '>':y)
step ans _ (x, '>':'<':y) = step ans '<' (x, '<':y)
step ans _ ('>':x, '<':y) = step ans '>' (x, '>':y)
step ans _ ('<':x, '<':y) = step ans '<' (x, '<':y)
step ans _ (x, '>':y) = step ans '>' ('>':x, y)
step ans _ (c:x, '<':y) = step ans '<' (x, c:'<':y)
step ans _ (x, '<':y) = ans
step ans '>' (x, '0':y) = step (inc 0 ans) '>' (x, y)
step ans '>' (x, c:y) = step (inc (read [c]) ans) '>' (pred c:x, y)
step ans '<' (c:x, '0':y) = step (inc 0 ans) '<' (x, c:y)
step ans '<' (d:x, c:y) = step (inc (read [c]) ans) '<' (x, d:pred c:y)

inc i ans = take i ans ++ (ans!!i + 1) : drop (i+1) ans

main = interact $ unlines . (\(_:s:qs) -> map (unwords . map show . solve s . map read . words) qs) . lines

solve seq [l, r] = step (replicate 10 0) '>' ("", drop (l-1) $ take r seq)

step ans _ (x, '>':'>':y) = step ans '>' (x, '>':y)
step ans _ (x, '>':'<':y) = step ans '<' (x, '<':y)
step ans _ ('>':x, '<':y) = step ans '>' (x, '>':y)
step ans _ ('<':x, '<':y) = step ans '<' (x, '<':y)
step ans _ (x, '>':y) = step ans '>' ('>':x, y)
step ans _ (c:x, '<':y) = step ans '<' (x, c:'<':y)
step ans _ ([], '<':y) = ans
step ans '>' (x, '0':y) = step (inc 0 ans) '>' (x, y)
step ans '>' (x, c:y) = step (inc (read [c]) ans) '>' (pred c:x, y)
step ans '<' (c:x, '0':y) = step (inc 0 ans) '<' (x, c:y)
step ans '<' (d:x, c:y) = step (inc (read [c]) ans) '<' (x, d:pred c:y)
step ans _ _ = ans

inc i ans = take i ans ++ (ans!!i + 1) : drop (i+1) ans

{-# LANGUAGE BangPatterns #-}

import Data.Array.Base

main = do
  _ <- getLine
  tape <- getLine
  let query [l,r] = run $ take(r-l+1) $ drop(l-1) tape
  interact $ unlines.map(show.query.map read.words).lines

data Dir = L | R deriving Eq
data M = M String Dir String String

instance Show M where
  show (M ns _ _ _) = unwords $ map (show.unsafeAt arr.fromEnum) ['0'..'9']
   where
     !arr = unsafeAccumArray (+) 0 (0,fromEnum '9') $ map(\c->(fromEnum c,1)) ns :: UArray Int Int

run tape = go $ M [] R [] tape
go (M ns _ ('<':ls) ('<':rs)) = go $ M ns       L ls ('<':rs)
go (M ns _ ('>':ls) ('<':rs)) = go $ M ns       L ls ('>':rs)
go (M ns _ ls ('>':'>':rs))   = go $ M ns       R ls ('>':rs)
go (M ns _ ls ('>':'<':rs))   = go $ M ns       R ls ('<':rs)
go (M ns _ (l:ls) ('<':rs))   = go $ M ns       L ls (l:'<':rs)
go (M ns _ ls ('>':rs))       = go $ M ns       R ('>':ls) rs
go (M ns L (l:ls) ('0':rs))   = go $ M ('0':ns) L ls (l:rs)
go (M ns R ls ('0':rs))       = go $ M ('0':ns) R ls rs
go (M ns L (l:ls) (n:rs))     = go $ M (n:ns)   L ls (l:pred n:rs)
go (M ns R ls (n:rs))         = go $ M (n:ns)   R (pred n:ls) rs
go (M ns L [] (n:_)) = M (n:ns) L [] []
go m = m


solve :: [String] -> [String]
solve ws = [(show $ length result),  result]
  where result = concatAll $ rearange $ findPairs ws

rearange :: [(String, String)] -> [(String, String)]
rearange pairs
  | null singles = withoutSingles
  | otherwise = withoutSingles ++ [(head singles)]
  where singles = filter (\(x, y) -> y == "") pairs
        withoutSingles = filter (\(x, y) -> y /= "") pairs

isReversed :: String -> String -> Bool
isReversed a b = a == reverse b

isPalindrome :: String -> Bool
isPalindrome w = w == reverse w

findPairs :: [String] -> [(String, String)]
findPairs [] = []
findPairs [a] = if isPalindrome a then [(a, "")] else []
findPairs (w:ws)
  | null pairs = if isPalindrome w then [(w, "")] ++ findPairs ws else findPairs ws
  | otherwise  = [(w, head pairs)] ++ findPairs ws
  where pairs = (filter (\x -> isReversed w x) ws)

concatAll :: [(String, String)] -> String
concatAll [] = ""
concatAll [(a, b)] = a++b
concatAll ((a, b):xs) = a ++ (concatAll xs) ++ b

main :: IO ()
main = interact (unlines . solve . tail . lines)

import Control.Monad
import qualified Data.Set as ST

type Info = (ST.Set String, String, String, String)

solve :: [String] -> IO ()
solve xss = do
  print (length left + length middle + length right)
  putStrLn (left ++ middle ++ right)
  where
    st = foldl (flip ST.insert) ST.empty xss
    (_,left,middle,right) = foldl step (st, [], [], []) xss
    step :: Info -> String -> Info
    step (st, ls, ms, rs) xs
      | xs == rev = (st, ls, xs, rs)
      | ST.member rev st = (st', ls++xs, ms, rev++rs)
      | otherwise = (st, ls, ms, rs)
        where
          rev = reverse xs
          st' = ST.delete rev $ (ST.delete xs st)

main = do
  [n,m] <- map read . words <$> getLine :: IO [Int]
  xss <- replicateM n $ do
    getLine >>= return
  solve xss


import Data.Map (Map)
import qualified Data.Map as Map
import Maybe
main = interact solve
solve input = output where
  ns = map (read::String->Int) $ words $ head $ lines input
  opt = map s2i $ drop 2 $ lines input
  output = unlines $ map i2s $ answer (num ns) opt
size = ["S","M","L","XL","XXL"]
s2i x = fromJust $ lookup x $ zip size [1..5]
i2s x = size!!(x-1)
num xs = Map.fromList $ zip [1..5] xs
pre = Map.fromList $ zip [1..5]
  [[1,2,3,4,5],[2,3,1,4,5],[3,4,2,5,1],[4,5,3,2,1],[5,4,3,2,1]]
answer :: Map Int Int -> [Int] -> [Int]
answer _ [] = []
answer xs (y:ys) = x : ( answer (Map.adjust (\z->z-1) x xs) ys ) where
  x = choice xs (fromJust $ Map.lookup y pre)
choice :: Map Int Int -> [Int] -> Int
choice _ [] = 0
choice xs (y:ys) = if (fromJust $ Map.lookup y xs)==0 then choice xs ys else y

import Data.Map
main = interact (unlines.sol.words)
sol (s:m:l:xl:xxl:n:xs) = sol' sz (take (read n) xs) [] where
    sz = fromList [("S",read s),("M",read m),("L",read l),("XL",read xl),("XXL",read xxl)]
    sol' sz []     acc = reverse acc
    sol' sz (x:xs) acc = sol' (adjust pred k sz) xs (k:acc) where
        k = k' (ks!x) where k' (k:f) = if sz!k>0 then k else k' f
ks = fromList [("S",["S","M","L","XL","XXL"]),("M",["M","L","S","XL","XXL"]),("L",["L","XL","M","XXL","S"]),("XL",["XL","XXL","L","M","S"]),("XXL",["XXL","XL","L","M","S"])]

solve :: Int -> Int -> Int -> Int -> Int -> [String] -> [String]
solve _ _ _ _ _ []  =  []
solve nS nM nL nXL nXXL ("S":xs)
  | nS > 0  =  "S" : solve (nS-1) nM nL nXL nXXL xs
  | nM > 0  =  "M" : solve nS (nM-1) nL nXL nXXL xs
  | nL > 0  =  "L" : solve nS nM (nL-1) nXL nXXL xs
  | nXL > 0  =  "XL" : solve nS nM nL (nXL-1) nXXL xs
  | nXXL > 0  =  "XXL" : solve nS nM nL nXL (nXXL-1) xs
solve nS nM nL nXL nXXL ("M":xs)
  | nM > 0  =  "M" : solve nS (nM-1) nL nXL nXXL xs
  | nL > 0  =  "L" : solve nS nM (nL-1) nXL nXXL xs
  | nS > 0  =  "S" : solve (nS-1) nM nL nXL nXXL xs
  | nXL > 0  =  "XL" : solve nS nM nL (nXL-1) nXXL xs
  | nXXL > 0  =  "XXL" : solve nS nM nL nXL (nXXL-1) xs
solve nS nM nL nXL nXXL ("L":xs)
  | nL > 0  =  "L" : solve nS nM (nL-1) nXL nXXL xs
  | nXL > 0  =  "XL" : solve nS nM nL (nXL-1) nXXL xs
  | nM > 0  =  "M" : solve nS (nM-1) nL nXL nXXL xs
  | nXXL > 0  =  "XXL" : solve nS nM nL nXL (nXXL-1) xs
  | nS > 0  =  "S" : solve (nS-1) nM nL nXL nXXL xs
solve nS nM nL nXL nXXL ("XL":xs)
  | nXL > 0  =  "XL" : solve nS nM nL (nXL-1) nXXL xs
  | nXXL > 0  =  "XXL" : solve nS nM nL nXL (nXXL-1) xs
  | nL > 0  =  "L" : solve nS nM (nL-1) nXL nXXL xs
  | nM > 0  =  "M" : solve nS (nM-1) nL nXL nXXL xs
  | nS > 0  =  "S" : solve (nS-1) nM nL nXL nXXL xs
solve nS nM nL nXL nXXL ("XXL":xs)
  | nXXL > 0  =  "XXL" : solve nS nM nL nXL (nXXL-1) xs
  | nXL > 0  =  "XL" : solve nS nM nL (nXL-1) nXXL xs
  | nL > 0  =  "L" : solve nS nM (nL-1) nXL nXXL xs
  | nM > 0  =  "M" : solve nS (nM-1) nL nXL nXXL xs
  | nS > 0  =  "S" : solve (nS-1) nM nL nXL nXXL xs

main :: IO ()
main  =  do
    [nS, nM, nL, nXL, nXXL]  <-  getLine >>= return . map read . words
    n  <-  readLn
    xs  <-  getContents >>= return . take n . lines
    mapM_ putStrLn $ solve nS nM nL nXL nXXL xs


import Data.Maybe
q l|null l=Nothing|1>0=Just(head l,last l)
p=q.map fst.filter((=='W').snd).zip[0..]

sr dir i []=(-1)
sr dir i (Nothing:t)=1+sr (-dir) i t
sr 1 i (Just(l,r):t)=1+2*b+f+sr (-1) j t where
  b|i>l=i-l
   |1>0=0
  (f,j)=(r-i,r)
sr (-1) i (Just(l,r):t)=1+2*b+f+sr 1 j t where
  b|i<r=r-i
   |1>0=0
  (f,j)=(i-l,l)

dn (Nothing:h:t) = dn (h:t)
dn l = l

main=interact$show.sr 1 0.reverse.dn.reverse.map p.tail.lines

{-# OPTIONS -O2 #-}
import Data.List

main = do
  s <- getContents
  let
    (grid:ls) = lines s
    [row, col] = map read $ words grid :: [Int]
    ws' = [(i+1, j+1) |i<-[0..row-1], j<-[0..col-1], (ls !! i) !! j == 'W']
    ws = [(r, (minimum [x|(y,x)<-ws', y==r], maximum [x|(y,x)<-ws', y==r])) | r <- [1..row], elem 'W' (ls !! (r-1))]
  print $ search 1 1 ws

search _ _ [] = 0
search row column orig@[(r, (a, b))]
  | row == r = dist goalPos'
  | row + 1 == r = dist goalPos' + 1 + search (row+1) goalPos' orig
  | otherwise = 1 + search (row+1) column orig
  where
    dist x = abs $ x - column
    goalPos' = if mod row 2 == 0 then a else b

search row column orig@((r, (a, b)):(r', (a', b')):l)
  | row == r && row + 1 == r' = dist goalPos + 1 + search (row+1) goalPos ((r', (a', b')):l)
  | row == r = dist goalPos' + 1 + search (row+1) goalPos' ((r', (a', b')):l)
  | row + 1 == r = dist goalPos' + 1 + search (row+1) goalPos' orig
  | otherwise = 1 + search (row+1) column orig
  where
    dist x = abs $ x - column
    goalPos = if mod row 2 == 0 then min a a' else max b b'
    goalPos' = if mod row 2 == 0 then a else b

import Data.List
import qualified Data.Map as Map
import Data.Map ((!))
import Control.Monad
import Control.Applicative
import Debug.Trace

traceS a b = trace (show a) b

type Z = Int

data Dir = L | R deriving Show

antiDir L = R
antiDir R = L

solve :: Z -> Z -> [String] -> Z
solve n m ls = solve' n m ls' 0 R
  where ls' = cutter ls

cutter ls = reverse $ cutter' (reverse ls)

cutter' [] = []
cutter' ls =
  case elemIndex 'W' l of
    Nothing -> cutter' lss
    Just _  -> ls
  where (l:lss) = ls

solve' _ _ [] _ _ = 0
solve' n m [l] c L = c - (elemFind c l)
solve' n m [l] c R = solve' n m [reverse l] (m-c-1) L
solve' n m (l1:lrem@(l2:ls)) c dir =
  abs (t-c) + solve' n m lrem t (antiDir dir) + 1
  where t = getTarget c m l1 l2 dir

getTarget c m l1 l2 L = min t1 t2
  where t1 = elemFind c l1
        t2 = elemFind c l2
getTarget c m l1 l2 R = m - (1 + getTarget (m-c-1) m (reverse l1) (reverse l2) L)

elemFind c l1 =
  case elemIndex 'W' l1 of
    Nothing -> c
    Just t1 -> min t1 c

main = do
  (n,m) <- (\[a,b] -> (a,b)) . map read . words <$> getLine
  ls <- replicateM n getLine
  print $ solve n m ls

module Main where

import Data.List
import Control.Monad

data Dir = LEFT | RIGHT deriving (Show, Eq)

main = do
    [n, m] <- getLine >>= return . map read . words :: IO [Int]

    boards <- replicateM n getLine
    let pivots = map (\l -> if null l then Nothing else Just (head l, last l)) $ map (elemIndices 'W') boards
        (cursor, cost, dir, skip) = foldl' (\(cursor, cost, dir, skip) pivot ->
                let dir' = case dir of
                        LEFT -> RIGHT
                        RIGHT -> LEFT
                in case pivot of
                    Nothing -> (cursor, cost, dir', skip+1)
                    Just (l, r) -> case dir of
                        LEFT -> if cursor <= l
                            then (r, cost+skip+r-cursor, dir', 1)
                            else (r, cost+skip+cursor-l+r-l, dir', 1)
                        RIGHT -> if cursor >= r
                            then (l, cost+skip+cursor-l, dir', 1)
                            else (l, cost+skip+r-cursor+r-l, dir', 1)
            ) (0, 0, LEFT, 0) pivots

    --putStrLn $ show pivots
    --putStrLn $ show (cursor, cost, dir, skip)
    putStrLn $ show cost

import qualified Data.ByteString.Lazy.Char8 as C
import IO
import Data.Maybe

last' l = case (C.elemIndex 'W' . C.reverse) l of
	Nothing -> 0
	Just x -> C.length l - 1 - x
fst' l = case C.elemIndex 'W' l of
	Nothing -> 0
	Just x -> C.length l - 1 - x

solve [] _ = 0
solve [ln] i = max 0 (last' ln - i)
	where n = C.length ln
solve (ln1:ln2:lns) i = let j = max 0 (max (last' ln1) (fst' ln2) - i) in let next = solve (ln2:lns) (n - j - i - 1) in j + next + 1
	where n = C.length ln1

halfrev lns = [if i `mod` 2 == 1 then C.reverse (lns !! i) else (lns !! i) | i <- [0..n-1]]
	where n = length lns

tailcut [] = []
tailcut (x:xs)
	| tailcut xs == [] && C.elemIndex 'W' x == Nothing = []
	| otherwise = (x:tailcut xs)

main = do
	input <- fmap C.lines $ C.hGetContents stdin
	let [n, m] = map (fst . fromJust . C.readInt) . C.words $ head input
	let view = take n $ tail input
	putStrLn . show $ solve (tailcut $ halfrev view) 0

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
{-# 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
    m <- readInt
    grid <- replicateM n (BS.unpack <$> readString)
    return (n, m, grid)
  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

inf = 10^9

solve (n, m, grid) = go (0 : replicate (m-1) inf) True weeds' - 1
  where
    weeds = [ indices
            | (i, row) <- zip [0..] grid
            , let indices = elemIndices 'W' row ++ [0 | i == 0]
            ]

    weeds' = reverse $ dropWhile null $ reverse weeds

    go prev right [] = minimum prev
    go prev right (row:rows) = go end' (not right) rows
      where
        minv = if null row then inf else minimum row
        maxv = if null row then -inf else maximum row

        start = [if right && i > minv || not right && i < maxv then inf else ri + 1 | (i, ri) <- zip [0..] prev]
        end
            | right     = scanl1 (\v x -> (v + 1) `min` x) start
            | otherwise = scanr1 (\x v -> (v + 1) `min` x) start
        end' = [if right && i < maxv || not right && i > minv then inf else min inf ri | (i, ri) <- zip [0..] end]

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

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 qualified Data.ByteString.Lazy.Char8 as C
import IO
import Data.Maybe

last' l = case (C.elemIndex 'W' . C.reverse) l of
	Nothing -> -1
	Just x -> C.length l - 1 - x
fst' l = case C.elemIndex 'W' l of
	Nothing -> -1
	Just x -> C.length l - 1 - x

solve [] _ = -1
solve [ln] i = max (-1) (last' ln - i)
	where n = C.length ln
solve (ln1:ln2:lns) i = let j = max (last' ln1) (fst' ln2) in max (-1) (j - i) + solve (ln2:lns) (n - j - 1) + 1
	where n = C.length ln1

halfrev lns = [if i `mod` 2 == 1 then C.reverse (lns !! i) else (lns !! i) | i <- [0..n-1]]
	where n = length lns

main = do
	input <- fmap C.lines $ C.hGetContents stdin
	let [n, m] = map (fst . fromJust . C.readInt) . C.words $ head input
	let view = take n $ tail input
	putStrLn . show . max 0 $ solve (halfrev view) 0

import qualified Data.ByteString.Lazy.Char8 as C
import IO
import Data.Maybe

last' l = case (C.elemIndex 'W' . C.reverse) l of
	Nothing -> -1
	Just x -> C.length l - 1 - x
fst' l = case C.elemIndex 'W' l of
	Nothing -> -1
	Just x -> C.length l - 1 - x

solve [] _ = 0
solve [ln] i = max (-1) (last' ln - i)
	where n = C.length ln
solve (ln1:ln2:lns) i = let j = max (last' ln1) (fst' ln2) in let next = max (-1) (solve (ln2:lns) (n - j - 1)) in if next < 0 then max (-1) (j-i) else max 0 (j-i) + next + 1
	where n = C.length ln1

halfrev lns = [if i `mod` 2 == 1 then C.reverse (lns !! i) else (lns !! i) | i <- [0..n-1]]
	where n = length lns

main = do
	input <- fmap C.lines $ C.hGetContents stdin
	let [n, m] = map (fst . fromJust . C.readInt) . C.words $ head input
	let view = take n $ tail input
	putStrLn . show . max 0 $ solve (halfrev view) 0

import qualified Data.ByteString.Lazy.Char8 as C
import IO
import Data.Maybe

last' l = case (C.elemIndex 'W' . C.reverse) l of
	Nothing -> -1
	Just x -> C.length l - 1 - x
fst' l = case C.elemIndex 'W' l of
	Nothing -> -1
	Just x -> C.length l - 1 - x

solve [] _ = -1
solve [ln] i = max (-1) (last' ln - i)
	where n = C.length ln
solve (ln1:ln2:lns) i = let j = max (last' ln1) (fst' ln2) in max 0 (j - i) + solve (ln2:lns) (n - j - 1) + 1
	where n = C.length ln1

halfrev lns = [if i `mod` 2 == 1 then C.reverse (lns !! i) else (lns !! i) | i <- [0..n-1]]
	where n = length lns

main = do
	input <- fmap C.lines $ C.hGetContents stdin
	let [n, m] = map (fst . fromJust . C.readInt) . C.words $ head input
	let view = take n $ tail input
	putStrLn . show . max 0 $ solve (halfrev view) 0

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
{-# 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
    m <- readInt
    grid <- replicateM n (BS.unpack <$> readString)
    return (n, m, grid)
  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 (n, m, grid) = go 0 True weeds - 1
  where
    weeds = [ sort indices
            | (i, row) <- zip [0..] grid
            , let indices = elemIndices 'W' row ++ [0 | i == 0]
            ]

    weeds' = reverse $ dropWhile null $ reverse weeds

    go _ _ [] = 0
    go p right ([] : rows) = go p (not right) rows + 1
    go p right (row : rows)
        | right     = (maximum row - l) + (p - l) + 1 + go (maximum row) (not right) rows
        | otherwise = (r - minimum row) + (r - p) + 1 + go (minimum row) (not right) rows
      where
        l = minimum row `min` p
        r = maximum row `max` p

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

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

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
{-# 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
    m <- readInt
    grid <- replicateM n (BS.unpack <$> readString)
    return (n, m, grid)
  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

inf = 10^9

solve (n, m, grid) = go (0 : replicate (m-1) inf) True weeds - 1
  where
    weeds = [ indices
            | (i, row) <- zip [0..] grid
            , let indices = elemIndices 'W' row ++ [0 | i == 0]
            ]

    weeds' = reverse $ dropWhile null $ reverse weeds

    go prev right [] = minimum prev
    go prev right (row:rows) = go end' (not right) rows
      where
        minv = if null row then inf else minimum row
        maxv = if null row then -inf else maximum row

        start = [if right && i > minv || not right && i < maxv then inf else ri + 1 | (i, ri) <- zip [0..] prev]
        end
            | right     = scanl1 (\v x -> (v + 1) `min` x) start
            | otherwise = scanr1 (\x v -> (v + 1) `min` x) start
        end' = [if right && i < maxv || not right && i > minv then inf else min inf ri | (i, ri) <- zip [0..] end]

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

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

{-# OPTIONS -O2 #-}
import Data.List

main = do
  s <- getContents
  let
    (grid:ls) = lines s
    [row, col] = map read $ words grid :: [Int]
    ws' = [(i+1, j+1) |i<-[0..row-1], j<-[0..col-1], (ls !! i) !! j == 'W']
    ws = [(r, (minimum [x|(y,x)<-ws', y==r], maximum [x|(y,x)<-ws', y==r])) | r <- [1..row], elem 'W' (ls !! (r-1))]
  print $ search 1 1 ws

search _ _ [] = 0
search row column [(r, (a, b))]= if mod row 2 == 0 then column - a else b - column
search row column orig@((r, (a, b)):(r', (a', b')):l)
  | row == r && row + 1 == r' = dist goalPos + 1 + search (row+1) goalPos ((r', (a', b')):l)
  | row == r = dist goalPos' + 1 + search (row+1) goalPos' ((r', (a', b')):l)
  | row + 1 == r = dist goalPos' + 1 + search (row+1) goalPos' orig
  | otherwise = 1 + search (row+1) column orig
  where
    dist x = abs $ x - column
    goalPos = if mod row 2 == 0 then min a a' else max b b'
    goalPos' = if mod row 2 == 0 then a else b
    goalPos'' = if mod row 2 == 0 then b else a

{-# OPTIONS -O2 #-}
import Data.List

main = do
  s <- getContents
  let
    (grid:ls) = lines s
    [row, col] = map read $ words grid :: [Int]
    ws' = [(i+1, j+1) |i<-[0..row-1], j<-[0..col-1], (ls !! i) !! j == 'W']
    ws = [(r, (minimum [x|(y,x)<-ws', y==r], maximum [x|(y,x)<-ws', y==r])) | r <- [1..row], elem 'W' (ls !! (r-1))]
  print $ search 1 1 ws

search _ _ [] = 0
search row column [(r, (a, b))]= if mod row 2 == 0 then column - a else b - column
search row column orig@((r, (a, b)):(r', (a', b')):l)
  | row == r && row + 1 == r' = dist goalPos + 1 + search (row+1) goalPos ((r', (a', b')):l)
  | row == r = dist goalPos' + 1 + search (row+1) goalPos' ((r', (a', b')):l)
  | row + 1 == r = dist goalPos' + 1 + search (row+1) goalPos' orig
  | otherwise = search (row+1) column orig
  where
    dist x = abs $ x - column
    goalPos = if mod row 2 == 0 then min a a' else max b b'
    goalPos' = if mod row 2 == 0 then a else b

{-# OPTIONS -O2 #-}
import Data.List

main = do
  s <- getContents
  let
    (grid:ls) = lines s
    [row, col] = map read $ words grid :: [Int]
    ws' = [(i+1, j+1) |i<-[0..row-1], j<-[0..col-1], (ls !! i) !! j == 'W']
    ws = [(r, (minimum [x|(y,x)<-ws', y==r], maximum [x|(y,x)<-ws', y==r])) | r <- [1..row], elem 'W' (ls !! (r-1))]
  print $ search 1 1 ws

search _ _ [] = 0
search row column [(r, (a, b))]= if mod row 2 == 0 then column - a else b - column
search row column orig@((r, (a, b)):(r', (a', b')):rows)
  | row == r && row + 1 == r' = dist goalPos + 1 + search (row+1) goalPos ((r', (a', b')):rows)
  | row == r || row + 1 == r = dist goalPos' + 1 + search (row+1) goalPos' ((r', (a', b')):rows)
  | otherwise = search (row+1) column orig
  where
    dist x = abs $ x - column
    goalPos = if mod row 2 == 0 then min a a' else max b b'
    goalPos' = if mod row 2 == 0 then a else b

import Data.List
import qualified Data.Map as Map
import Data.Map ((!))
import Control.Monad
import Control.Applicative
import Debug.Trace

traceS a b = trace (show a) b

type Z = Int

data Dir = L | R deriving Show

antiDir L = R
antiDir R = L

solve :: Z -> Z -> [String] -> Z
solve n m ls = solve' n m ls' 0 R
  where ls' = cutter ls

cutter ls = reverse $ cutter' (reverse ls)

cutter' [] = []
cutter' ls =
  case elemIndex 'W' l of
    Nothing -> cutter' lss
    Just _  -> ls
  where (l:lss) = ls

solve' _ _ [] _ _ = 0
solve' n m [l] c L = c - (elemFind c l)
solve' n m [l] c R = abs $ c - (elemFind (m-c-1) (reverse l))
solve' n m (l1:lrem@(l2:ls)) c dir =
  abs (t-c) + solve' n m lrem t (antiDir dir) + 1
  where t = getTarget c m l1 l2 dir

getTarget c m l1 l2 L = min t1 t2
  where t1 = elemFind c l1
        t2 = elemFind c l2
getTarget c m l1 l2 R = m - (1 + getTarget (m-c-1) m (reverse l1) (reverse l2) L)

elemFind c l1 =
  case elemIndex 'W' l1 of
    Nothing -> c
    Just t1 -> min t1 c

main = do
  (n,m) <- (\[a,b] -> (a,b)) . map read . words <$> getLine
  ls <- replicateM n getLine
  print $ solve n m ls

import Data.List
import qualified Data.Map as Map
import Data.Map ((!))
import Control.Monad
import Control.Applicative
import Debug.Trace

traceS a b = trace (show a) b

type Z = Int

data Dir = L | R deriving Show

antiDir L = R
antiDir R = L

solve :: Z -> Z -> [String] -> Z
solve n m ls = solve' n m ls' 0 R
  where ls' = cutter ls

cutter [] = []
cutter ls =
  case elemIndex 'W' l of
    Nothing -> cutter lss
    Just _  -> ls
  where (l:lss) = reverse ls

solve' _ _ [] _ _ = 0
solve' n m [l] c L = c - (elemFind c l)
solve' n m [l] c R = abs $ c - (elemFind (m-c-1) (reverse l))
solve' n m (l1:lrem@(l2:ls)) c dir =
  traceS (abs (t-c),dir) $ abs (t-c) + solve' n m lrem t (antiDir dir) + 1
  where t = getTarget c m l1 l2 dir

getTarget c m l1 l2 L = min t1 t2
  where t1 = elemFind c l1
        t2 = elemFind c l2
getTarget c m l1 l2 R = m - (1 + getTarget (m-c-1) m (reverse l1) (reverse l2) L)

elemFind c l1 =
  case elemIndex 'W' l1 of
    Nothing -> c
    Just t1 -> min t1 c

main = do
  (n,m) <- (\[a,b] -> (a,b)) . map read . words <$> getLine
  ls <- replicateM n getLine
  print $ solve n m ls

import Data.List
import qualified Data.Map as Map
import Data.Map ((!))
import Control.Monad
import Control.Applicative
import Debug.Trace

traceS a b = trace (show a) b

type Z = Int

data Dir = L | R deriving Show

antiDir L = R
antiDir R = L

solve :: Z -> Z -> [String] -> Z
solve n m ls = solve' n m ls 0 R

solve' n m [l] c L = c - (elemFind c l)
solve' n m [l] c R = abs $ c - (elemFind (m-c-1) (reverse l))
solve' n m (l1:lrem@(l2:ls)) c dir =
  traceS (abs (t-c),dir) $ abs (t-c) + solve' n m lrem t (antiDir dir) + 1
  where t = getTarget c m l1 l2 dir

getTarget c m l1 l2 L = min t1 t2
  where t1 = elemFind c l1
        t2 = elemFind c l2
getTarget c m l1 l2 R = m - (1 + getTarget (m-c-1) m (reverse l1) (reverse l2) L)

elemFind c l1 =
  case elemIndex 'W' l1 of
    Nothing -> c
    Just t1 -> min t1 c

main = do
  (n,m) <- (\[a,b] -> (a,b)) . map read . words <$> getLine
  ls <- replicateM n getLine
  print $ solve n m ls


import Data.List
import System.IO

main :: IO ()
main = do
    input <- getContents
    putStr $ solve $ tail $ map read $ words input

solve :: [Int] -> String
solve [] = ""
solve (n:m:rs) = let (cur,rest) = splitAt (n*m) rs
                     lt0 = filter (<0) cur
                     abs_list = map abs cur
                     all_sum = sum abs_list
                     ans = if even $ length lt0
                           then all_sum
                           else all_sum - 2*(minimum abs_list)
                 in (show ans) ++ "\n" ++ solve rest
solve _ = ""

import Control.Arrow ((>>>))

main :: IO ()
main =
  interact $
  lines >>>
  drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines

process :: [[Int]] -> [Int]
process [] = []
process ([n, _]:xss) =
  let (xs, xss') = splitAt n xss
   in solve xs : process xss'

solve :: [[Int]] -> Int
solve xs
  | elem 0 ys || even neg = sum ys'
  | otherwise = sum ys' - 2 * minimum ys'
  where
    ys = concat xs
    ys' = map abs ys
    neg = length . filter (< 0) $ ys

main :: IO ()
main = interact $ unlines . map show . solve . map read . tail . words

solve :: [Int] -> [Int]
solve [] = []
solve (n:m:rs) = ans:(solve rest)
    where (cur,rest) = splitAt (n*m) rs
          lt0_cnt = length $ filter (<0) cur
          abs_list = map abs cur
          abs_sum = sum abs_list
          ans = if even lt0_cnt
                then abs_sum
                else abs_sum - 2*(minimum abs_list)
solve _ = []

import Data.List
import System.IO

main :: IO ()
main = do
    input <- getContents
    putStr $ solve $ tail $ map read $ words input

solve :: [Int] -> String
solve [] = ""
solve (n:m:rs) = let sz = n*m
                     (cur,rest) = splitAt sz rs
                     lt0 = filter (<0) cur
                     abs_list = map abs cur
                     all_sum = sum abs_list
                     ans = if even $ length lt0
                           then all_sum
                           else all_sum - 2*(minimum abs_list)
                 in (show ans) ++ "\n" ++ solve rest
solve _ = ""

import Control.Monad
{-
n rows
m columns
cell i-th row j-th column from the left has value a(i,j)

can do following operation any number of times:
  choose any two adjacent cells and multiply the values in them by -1
  two cells are called adjacent if they share a side
-}

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

rowsToIntList :: Int -> IO [Int]
rowsToIntList 0 = return []
rowsToIntList n = do
  thisRow <- (map read . words) <$> getLine
  nextRow <- rowsToIntList (n - 1)
  return $ mappend thisRow nextRow

counter :: Int -> (Int, Int, Int) -> (Int, Int, Int)
counter a (sumAbs, negativeCount, smallestAbs) = (sumAbs + abs a, negativeCount + negativeIncrement, min smallestAbs (abs a))
  where
    negativeIncrement = if a < 0 then 1 else 0

main = do
  cases <- read <$> getLine
  replicateM_ cases $ do
    [n, m] <- (map read . words) <$> getLine :: IO [Int]
    rows <- rowsToIntList n
    let (sumAbs, negativeCount, smallestAbs) = foldr counter (0, 0, abs (head rows)) rows
    case even negativeCount of
      True -> putStrLn $ show $ sumAbs
      False -> putStrLn $ show $ sumAbs - 2 * smallestAbs

readCases :: [Int] -> [[Int]]
readCases [] = []
readCases (r:c:ws) = cs : readCases rs
  where (cs, rs) = splitAt (r*c) ws

findMaxSum :: [Int] -> Int
findMaxSum as
  | odd $ numNegetive as = sum as' - (2 * minimum as')
  | otherwise = sum as'
  where as' = map abs as
        numNegetive = length . filter (<0)

solve :: String -> String
solve = unlines . map show . map findMaxSum . readCases . map read . tail . words

main = interact solve

import Data.List
import System.IO

main :: IO ()
main = do
    input <- getContents
    putStr $ solve $ tail $ map read $ words input

solve :: [Int] -> String
solve [] = ""
solve (n:m:rs) = let sz = n*m
                     (cur,rest) = splitAt sz rs
                     eq0 = filter (==0) cur
                     lt0 = filter (<0) cur
                     tmp = (sum cur)-2*(sum lt0)
                     ans = if (length eq0 > 0) || (even $ length lt0)
                           then tmp
                           else tmp + 2*(maximum lt0)
                 in (show ans) ++ "\n" ++ solve rest
solve _ = ""


-- maxRight: O(n)
maxRight :: [Int] -> [Int]
maxRight []     = [0]
maxRight (x:xs) = max x (head ys) : ys
  where ys = maxRight xs

-- solve: O(n)
solve :: [Int] -> [Int]
solve xs = zipWith f xs (tail $ maxRight xs)
  where f a b = if a <= b then b + 1 - a else 0

main :: IO ()
main =
  getLine >>= \n ->
  getLine >>= putStrLn . unwords . map show . solve . map read . words

main = interact $ unwords . map show . solve . map read . tail . words
solve = map (max 0 . succ) . (zipWith (-) =<< tail . scanr max (-1))

import Control.Monad

maxRight :: [Int] -> [Int]
maxRight []     = [0]
maxRight (x:xs) = max x (head ys) : ys
  where ys = maxRight xs

solve :: [Int] -> [Int]
solve xs = zipWith f xs (tail $ maxRight xs)
  where f a b = if a <= b then b + 1 - a else 0

ansJoin :: Show a => [a] -> String
ansJoin = tail . foldr (++) "" . map ((++) " ". show)

main :: IO ()
main =
  getLine >>= \n ->
  getLine >>= putStrLn . ansJoin . solve . map read . words

import qualified Data.Map as Map

luxury :: (Integral a) => [a] -> [a]
luxury values =
    let counts = foldr (\v c -> Map.insertWith (+) v 1 c) Map.empty values
    in reverse $ fst $ foldl step ([], counts) values
        where step (res, counts) v =
                let nm = Map.update (\c -> if c > 1 then (Just (c-1)) else Nothing) v counts
                in if Map.null nm then (0:res, nm)
                else ((((max ((fst $ (Map.findMax nm))+1) v) - v):res), nm)

main = do
    inp <- getContents
    let values = map read $ words $ head $ tail $ lines inp :: [Int]
    putStrLn $ unwords $ map show $ luxury values

import Control.Applicative
import Data.List
import Data.Char

main= do
	getLine
	s<- map read. words <$> getLine ::IO [Int]
	let t = tail $ scanr max 0 s
	putStrLn $ intercalate " " $ map show $ zipWith (\a b ->    (max 0 (b+1-a))) s t

import Control.Applicative

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

inputInts = inputRow :: IO [Int]

go :: [Int] -> ([Int], Int)
go [] = ([], 0)
go (a:as) = ([max (b - a + 1) 0] ++ r1, max a b)
    where (r1, b) = go as

trans :: [Int] -> String
trans [a] = show a
trans (a:as) = show a ++ " " ++ trans as

main :: IO()
main = do
    [ln] <- inputInts
    lst <- inputInts
    putStrLn (trans(fst(go lst)))

readInt :: IO Int
readInt = do
    getLine >>= return . read

readCase :: IO [Int]
readCase = do
    readInt   -- Read and do nothing
    getLine >>= return . (map read . words)

constructArray :: [Int] -> ([Int], Int)
constructArray [] = ([], 0)
constructArray (x:xs) =  (y, z)
    where ans = constructArray xs
          z = max x (snd ans)
          y = (max 0 ((snd ans)-x+1)) : (fst ans)

main :: IO()
main = do
    readCase >>= putStrLn . unwords . (map show) .  fst . constructArray

main = do
        getLine
        interact $ unwords.map show.reverse.solve.reverse.map read.words
solve (x:xs) = 0:res x xs
  where res _ [] = []
        res m (x:xs)|m>=x      = m-x+1:res m xs
                    |otherwise = 0:res x xs

import Data.List (intercalate)
main=interact $ intercalate " ". (map show).solve . (map read) . tail. words
solve :: [Int]->[Int]
solve s = reverse ([0] ++ (zipWith (\a b->max (b-a+1) 0) (tail $ reverse s) (scanl1 max $ reverse s)))

main=interact $ solve . (map read) . tail. words
solve s = unwords $ map show $ reverse $ [0] ++ (zipWith (\a b->max (b-a+1) 0) (tail $ reverse s) (scanl1 max $ reverse s))

main = do
    n <- getLine
    numbersString <- getLine
    let numbers = map read (words numbersString) :: [Int]
    let maxes = scanr max 0 numbers
    let answers = [if m >= num then (m+1-num) else 0 | (num, m) <- zip numbers (tail maxes)]
    putStrLn (unwords $ map show answers)

main :: IO()
main = putStrLn . unwords . map show . solve . map read . tail . words =<< getContents

solve :: [Int] -> [Int]
solve a = let m = getMax a
          in solve' a (tail m)

solve' :: [Int] -> [Int] -> [Int]
solve' []    []     = []
solve' (a:s) (m:ms) | a > m     = 0 : solve' s ms
                    | otherwise = (m - a + 1) : solve' s ms

getMax :: [Int] -> [Int]
getMax []    = [0]
getMax (a:s) = let next = getMax s
               in (max a (head next)):next

main = do
  n <- readLn :: IO Int
  a <- fmap ((map read) . words) getLine :: IO [Int]
  let list = reverse $ 0:solve (last a) (reverse . init $a)
  mapM_ (\x -> putStrLn (show x ++ " ")) list

solve m [] = []
solve m (x:xs)
 |x>m = 0:solve x xs
 |otherwise = m-x+1:solve m xs

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

import Control.Applicative
import Control.Monad hiding ((<$!>))
import Control.Monad.ST.Safe
import Control.Monad.State hiding ((<$!>))
-- import Data.Array
import Data.Array.IArray
import Data.Array.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Builder as BB
import Data.Char
import qualified Data.Foldable as F
import Data.Function
import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
-- import Data.Tree
import Data.Tuple
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
-- import Debug.Trace
import System.IO

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

main = do
  getLine
  hs <- getInts

  putStrLn $ unwords $ map show $ zipWith (\m h -> if h > m then 0 else m-h+1) (tail $ scanr max 0 hs) hs

main = do
	getLine
	as <- (map read . words) `fmap` getLine

	let
		ms = tail (scanr1 max as) ++ [0]
		res = map (\(v, m) -> if v > m then 0 else m + 1 - v) $ zip as ms

	putStrLn $ unwords . map show $ res

import Data.List (intercalate)
mac (h:t) | null t = [(h-1)]
          | otherwise = (max th mx):next
             where next = mac t
                   th = head t
                   mx = max th (head next)
main = do
  w0 <- getLine
  w1 <- getLine
  let h = [read n::Int|n <-(words w1)]
  let c = map (+1) $ mac h
  let res = map (\x -> max 0 ((fst x) - (snd x))) $ zip c h
  putStrLn $ intercalate " " $ map show res

main = do
        getLine
        interact $ unwords.map show.reverse.solve.reverse.map read.words
solve (x:xs) = 0:res x xs
  where res _ [] = []
        res m (x:xs)|m>=x      = m-x+1:res(m+1) xs
                    |otherwise = 0:res m xs

import Data.List
main = do
    n <- readLn :: IO Int
    a <- fmap ((map read) . words ) getLine :: IO [Int]
    mapM_ (\x -> putStr ((show x)++" ")) $ (zipWith (\x y -> y-x+1) a (init (scanr max (last a) (init a)))) ++ [0]

import Data.List
main = do
    n <- readLn :: IO Int
    a <- fmap ((map read) . words ) getLine :: IO [Int]
    let ml = scanr max (last a) (init a)
        ans = solve a ml
    printList ans

solve [] [] = []
solve (x:xs) (y:ys)
 |x==y = 0 : solve xs ys
 |otherwise = y-x+1 : solve xs ys

printList = mapM_ (\x -> putStr ((show x)++" "))

main = do
  n <- readLn :: IO Int
  a <- fmap ((map read) . words) getLine :: IO [Int]
  let list = reverse $ 0:solve (last a) (reverse . init $a)
  mapM_ (\x -> putStrLn (show x ++ " ")) list

solve m [] = []
solve m (x:xs)
 |x>=m = 0:solve x xs
 |otherwise = m-x+1:solve m xs

main = do
  n <- readLn :: IO Int
  a <- fmap ((map read) . words) getLine :: IO [Int]
  let list = 0:solve (last a) (init a)
  mapM_ (\x -> putStrLn (show x ++ " ")) (init list)

solve m [] = []
solve m (x:xs)
 |x>=m = 0:solve x xs
 |otherwise = m-x+1:solve m xs

main = do
  n <- readLn :: IO Int
  a <- fmap ((map read) . words) getLine :: IO [Int]
  let list = reverse $ 0:solve (last a) (reverse . init $a)
  mapM_ (\x -> putStr ((show x) ++ " ")) list

solve m [] = []
solve m (x:xs)
 |x>=m = 0:solve x xs
 |otherwise = m-x+1:solve m xs

import Data.List
main = do
    n <- readLn :: IO Int
    a <- fmap ((map read) . words ) getLine :: IO [Int]
    mapM_ (\x -> putStr ((show x)++" ")) $ zipWith (\x y -> if x==y then 0 else y-x+1) a (scanr max (last a) (init a))

import Data.List (intercalate)
mac (h:t) | null t = [(h-1)]
          | otherwise = (max th mx):next
             where next = mac t
                   th = head t
                   mx = max th (head next)
main = do
  w0 <- getLine
  w1 <- getLine
  let h = [read n::Int|n <-(words w1)]
  let c = map (+1) $ mac h
  let res = map (\x -> (fst x) - (snd x)) $ zip c h
  putStrLn $ intercalate " " $ map show res

import Control.Applicative
import Data.List
import Data.Char

main= do
	getLine
	s<- map read. words <$> getLine ::IO [Int]
	let t = tail $ scanr max 0 s
	putStrLn $ intercalate " " $ map show $ zipWith (\a b -> if b==a then 0 else  (max 0 (b+1-a))) s t

import Control.Applicative
import Data.List
import Data.Char

main= do
	getLine
	s<- map read. words <$> getLine ::IO [Int]
	let t = scanr max 0 s
	putStrLn $ intercalate " " $ map show $ zipWith (\a b -> if b==a then 0 else  b+1-a) s t


getMult :: Int -> Int -> Int -> [Int]
getMult y k n
	| div n k == div y k	= []
	| otherwise				= (n - (mod n k) - y) : (getMult y k (n - k))

printList :: [Int] -> IO()
printList [] = do
	putStrLn ""
printList (a:b) = do
	putStr ((show a) ++ " ")
	printList b

main :: IO()
main = do
	str <- getLine
	let y = read ((words str) !! 0)
	let k = read ((words str) !! 1)
	let n = read ((words str) !! 2)
	if (div n k <= div y k)
		then putStrLn "-1"
		else printList (reverse (getMult y k n))

import Data.Array
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Char
import Data.List
import Control.Monad
import Control.Monad.ST.Safe
-- import Debug.Trace

getInts = fmap (map read . words) getLine :: IO [Int]

main = do
  [y, k, n] <- getInts

  let a = filter (>= 1) $ map (\s -> s-y) $ takeWhile (<= n) $ map (*k) [1..]

  if null a
     then print $ -1
     else putStrLn $ unwords $ map show a

main :: IO ()
main = do [y,k,n] <- (getLine >>= (return . map read . words))
          let l = [ z - y | z <- [k,2*k..n], z > y]
          let ans = if l == [] then [-1] else l
          putStrLn . unwords . map show $ ans

main = do
    x <- getLine
    putStrLn $ unwords $ map show $ f1 $ (\[a,b,c] -> map (\t -> t-a) $ f a b c) $ map (\a -> read a::Int) $ words x

f1 :: [Int] -> [Int]
f1 [] = [-1]
f1 x = x

f :: Int -> Int -> Int -> [Int]
f y k n
    | mod (y+1) k == 0 = [y+1,y+1+k..n]
    | otherwise = f (k*((div y k)+1)-1) k n

main :: IO ()
main = interact $ (\x -> if null x then "-1" else unwords $ map show x) . testcase . map read . words

testcase :: [Integer] -> [Integer]
testcase [y,k,n] = [ x | pos <- takeWhile (<=n) (iterate (+k) k), let x = pos - y, x >= 1]

import Control.Monad (liftM)

solve :: [Int] -> [Int]
solve [y, k, n]  =  map (\z -> z - y) [x, x + k .. n]
  where
    x  =  (y `div` k + 1) * k

prints :: Show a => [a] -> IO ()
prints []      =  print (-1)
prints [x]     =  print x
prints (x:xs)  =  putStr (show x ++ " ") >> prints xs

main :: IO ()
main  =  liftM (map read . words) getLine >>= prints . solve

main :: IO ()
main = getContents >>= putStrLn . unwords . map show . solve . map read . words

solve :: [Int] -> [Int]
solve [ y, k, n ] = head $ filter (not . null) $ [(y `div` k + 1) * k - y, (y `div` k + 2) * k - y .. n - y] : [[-1]]
solve _ = undefined

main :: IO ()
main = getContents >>= putStrLn . unwords . map show . solve . map read . words

solve :: [Int] -> [Int]
solve [ y, k, n ] = head $ filter (not . null) $ [k - y `mod` k, 2 * k - y `mod` k .. n - y] : [[-1]]
solve _ = undefined

main=interact$unwords.map show.f.map read.words
f[y,k,n]= case dropWhile(<=0)[(-y)`mod`k,(-y)`mod`k+k..n-y] of
            [] -> [-1]
            xs -> xs

import Control.Applicative
import Data.Ratio
import Data.List
main = do
    [y,k,n] <- map read . words <$> getLine
    let l1 = [ m*k + c1 | m <- [0..(n-y-c1)`div`k]]
        c1 = k - y`mod`k
    case (l1 == []) of
        False -> putStrLn.unwords.map show $ l1
        True -> print (-1)

{-# OPTIONS_GHC -rtsopts -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}

import qualified Data.List as L
import qualified Data.Function as F
import qualified Data.Set as S
import qualified Data.Map as M

parse = map read . words

solve :: [Int] -> [Int]
solve [y, k, n] =
  map (\x -> x - y) $ dropWhile (<= y) $ takeWhile (<= n) [x | x <- [k, 2*k ..]]

present :: [Int] -> String
present [] = "-1"
present foo = unwords $ map show foo

main = interact $ present . solve . parse

main = interact $ unwords . map show . solve . map read . words
solve [y,k,n]
  | k - mod y k > n - y = [-1]
  | otherwise = [k - mod y k, 2 * k - mod y k .. n - y]

main :: IO ()
main = getContents >>= putStrLn . unwords . map show . solve . map read . words

solve :: [Int] -> [Int]
solve [ y, k, n ] = head $ filter (not . null) $ [((y + k - 1) `div` k) * k - y, ((y + 2 * k - 1) `div` k) * k - y .. n - y] : [[-1]]
solve _ = undefined

import Control.Applicative
import Data.Ratio
import Data.List
main = do
    [y,k,n] <- map read . words <$> getLine
    let l2 = sort [x | x <- [0..n-y], (x+y)`mod`k==0]
    case (l2 == []) of
        False -> putStrLn.unwords.map show $ l2
        True -> print (-1)

{-# OPTIONS_GHC -rtsopts -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}

import qualified Data.List as L
import qualified Data.Function as F
import qualified Data.Set as S
import qualified Data.Map as M

parse = map read . words

solve :: [Int] -> [Int]
solve [y, k, n] =
  map (\x -> x - y) $ dropWhile (<y) $ takeWhile (<= n) [x | x <- [k, 2*k ..]]

present :: [Int] -> String
present [] = "-1"
present foo = unwords $ map show foo

main = interact $ present . solve . parse

{-# OPTIONS_GHC -rtsopts -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}

import qualified Data.List as L
import qualified Data.Function as F
import qualified Data.Set as S
import qualified Data.Map as M

parse = map read . words

solve :: [Int] -> [Int]
solve [y, k, n] =
  map (\x -> x - y) $ dropWhile (<y) $ takeWhile (<n) [x | x <- [k, 2*k ..]]

present :: [Int] -> String
present [] = "-1"
present foo = unwords $ map show foo

main = interact $ present . solve . parse


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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}

{-# options_ghc -Wno-safe                        #-}     -- no warning if inferred as safe
{-# options_ghc -Wno-all-missed-specialisations  #-}     -- "Could not specialise..." when -O1
{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  cat -- input.txt | ./a.out  &&  cat -- repaint.hs | xclip -selection clipboard  &&  echo COPIED  ||  echo ERROR)

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

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

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        sort . concat <$> replicateM 2 getLine
    mapM_ (putStrLn.show.solve) tcs

solve = length . init . sortOn length . group

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

import Data.Maybe
import Control.Monad

import Data.List (group, sort)

solve as =
    let as' = group $ sort as
    in length as' - 1

read = do
    s1 <- C.getLine
    s2 <- C.getLine

    print $ solve [s1 `B.index` 0, s1 `B.index` 1, s2 `B.index` 0, s2 `B.index` 1]

main :: IO()
main = do
    t <- C.getLine

    replicateM_ (fst $ fromJust $ C.readInt t) Main.read

import Data.Set

computeProg n = (1 + n) * n `div` 2

decide n = decideBody n
decideBody 0 = return ()
decideBody n = do
    s1 <- getLine
    s2 <- getLine
    case (size $ fromList (s1 ++ s2)) of
        1 -> putStrLn (show 0)
        2 -> putStrLn (show 1)
        3 -> putStrLn (show 2)
        4 -> putStrLn (show 3)
    decideBody $ n - 1

main :: IO ()
main = do
    t <- getLine >>= (return . (read :: String -> Int))
    decide t


import Control.Monad (replicateM_)

solve :: Int -> [Char] -> Int
solve _ [] = 0
solve c (x : xs) =
    if x == '1'
        then solve (c + 1) xs
        else max (2 - c) 0 + solve 0 xs

main :: IO ()
main = do
    t <- readLn :: IO Int
    replicateM_ t $ do
        getLine
        l <- getLine
        print $ solve 2 l

-- https://codeforces.com/contest/1679/problem/D
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE LambdaCase #-}

import Control.Arrow ((>>>))
import Control.Monad (
    MonadPlus (mplus),
    foldM_,
    forM_,
    guard,
    join,
    replicateM,
    replicateM_,
 )
import qualified Control.Monad.ST.Strict as ST
import qualified Control.Monad.State.Strict as S

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 Data.Bits
import qualified Data.ByteString.Char8 as B8
import Data.Char
import Data.Int

import Data.Function (on)
import Data.Functor ((<&>))
import Data.Maybe (fromJust, fromMaybe, isJust)

import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import Data.List (
    elemIndices,
    find,
    findIndices,
    intersect,
    isPrefixOf,
    nub,
    sort,
    sortOn,
 )
import qualified Data.Map as M
import qualified Data.Set as S

import Control.Monad.Cont (MonadIO (liftIO))
import Data.IORef (modifyIORef, newIORef, readIORef)
import GHC.IO.Handle (hDuplicateTo)
import System.IO (
    IOMode (ReadMode, WriteMode),
    openFile,
    stdin,
    stdout,
 )
import System.Posix.Internals (puts)
import Text.Printf (printf)

-- import Debug.Trace (trace, traceM, traceShowM)
-- debug = flip trace

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

modifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray arr ix f = do
    value <- MA.readArray arr ix
    MA.writeArray arr ix $ f value

putsYesNo :: Bool -> IO ()
putsYesNo value = do
    let result :: String =
            if value
                then "Yes"
                else "No"
    printf "%s\n" result

{- END OF GENERAL -}

solve :: B8.ByteString -> Int
solve str = flip S.evalState ((0, 2)::(Int, Int)) $ do
    forM_ (B8.unpack str) $ \case
        '0' -> S.modify $ \(answer, cnt1) -> (answer + max (2 - cnt1) 0, 0)
        '1' -> S.modify $ \(answer, cnt1) -> (answer, cnt1 + 1)
    (answer, _) <- S.get
    return answer

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        n <- B8.getLine <&> readIntB8
        str <- B8.getLine <&> head . B8.words
        let answer = solve str
        printf "%d\n" answer


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

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n, u, v] <- readInts
    a : as <- readInts
    let
      canEscapeAlready = or [abs (p - q) > 1 | (p, q) <- zip as $ a : as]
      allSame = all (== a) as
    putInts $ pure $ if  canEscapeAlready
      then  0
      else  min u v + if  allSame
      then  v
      else  0

type SIO = StateT P.ByteString IO

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

import Control.Monad
import Data.List

main = do
    t <- getLine
    replicateM_ (read t) testcase

testcase :: IO ()
testcase = do
    [n,u,v] <- fmap (map read . words) getLine
    a <- fmap (map read . words) getLine
    putStrLn $ solve n u v a

solve :: Int -> Int -> Int -> [Int] -> String
solve n u v a
    | distance == 0 = show $ min (u+v) (2*v)
    | distance == 1 = show $ min u v
    | otherwise = "0"
    where
        distance = snd $ foldl' (\(last,dist) curr -> (curr,max dist . abs $ last-curr)) (head a,0) a :: Int

{-# LANGUAGE TypeApplications #-}
module Main where

import           Control.Monad                  ( replicateM_ )
import           Data.Array.Unboxed             ( (!)
                                                , UArray
                                                , listArray
                                                )

main :: IO ()
main = do
  t <- readLn
  replicateM_ t eachCase
 where
  eachCase = do
    [n, u, v] <- fmap read . words <$> getLine
    obs       <- fmap (read @Int) . words <$> getLine
    let obsArr = listArray @UArray (1, length obs) obs
    if all (== head obs) (tail obs)
      then print (v + min u v)
      else if any (\i -> abs (obsArr ! i - obsArr ! (i - 1)) > 1) [2 .. length obs] then print 0 else print (min u v)

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

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n, u, v] <- readInts
    a : as <- readInts
    putInts $ pure $ min u v + if  all (== a) as
      then  v
      else  0

type SIO = StateT P.ByteString IO

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


import Control.Arrow

main = interact $
	lines >>> drop 1
	>>> map (words >>> map read >>> sum >>> show)
	>>> unlines

import Control.Applicative ((<$>))
import Control.Monad (replicateM)

getLines :: Int -> IO [String]
getLines n = replicateM n getLine

getInts :: Int -> IO [Int]
getInts n = fmap read <$> getLines n

getInt :: IO Int
getInt = fmap read getLine

workProblem :: [String] -> IO ()
workProblem [] = pure ()
workProblem (x:xs) = do
                    let [num1, num2] = words x
                    let a = read num1 :: Int
                    let b = read num2 :: Int
                    putStrLn $ show (a + b)
                    workProblem xs

main :: IO ()
main = do
         n <- getInt
         lines <- getLines n
         workProblem lines

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

process = do
		s<-map read <$> words <$> getLine ::IO [Int]
		print $ sum s

main = do
		n<-read <$> getLine ::IO Int
		replicateM_ n process


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 Control.Monad.Trans.Class (lift)
import Data.Char (isSpace)
import Data.Maybe

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

readInt :: P.ByteString -> Int
readInt = fst . fromJust . P.readInt

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'

readIntIO :: IO Int
readIntIO = do
  t <- getLine
  if all isSpace t then readIntIO else pure . readInt . P.pack $ t

type DoState = StateT (S.Set Int) IO

go :: IO ()
go = do
  n <- readIntIO
  cs <- flip evalStateT S.empty $ fmap (foldr (<>) []) $ mapM findCycles [1..n]
  let
    p :: UArray Int Int
    p = array (1, n) cs
  P.putStr $ toLazyByteString $ char7 '!' <> char7 ' ' <> (putInts $ elems p) <> char7 '\n' <> flush
  where
    findCycles :: Int -> DoState [(Int, Int)]
    findCycles i = do
      b <- S.member i <$> get
      if b then pure []
      else do
        y <- g
        pure $ zip y (tail y)
      where
        g :: DoState [Int]
        g = do
          lift $ P.putStr $ toLazyByteString $ char7 '?' <> char7 ' ' <> putInts [i] <> char7 '\n' <> flush
          nextI <- lift readIntIO
          nextB <- S.member nextI <$> get
          modify $ S.insert nextI
          if nextB then pure [nextI]
          else (nextI:)<$>g

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  t <- readInt .  P.pack <$> getLine
  replicateM_ t go

{-# LANGUAGE ScopedTypeVariables #-}
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
import Data.Array.ST.Safe
import Control.Monad.ST.Lazy
import qualified Control.Monad.ST as Strict
import Control.Monad.Trans.Class

solve :: forall s. S (ST s) Builder
solve = do
  ~[n] <- getInts 1
  let  lst :: Strict.ST s v -> S (ST s) v
       lst = lift . strictToLazyST
  arr :: STUArray s Int Int <- lst $ newArray (1, n) 0
  let
    query :: Int -> Builder
    query k = string7 "? " <> putInts [k] <> flush
    loopQuery :: Int -> Int -> S (ST s) Builder
    loopQuery k prev = (query k <>) <$> do
      ~[resp] <- getInts 1
      lst $ writeArray arr prev resp
      vis <- lst $ readArray arr resp
      if  vis /= 0
        then  pure mempty
        else  loopQuery k resp
    go :: Int -> S (ST s) Builder
    go k = do
      vis <- lst $ readArray arr k
      if  vis == 0
        then  (query k <>) <$> do
          ~[resp] <- getInts 1
          loopQuery k resp
        else  pure mempty
  queries <- forM [1 .. n] go
  ansArr :: UArray Int Int <- lst $ freeze arr
  let  ans = char7 '!' <> char7 ' ' <> putInts (elems ansArr)
  pure $ mconcat queries <> ans <> flush

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    state $ \st -> runST $ runStateT solve st

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

getNext :: Monad m => Int -> S m [P.ByteString]
getNext = state . splitAt

getInts :: Monad m => Int -> S m [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

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 $ P.words 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 Control.Monad.Trans.Class (lift)
import Data.Char (isSpace)
import Data.Maybe

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

readInt :: P.ByteString -> Int
readInt = fst . fromJust . P.readInt

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'

readIntIO :: IO Int
readIntIO = do
  t <- getLine
  if all isSpace t then readIntIO else pure . readInt . P.pack $ t

type DoState = StateT (S.Set Int) IO

go :: IO ()
go = do
  n <- readIntIO
  cs <- flip evalStateT S.empty $ fmap (foldr (<>) []) $ mapM findCycles [1..n]
  let
    p :: UArray Int Int
    p = array (1, n) cs
  P.putStr $ toLazyByteString $ char7 '!' <> char7 ' ' <> (putInts $ elems p) <> char7 '\n' <> flush
  where
    findCycles :: Int -> DoState [(Int, Int)]
    findCycles i = do
      b <- S.member i <$> get
      if b then pure []
      else do
        y@(x:xs) <- g
        pure $ zip y (xs ++ [x])
      where
        g :: DoState [Int]
        g = do
          b <- S.member i<$>get
          if b then pure []
          else do
            lift $ P.putStr $ toLazyByteString $ char7 '?' <> char7 ' ' <> putInts [i] <> char7 '\n' <> flush
            nextI <- lift readIntIO
            modify $ S.insert nextI
            (nextI:)<$>g

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  t <- readInt .  P.pack <$> getLine
  replicateM_ t go

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 Control.Monad.Trans.Class (lift)
import Data.Char (isSpace)
import Data.Maybe

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

readInt :: P.ByteString -> Int
readInt = fst . fromJust . P.readInt

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'

readIntIO :: IO Int
readIntIO = do
  t <- getLine
  if all isSpace t then readIntIO else pure . readInt . P.pack $ t

type DoState = StateT (S.Set Int) IO

go :: IO ()
go = do
  n <- readIntIO
  cs <- flip evalStateT S.empty $ fmap (foldr (<>) []) $ mapM findCycles [1..n]
  let
    p :: UArray Int Int
    p = array (1, n) cs
  P.putStr $ toLazyByteString $ char7 '!' <> (putInts $ elems p) <> char7 '\n' <> flush
  where
    findCycles :: Int -> DoState [(Int, Int)]
    findCycles i = do
      b <- S.member i <$> get
      if b then pure []
      else do
        y@(x:xs) <- g
        pure $ zip y (xs ++ [x])
      where
        g :: DoState [Int]
        g = do
          b <- S.member i<$>get
          if b then pure []
          else do
            lift $ P.putStr $ toLazyByteString $ char7 '?' <> putInts [i] <> char7 '\n' <> flush
            nextI <- lift readIntIO
            modify $ S.insert nextI
            (nextI:)<$>g

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  t <- readInt .  P.pack <$> getLine
  replicateM_ t go


import Control.Monad (liftM)
import Data.List (sortBy)

parseLine :: String -> (Int, Int)
parseLine line  =  (a, b)
  where
    [a, b]  =  map read (words line)

myCompare :: (Int, Int) -> (Int, Int) -> Ordering
myCompare (n1, x1) (n2, x2)
  | x1 > x2  =  LT
  | x1 < x2  =  GT
  | n1 < n2  =  LT
  | n1 > n2  =  GT
  | otherwise  =  EQ

solve :: Int -> Int -> Int -> [(Int, Int)] -> [(Int, Int)]
solve t1 t2 k  =  (sortBy myCompare . solve' . zip [1..])
  where
    solve'  =  map calcMaxHeight
    calcMaxHeight (n, (a, b))  =  (n, max (calcMaxHeight' a b) (calcMaxHeight' b a))
    calcMaxHeight' a b  =  a * t1 * (100 - k) + 100 * b * t2

printAns :: [(Int, Int)] -> IO ()
printAns  =  mapM_ printAns'
  where
    printAns' (n, x)  =  putStrLn $ concat [show n, " ", show a, ".", b']
      where
        (a, b)  =  divMod x 100
        b'  =  if b < 10 then '0' : show b else show b

main :: IO ()
main  =  do
    lines'  <-  liftM lines getContents
    let [n, t1, t2, k]  =  (map read . words . head) lines'
    let ps  =  (map parseLine . take n . tail) lines'
    printAns (solve t1 t2 k ps)

import Data.List   (sortBy)
import Text.Printf (printf)

sortGT (a1, b1) (a2, b2)
  | b1 <  b2 = GT
  | b1 >  b2 = LT
  | b1 == b2 = EQ

answer :: Double -> Double -> Double -> [(Double, Double)] -> [(Int, Double)]
answer t1 t2 k gnomes = sortBy sortGT $ zipWith maxHeight [1..] gnomes
	where
		maxHeight n (a, b) = (n, max (height a b) (height b a))
		height a b = t1 * a * k + t2 * b

showGnome :: (Int, Double) -> String
showGnome (i, h) = printf "%i %.2f" i h

toTuple :: [a] -> (a, a)
toTuple (x:y:[]) = (x,y)
toTuple _        = error "wrong input"

main = do
	tmp <- getLine
	let (n:t1:t2:k:[]) = map read . words $ tmp
	gnomeTmp <- getContents
	let gnomes = map (toTuple . map read . words) . lines $ gnomeTmp
	putStrLn . unlines . map showGnome $ answer t1 t2 (1 - k/100) gnomes

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

main = do
  [n,t1,t2,k] <- map read.words <$> getLine
  uvs <- replicateM n $ map read.words <$> getLine
  mapM_ (\ (i,f) -> printf "%d %.2f\n" i f) $ solve [n,t1,t2,k] uvs

solve :: [Int] -> [[Int]] -> [(Int,Double)]
solve [n,t1,t2,k] uvs = sortBy (flip $ comparing snd).zip [1..].map calc $ uvs
   where calc [v,u] = max (f[v,u]) (f[u,v])
         f [v,u] = (fromIntegral $ (100-k)*v*t1+100*u*t2)/100

import Control.Monad
import Data.List

main =
    do
        vals <- getLine
        let (n:t1:t2:k:_) = map (read :: String -> Int) $ words vals
        input <- getContents
        mapM (putStrLn.printSol) (sortBy myCmp (solve t1 t2 (100-k) 1 n $ lines input))

myCmp :: Ord a => (a,a) -> (a,a) -> Ordering
myCmp (x1,y1) (x2,y2) =
    if x1 == x2
    then
        compare y1 y2
    else
        compare x2 x1

solve :: Int -> Int -> Int -> Int -> Int -> [String] -> [(Int, Int)]
solve _ _ _ _ _ [] = []
solve t1 t2 k i n (x:xs)
    | i > n = []
    | otherwise =
        let
            (speed1:speed2:_) = map (read :: String -> Int) $ words x
            m = max (t1 * speed1 * k + t2 * speed2 * 100) (t1 * speed2 * k + t2 * speed1 * 100)
        in
            (m, i) : (solve t1 t2 k (i+1) n xs)

printSol :: (Int, Int) -> String
printSol (a,b) = (show b ++ " " ++ addDot a)

addDot :: Int -> String
addDot = snd . foldr (\x (p,ys) -> (p+1, if p == 2 then '.':x:ys else x:ys)) (1,[]) . show

import Data.List
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Char

process :: [(Integer, Integer)] -> Integer -> Integer -> Integer -> [Integer]
process [] t1 t2 k = []
process ((a, b): as) t1 t2 k = ( max (a*t1 + b*t2 - (a*t1*k `div` 100)) (a*t2 + b*t1 - (b*t1*k `div` 100)) ) : process (as) t1 t2 k

main :: IO ()
main = do
	line1 <- getLine
	let
		[n, tt1, tt2, k] = map (\x -> read x :: Integer).words $ line1
		t1 = tt1*100
		t2 = tt2*100
	content <- getContents
	let
	 	arr =  map (\x -> let [a, b] = words$ x in (read a :: Integer, read b :: Integer)). lines $ content
		arr1 = reverse. sortBy (\(a, b) (c, d) -> if b /= d then compare b  d else compare c a). zip [1..] $ process arr t1 t2 k
	mapM_ (\(x, y) -> putStrLn$ (show x) ++ " " ++ (show$ y `div` 100) ++ "." ++ appendZero (show $ y `mod` 100)) arr1
	where
		appendZero x
		 | length x == 2 = x
		 | otherwise = appendZero ('0': x)

import Data.List
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Char

process :: [(Int, Int)] -> Int -> Int -> Int -> [Int]
process [] t1 t2 k = []
process ((a, b): as) t1 t2 k = ( max (a*t1 + b*t2 - (a*t1*k `div` 100)) (a*t2 + b*t1 - (b*t1*k `div` 100)) ) : process (as) t1 t2 k

main :: IO ()
main = do
	line1 <- getLine
	let
		[n, tt1, tt2, k] = map (\x -> read x :: Int).words $ line1
		t1 = tt1*100
		t2 = tt2*100
	content <- getContents
	let
	 	arr =  map (\x -> let [a, b] = words$ x in (read a :: Int, read b :: Int)). lines $ content
		arr1 = reverse. sortBy (\(a, b) (c, d) -> if b /= d then compare b  d else compare c a). zip [1..] $ process arr t1 t2 k
	mapM_ (\(x, y) -> putStrLn$ (show x) ++ " " ++ (show$ y `div` 100) ++ "." ++ appendZero (show $ y `mod` 100)) arr1
	where
		appendZero x
		 | length x == 2 = x
		 | otherwise = appendZero (x++"0")

import Data.List
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Char

process :: [(Int, Int)] -> Int -> Int -> Int -> [Int]
process [] t1 t2 k = []
process ((a, b): as) t1 t2 k = ( max (a*t1 + b*t2 - (a*t1*k `div` 100)) (a*t2 + b*t1 - (b*t1*k `div` 100)) ) : process (as) t1 t2 k

main :: IO ()
main = do
	line1 <- getLine
	let
		[n, tt1, tt2, k] = map (\x -> read x :: Int).words $ line1
		t1 = tt1*100
		t2 = tt2*100
	content <- getContents
	let
	 	arr =  map (\x -> let [a, b] = words$ x in (read a :: Int, read b :: Int)). lines $ content
		arr1 = reverse. sortBy (\(a, b) (c, d) -> if b /= d then compare b  d else compare c a). zip [1..] $ process arr t1 t2 k
--	print arr
--	mapM_ (print) arr1
	mapM_ (\(x, y) -> putStrLn$ (show x) ++ " " ++ (show$ y `div` 100) ++ "." ++ (show $ y `mod` 100)) arr1

import Data.List
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Char

process :: [(Int, Int)] -> Int -> Int -> Int -> [Int]
process [] t1 t2 k = []
process ((a, b): as) t1 t2 k = ( max (a*t1 + b*t2 - (a*t1*k `div` 100)) (a*t2 + b*t1 - (b*t1*k `div` 100)) ) : process (as) t1 t2 k

main :: IO ()
main = do
	line1 <- getLine
	let
		[n, tt1, tt2, k] = map (\x -> read x :: Int).words $ line1
		t1 = tt1*100
		t2 = tt2*100
	content <- getContents
	let
	 	arr =  map (\x -> let [a, b] = words$ x in (read a :: Int, read b :: Int)). lines $ content
		arr1 = reverse. sortBy (\(a, b) (c, d) -> if b /= d then compare b  d else compare c a). zip [1..] $ process arr t1 t2 k
	mapM_ (\(x, y) -> putStrLn$ (show x) ++ " " ++ (show$ y `div` 100) ++ "." ++ appendZero (show $ y `mod` 100)) arr1
	where
		appendZero x
		 | length x == 2 = x
		 | otherwise = appendZero ('0': x)

import Data.List   (sortBy)
import Text.Printf (printf)

sortGT (a1, b1) (a2, b2)
  | b1 <  b2 = GT
  | b1 >  b2 = LT
  | b1 == b2 = EQ

answer :: Double -> Double -> Double -> [(Double, Double)] -> [(Int, Double)]
answer t1 t2 k gnomes = sortBy sortGT $ zipWith maxHeight [1..] gnomes
	where
		maxHeight n (a, b) = (n, max (height a b) (height b a))
		height a b = t1 * a * k + t2 * b

showGnome :: (Int, Double) -> String
showGnome (i, h) = printf "%i %.2f" i h

toTuple :: [a] -> (a, a)
toTuple (x:y:[]) = (x,y)
toTuple _        = error "wrong input"

main = do
	tmp <- getLine
	let (n:t1:t2:k:[]) = map read . words $ tmp
	gnomeTmp <- getContents
	let gnomes = map (toTuple . map read . words) . lines $ gnomeTmp
	putStrLn . unlines . map showGnome $ answer t1 t2 (k/100) gnomes


import Data.List

main :: IO ()
main =
    interact
    $ show
    . maximum
    . map length
    . group
    . sort
    . map (read :: String -> Int)
    . tail
    . words

module Main where
import qualified Data.ByteString.Char8 as B
import Data.List
import Control.Applicative

main = B.interact exec
exec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . tail . B.words
solve = maximum . map length . group . sort

import Data.List

groupOn :: Int -> [a] -> [[a]]
groupOn _ [] = []
groupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds
-------------------------------------------------------------------------------

main = interact $ unlines . parse . lines

parse [_,ops'] = sol ops
  where
    ops = fn $ words ops'
    fn :: [String] -> [Int]
    fn xs = map read xs

sol bs = [ show res ]
  where
    res = length $ maximumBy cmp $ group $ sort bs
    cmp a b = compare (length a) (length b)