--fast read
import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Control.Applicative
modulo=1000000007
readInts a = fmap (map (fst . fromJust)) $ fmap (map B.readInteger) $ fmap B.words a
readLists = readInts $ B.getLine
readLLists = fmap (map (fst . fromJust)) $ fmap (map B.readInteger) $ fmap B.lines $ B.getContents
readMatrix = fmap readInts $ fmap B.lines $ B.getContents
getModLessNum::Integer->Integer->Integer -> Integer
getModLessNum n a m
  | n-1-m < 0 = 0
  | otherwise = 1 + div (n-m-1) a -- fromIntegral $ length $ filter (\x -> mod x a == m) [0..(n-1)]
getModNum::Integer->Integer->Integer
getModNum k a = getModLessNum (10^k) a 0
getModNumNot::Integer->Integer->Integer->Integer
getModNumNot k a b = getModLessNum (10^(k-1)) a (mod (a - (mod (b*(10^(k-1))) a)) a)
getAns::Integer -> Integer -> Integer -> Integer
getAns k a b = (getModNum k a) - (getModNumNot k a b)
main = do
  [n,k] <- readLists
  a <- readLists
  b <- readLists
  let ans = foldr1 (\x y -> mod (x*y) modulo) [getAns k a0 b0|(a0,b0) <- zip a b]
  print $ ans

main = interact $ show . solve . parse
  where parse = filter (not . null) . map (map read . words) . lines

mod' = (`mod` (10^9+7))

solve :: [[Integer]] -> Integer
solve [[_, k], as, bs] = product' xs
  where
    product' = foldr (\x y -> mod' (x*y)) 1
    xs = zipWith solveBlock as bs
    solveBlock x y = mod' $ below 10 - below (y+1) + below y
      where
        below n
          | n <= 0 = 0
          | otherwise = 1 + (n * 10^(k-1) - 1) `div` x

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

modn :: Int64
modn = 1000000007

nums k a b = (10^k-1) `div` a - (firstDigit b) + (if b == 0 then 0 else 1)
  where firstDigit l
            | l == 0    = (10^(k-1) - 1) `div` a
            | otherwise = ((l+1) * 10^(k-1) - 1) `div` a - (l*10^(k-1) - 1) `div` a

main :: IO ()
main = do
    [n, k] <- map (read::String->Int64) . words <$> getLine
    as <- map (read::String->Int64) . words <$> getLine
    bs <- map (read::String->Int64) . words <$> getLine
    let blocks = zipWith (nums k) as bs
    print $ foldl' (\a -> \b -> a*b `mod` modn) 1 blocks

import Control.Applicative

solve :: Integer -> (Integer,Integer) -> Integer
solve k (a,b) = num - rm
    where
        num = (10^k - 1) `div` a + 1
        rm = (+ 1) . (`div` a) . max (-1) $ ((b+1) * 10^(k-1) - 1) - ((b * 10^(k-1) - 1) `div` a + 1) * a

main :: IO ()
main = do
    [n,k] <- map read . words <$> getLine
    a <- map read . words <$> getLine
    b <- map read . words <$> getLine
    print . foldr1 (((`mod` 1000000007) .) . (*)) . map ((`mod` 1000000007) . solve k) $ zip a b

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

modn :: Int
modn = 1000000007

nums k a b = (10^k-1) `div` a - (firstDigit b) + (if b == 0 then 0 else 1)
  where firstDigit l
            | l == 0    = (10^(k-1) - 1) `div` a
            | otherwise = ((l+1) * 10^(k-1) - 1) `div` a - (l*10^(k-1) - 1) `div` a

main :: IO ()
main = do
    [n, k] <- map (read::String->Int) . words <$> getLine
    as <- map (read::String->Int) . words <$> getLine
    bs <- map (read::String->Int) . words <$> getLine
    let blocks = zipWith (nums k) as bs
    print $ foldl' (\a -> \b -> a*b `mod` modn) 1 blocks


import Data.Char
main = do nk <- getLine
          let n = (read.head.words) nk
          let k = (toInteger.read.last.words) nk
          sa <- getLine
          let a = (map toInteger.map read.words) sa
          let b = calc n a 0
          let s = scanr1 (\x y -> (if y > k * 10 then y else y * 2 + x)) (if last b < 0 then map (0 -) b else b)
          let ans = if last b < 0 then calc2 n k (map (0-) a) (map (0-) b) s else calc2 n k a b s
          putStrLn (show ans)
myRead :: String -> Int
myRead ('-':as) = 0 - foldl (\x y -> 10*x + (ord y - ord '0')) 0 as
myRead s = foldl (\x y -> 10*x + (ord y - ord '0')) 0 s
calc :: Int -> [Integer] -> Int -> [Integer]
calc 0 (a:[]) car = [toInteger car + a]
calc n (a:as) car = if bi < 0
                      then toInteger(mod (-bi) 2):calc (n-1) as (-(div (-bi) 2) - mod (-bi) 2)
                      else toInteger(mod bi 2):calc (n-1) as (div bi 2)
                    where bi = car + fromInteger a
calc2 :: Int -> Integer -> [Integer] -> [Integer] -> [Integer] -> Int
calc2 0 k (a:[]) (b:[]) (s:[]) = if abs (s - a) <= k && a /= s then 1 else 0
calc2 n k (a:as) (b:bs) (s:ss) | b /= 0 && abs (s - a) <= k = 1
                               | b /= 0 = 0
                               | abs (s - a) <= k = 1 + calc2 (n-1) k as bs ss
                               | otherwise = calc2 (n-1) k as bs ss

large=123456789123456789
main=interact$show.f1.map read.tail.words
f1 (a:b)=f3 a 0 b $(reverse.f2 a 0.reverse) b
f2 a b [c]=[]
f2 a b (c:d)=if abs e>a then large:f2 a large d else e:f2 a e d where e=b*2+c
f3 a b [c] _=if abs b<=a && b/=0 then 1 else 0
f3 a b (c:d) (e:f)=if e/=large && abs (e*2+b)<=a then 1+g else g where g=f4 a (b+c) d f
f4 a b c d=if odd b then 0 else f3 a (div b 2) c d

import Data.Char
main = do nk <- getLine
          let n = (myRead.head.words) nk
          let k = (toInteger.myRead.last.words) nk
          sa <- getLine
          let a = (map toInteger.map myRead.words) sa
          let b = calc n a 0
          let s = scanr1 (\x y -> (if y > k * 10 then y else y * 2 + x)) (if last b < 0 then map (0 -) b else b)
          let ans = if last b < 0 then calc2 n k (map (0-) a) (map (0-) b) s else calc2 n k a b s
          putStrLn (show ans)
myRead :: String -> Int
myRead ('-':as) = 0 - foldl (\x y -> 10*x + (ord y - ord '0')) 0 as
myRead s = foldl (\x y -> 10*x + (ord y - ord '0')) 0 s
calc :: Int -> [Integer] -> Int -> [Integer]
calc 0 (a:[]) car = [toInteger car + a]
calc n (a:as) car = if bi < 0
                      then toInteger(mod (-bi) 2):calc (n-1) as (-(div (-bi) 2) - mod (-bi) 2)
                      else toInteger(mod bi 2):calc (n-1) as (div bi 2)
                    where bi = car + fromInteger a
calc2 :: Int -> Integer -> [Integer] -> [Integer] -> [Integer] -> Int
calc2 0 k (a:[]) (b:[]) (s:[]) = if abs (s - a) <= k && a /= s then 1 else 0
calc2 n k (a:as) (b:bs) (s:ss) | b /= 0 && abs (s - a) <= k = 1
                               | b /= 0 = 0
                               | abs (s - a) <= k = 1 + calc2 (n-1) k as bs ss
                               | otherwise = calc2 (n-1) k as bs ss


{-# LANGUAGE Safe #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE MultiWayIf #-}

import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Control.Applicative
import Control.Arrow
import Data.List
import Data.Array
import Data.Array.IO.Safe
import Data.Array.ST.Safe
import Data.IORef
import Data.STRef
import Data.Maybe
import Data.Bits
import Data.Ord
import Data.Ratio
import Data.Int
import Data.Char
import qualified Data.IntMap as IM
import qualified Data.ByteString.Char8 as BS
import qualified Data.Set as Set
import qualified Data.Sequence as Sq
import Data.Tuple
import Data.Function
import Text.Printf
import Numeric

readIntBS = fst . fromJust . BS.readInt

main = do
  t <- readLn :: IO Int
  replicateM_ t $ do
    [len,v,l,r] <- map read . words <$> getLine :: IO [Int]
    print $ len`div`v - r`div`v + (l-1)`div`v

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

solve1 :: (Int, Int, Int, Int) -> Int
solve1 (d, v, l, r) = max 0 (lt - ls + 1) + max 0 (rt - rs + 1)
  where
    ls = 1
    lt = (l - 1) `div` v
    rs = (r + 1 + v - 1) `div` v
    rt = d `div` v

main :: IO ()
main = do
    n <- readLn
    dvlrs <- replicateM n $ do
        [d, v, l, r] <- unfoldr (B.readInt . B.dropWhile (== ' ')) <$> B.getLine
        return (d, v, l, r)
    mapM_ (print . solve1) dvlrs


import Control.Monad
import Data.Maybe
import Data.Int
import Data.List
import qualified Data.ByteString.Char8 as C
import qualified Data.Map.Strict as M
import Data.ByteString.Builder
import System.IO

parseInt :: (Integral a) => C.ByteString -> a
parseInt = fromIntegral . fst . fromJust . C.readInteger

getInts :: (Integral a) => IO [a]
getInts = map parseInt . C.words <$> C.getLine

update :: Num a => a -> Maybe a -> Maybe a
update delta value = case value of
  Nothing -> Just delta
  Just x -> Just (x + delta)

main :: IO ()
main = do
  [numCase] <- getInts
  output <- fmap mconcat $ replicateM numCase $ do
    [n, h] <- getInts :: IO [Int64]
    as <- getInts :: IO [Int64]
    let m1 = foldl' (\mp x -> M.alter (update 1) x mp) M.empty $ zipWith (-) (tail as) as
        m2 = snd $ M.mapAccumWithKey (\(c, t) x y -> let p = (c + y, t + x * y) in (p, p)) (0, 0) m1
        check x = case M.lookupLE x m2 of
                    Nothing -> n * x >= h
                    Just (_, (c, t)) -> (n - c) * x + t >= h
        func l r
          | l == r = l
          | check m = func l m
          | otherwise = func (m + 1) r
          where m = (l + r) `div` 2
    return $ int64Dec (func 1 h) <> charUtf8 '\n'
  hPutBuilder stdout output

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.Int -- don't be an idiot who gets hacked because of Int32

binSearch :: (Int64 -> Bool) -> Int64 -> Int64 -> Int64
{-# INLINE binSearch #-}
binSearch p = let
  go li ri = if  li == ri
    then  li
    else  let
    mi = li + quot (ri - li) 2
    in  if  p mi
    then  go li mi
    else  go (mi + 1) ri
  in  go

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    ~[h] <- getInt64s 1
    a <- getInt64s n
    let
      score k = (\step -> foldl' step k $ zipWith (-) (tail a) a) $ \acc sz ->
        acc + min k sz
      ans = binSearch (\k -> score k >= h) 0 h
    pure $ putInt64s [ans]

type SP = State [P.ByteString]

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

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k
getInt64s :: Int -> SP [Int64]
getInt64s k = map (fromIntegral . fst . fromJust . P.readInteger) <$> getNext k

putInt64s :: [Int64] -> Builder
putInt64s vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.int64Dec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> int64Dec 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 Data.Maybe

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

binSearch :: (Int -> Bool) -> Int -> Int -> Int
{-# INLINE binSearch #-}
binSearch p = let
  go li ri = if  li == ri
    then  li
    else  let
    mi = li + quot (ri - li) 2
    in  if  p mi
    then  go li mi
    else  go (mi + 1) ri
  in  go

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n, h] <- getInts 2
    a <- getInts n
    let
      score k = (\step -> foldl' step k $ zipWith (-) (tail a) a) $ \acc sz ->
        acc + min k sz
      ans = binSearch (\k -> score k >= h) 0 h
    pure $ putInts [ans]

type SP = State [P.ByteString]

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

getInts :: Int -> SP [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 Data.Array
import Control.Monad (replicateM_, replicateM)

main :: IO ()
main = read <$> getLine >>= flip replicateM_ singleCase

singleCase :: IO ()
singleCase = map read . words <$> getLine >>=
             \([n, m]) -> replicateM n (map read . words <$> getLine) >>=
             print . maxSum . listArray ((1, 1), (n, m)) . concat

diagSum :: Int -> Array (Int, Int) Int -> Bool -> Int
diagSum dd a b = let ((1,1), (n, m)) = bounds a
                     bf True i = dd+i
                     bf False i = dd-i
                     -- par True = [(1-n) .. (m-1)]
                     -- par False = [2 .. (n+m)]
                 in
                   sum . map (a!) . filter (inRange (bounds a)) $
                   [(i, bf b i) | i <- [1..n]]

maxSum :: Array (Int, Int) Int -> Int
maxSum a = let ((1, 1), (n, m)) = bounds a
               pd = array (1-n, m-1) [(k, diagSum k a True) | k <- [(1-n)..(m-1)]]
               nd = array (2, n+m) [(k, diagSum k a False) | k <- [2..(n+m)]]
               f acc (i, j) = max acc ((pd!(j-i))+(nd!(j+i))-(a!(i, j)))
           in
             foldl f 0 $ range (bounds a)

readArr :: Int -> IO [[Int]]
readArr 0 = pure []
readArr i = do
  arr <- map (\s -> read s :: Int) <$> (words <$> getLine)
  ans <- readArr $ i - 1
  pure (arr: ans)

mergeL :: [Int] -> [Int] -> [Int]
mergeL a [] = a
mergeL (x: xs) (y: ys) = (x + y: mergeL xs ys)

mergeR :: [Int] -> [Int] -> [Int]
mergeR [] a = a
mergeR (x: xs) (y: ys) = (x + y: mergeR xs ys)

calcLD :: [[Int]] -> [Int]
calcLD (x: []) = x
calcLD (x: xs) = reverse $ mergeR (reverse x) (0: (reverse $ calcLD xs))

calcRD :: [[Int]] -> [Int]
calcRD (x: []) = x
calcRD (x: xs) = mergeR x (0: calcRD xs)

calcH :: Int -> [Int] -> [Int] -> Int -> Int -> [Int] -> Int
calcH _ _ _ _ _ [] = 0
calcH n ld rd i j (x: xs) = max (rd !! (i + j) + ld !! (j - i + n - 1) - x) (calcH n ld rd i (j + 1) xs)

calc :: Int -> [Int] -> [Int] -> Int -> [[Int]] -> Int
calc _ _ _ _ [] = 0
calc n ld rd i (x: xs) = max (calcH n ld rd i 0 x) (calc n ld rd (i + 1) xs)

for :: Int -> IO ()
for 0 = pure ()
for i = do
  (n: m: _) <- map (\s -> read s :: Int) <$> (words <$> getLine)
  arr <- readArr n
  print $ calc n (calcLD arr) (calcRD arr) 0 arr
  for $ i - 1

main :: IO ()
main = do
  t <- readLn :: IO Int
  for t


main :: IO ()
main = getContents >>= printSolution . solve . map (map read . words) . tail . lines

solve :: [[Int]] -> [Int]
solve = map fst . filter (not . any (`elem` [1, 3]) . snd) . zip [1..]

printSolution :: Show a => [a] -> IO ()
printSolution xs = print (length xs) >> putStrLn (unwords (map show xs))

import Control.Monad
import Data.List

main = do
    n <- fmap read getLine
    xs <- forM [1..n] (\i -> do
        ys <- fmap (map read . words) getLine
        if 1 `elem` ys || 3 `elem` ys then return []
                                      else return [i]
        )
    let cxs = concat xs
    print $ length cxs
    putStrLn . intercalate " " . map show $ cxs

import Control.Monad
import Data.List

split key str = split_helper str [] where
    split_helper [] acc = if null acc then [] else [reverse acc]

    split_helper str acc =
        let
            c = head str
        in
            if head str == key then
                if null acc then
                    split_helper (tail str) []
                else
                    reverse acc : split_helper (tail str) []
            else
                split_helper (tail str) (c : acc)

solve n m i =
    if i > n then
        []
    else let
        rest = solve n (tail m) (i+1)
        good x = x < 0 || even x
    in
        if all (good . read) $ split ' ' (head m) then
            i : rest
        else
            rest

main = do
    n <- readLn
    m <- sequence $ take n $ repeat getLine
    let result = solve n m 1
    print $ length result
    when (length result > 0) $
        putStrLn $ concat $ intersperse " " $ map show result

import Control.Applicative
import Data.List

main= do
	n<-  read  <$>getLine::IO Int
	s<- map (map read). map words. lines <$> getContents ::IO [[Int]]
	let t=  map (length . take 1. filter (\z-> elem z [1,3])) s
	let t1= map snd $ filter (\z-> fst z==0) $ zip t [1..]
	print $ length t1
	putStrLn $ intercalate " " $ map show t1

import Data.Array.Unboxed
import qualified Data.Set as Set
import Data.List

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

main = do
	cars <- getLine

	let
		n = read cars :: Int

	rows_list <- getLines n

	let
		rows = map read $ concat $ map words $ rows_list :: [Int]
		matrix = listArray ((1, 1), (n, n)) rows :: UArray (Int, Int) Int
		good_cars = findGoodCars matrix n

	putStrLn $ show $ length good_cars
	putStrLn $ intercalate " " $ map show good_cars

findGoodCars :: UArray (Int, Int) Int -> Int -> [Int]
findGoodCars matrix n = [1..n] \\ (Set.elems $ findBadCars matrix 1 Set.empty)
	where
		findBadCars :: UArray (Int, Int) Int -> Int -> Set.Set Int -> Set.Set Int
		findBadCars matrix row set
			| row > n = set
			| otherwise = findBadCars matrix (row+1) bad
			where
				bad = inspectCollisions matrix row 1 set
				inspectCollisions :: UArray(Int, Int) Int -> Int -> Int -> Set.Set Int -> Set.Set Int
				inspectCollisions matrix row col set
					| col > n = set
					| collision == 1 = inspectCollisions matrix row (col+1) (Set.insert row set)
					| collision == 2 = inspectCollisions matrix row (col+1) (Set.insert col set)
					| collision == 3 = inspectCollisions matrix row (col+1) (Set.insert row $ Set.insert col set)
					| otherwise = inspectCollisions matrix row (col + 1) set
					where
						collision = matrix!(row,col)

{-# 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
  n <- readLn
  rs <- replicateM n getInts

  let is = map snd $ filter (all (`elem` [0, -1, 2]) . fst) $ zip rs [1..]

  print $ length is
  putStrLn $ unwords $ map show is

import Data.List (intercalate)
answer::[[Int]] -> [Int]
answer a = toNumberList $ map (all (\x -> (x == -1 || x == 0 || x == 2))) a
toNumberList::[Bool] -> [Int]
toNumberList [] = []
toNumberList b = map fst $ filter (\x -> snd x) $ zip [1..] b
readInput::Int -> IO [[Int]]
readInput 0 = return []
readInput n = do
  w <- getLine
  let a = [read n::Int|n <- (words w)]
  next <- readInput (n-1)
  return ([a] ++ next)
printAnswer::[Int] -> IO ()
printAnswer [] = print 0
printAnswer x = do
  print (length x)
  putStrLn $ intercalate " " $ map show $ x
main = do
  w <- getLine
  let n = read w::Int
  m <- readInput n
  printAnswer $ answer m

module Main where
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8  as C
import Data.List
import Data.Maybe

getInt :: IO Int
getInt = fst . fromJust . C.readInt <$> C.getLine

getIntMat :: IO [[Int]]
getIntMat = map ((map (read::String->Int)) . words) . lines <$> getContents

main :: IO ()
main = do
  n <- getInt
  m <- getIntMat
  let gs = sol m
  print $ length gs
  putStrLn . unwords $ map show gs

sol :: [[Int]] -> [Int]
sol = map ((+1) . fst) . filter (\(i,xs) -> all good xs) . zip [0..]
  where
  good x = x==(-1) || x`mod`2==0

{-# LANGUAGE ScopedTypeVariables #-}

import Control.Monad

main = do
    n <- getLine >>= return.read
    m <- replicateM n getLine >>= return.(map good)
    let l = map snd $ filter fst $ zip m [1..n]
    putStrLn $ show $ length l
    putStrLn $ unwords $ map show l

good s = not $ any (\x -> x==1||x==3) ((map read)$words s)

-- http://codeforces.com/problemset/problem/545/A

import Data.List

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

main = do
	cars <- getLine

	let
		n = read cars :: Int

	rows_list <- getLines n

	let
		collisions = map read $ concat $ map words $ rows_list :: [Int]
		cars = getCars n
		good_cars = findGoodCars cars collisions

	putStrLn $ show $ length good_cars
	putStrLn $ intercalate " " $ map show good_cars

-- (Car number, Good/Bad - True/False)
type Car = (Int, Bool)
-- Initially all cars are good
getCars :: Int -> [Car]
getCars n = [(x, True) | x <- [1..n]]

findGoodCars :: [Car] -> [Int] -> [Int]
findGoodCars cars collisions =
	foldr
	(\(n, s) acc -> if s then n:acc else acc)
	[] $ findGoodCars' cars collisions 1
	where
		n = length cars
		findGoodCars' :: [Car] -> [Int] -> Int -> [Car]
		findGoodCars' cars [] _ = cars
		findGoodCars' cars (c:cs) index
			| c == 1 = findGoodCars' (markBadCar row cars) cs (index + 1)
			| c == 2 = findGoodCars' (markBadCar col cars) cs (index + 1)
			| c == 3 = findGoodCars' (markBadCar col $ markBadCar row cars) cs (index + 1)
			| otherwise = findGoodCars' cars cs (index+1)
			where
				row = index `quot` n
				col = ((index-1) `mod` n) + 1
				markBadCar :: Int -> [Car] -> [Car]
				markBadCar _ [] = []
				markBadCar i ((n,s):cs)
					| i == n = (n, False):cs
					| otherwise = (n, s):markBadCar (i) cs

import Data.Array.Unboxed
import qualified Data.Set as Set
import Data.List

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

main = do
	cars <- getLine

	let
		n = read cars :: Int

	rows_list <- getLines n

	let
		rows = map read $ concat $ map words $ rows_list :: [Int]
		matrix = listArray ((1, 1), (n, n)) rows :: UArray (Int, Int) Int
		good_cars = findGoodCars matrix n

	putStrLn $ show $ length good_cars
	putStrLn $ intercalate " " $ map show good_cars

findGoodCars :: UArray (Int, Int) Int -> Int -> [Int]
findGoodCars matrix n = [1..n] \\ (Set.elems $ findBadCars matrix 1 Set.empty)
	where
		findBadCars :: UArray (Int, Int) Int -> Int -> Set.Set Int -> Set.Set Int
		findBadCars matrix row set
			| row > n = set
			| n `Set.member` set = findBadCars matrix (row+1) set
			| otherwise = findBadCars matrix (row+1) bad
			where
				bad = inspectCollisions matrix row 1 set
				inspectCollisions :: UArray(Int, Int) Int -> Int -> Int -> Set.Set Int -> Set.Set Int
				inspectCollisions matrix r col set
					| col > n = set
					| collision == 1 = inspectCollisions matrix r (col+1) (Set.insert r set)
					| collision == 2 = inspectCollisions matrix r (col+1) (Set.insert col set)
					| collision == 3 = inspectCollisions matrix r (col+1) (Set.insert r $ Set.insert col set)
					| otherwise = inspectCollisions matrix r (col + 1) set
					where
						collision = matrix!(r,col)

-- http://codeforces.com/problemset/problem/545/A

import Data.List

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

main = do
	cars <- getLine

	let
		n = read cars :: Int

	rows_list <- getLines n

	let
		collisions = map read $ concat $ map words $ rows_list :: [Int]
		cars = getCars n
		good_cars = findGoodCars cars collisions

	putStrLn $ show $ length good_cars
	putStrLn $ intercalate " " $ map show good_cars

-- (Car number, Good/Bad - True/False)
type Car = (Int, Bool)
-- Initially all cars are good
getCars :: Int -> [Car]
getCars n = [(x, True) | x <- [1..n]]

findGoodCars :: [Car] -> [Int] -> [Int]
findGoodCars cars collisions =
	foldr
	(\(n, s) acc -> if s then n:acc else acc)
	[] $ findGoodCars' cars collisions 0
	where
		n = length cars
		findGoodCars' :: [Car] -> [Int] -> Int -> [Car]
		findGoodCars' cars [] _ = cars
		findGoodCars' cars (c:cs) index
			| c == 1 = findGoodCars' (markBadCar row cars) cs (index + 1)
			| c == 2 = findGoodCars' (markBadCar col cars) cs (index + 1)
			| c == 3 = findGoodCars' (markBadCar col $ markBadCar row cars) cs (index + 1)
			| otherwise = findGoodCars' cars cs (index+1)
			where
				row = index `quot` n
				col = (index `mod` n) + 1
markBadCar :: Int -> [Car] -> [Car]
markBadCar _ [] = []
markBadCar i ((n,s):cs)
	| i == n = (n, False):cs
	| otherwise = (n, s):markBadCar (i) cs

module Main where
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8  as C
import Data.List
import Data.Maybe

getInt :: IO Int
getInt = fst . fromJust . C.readInt <$> C.getLine

getIntMat :: IO [[Int]]
getIntMat = map ((map (read::String->Int)) . words) . lines <$> getContents

main :: IO ()
main = do
  n <- getInt
  m <- getIntMat
  putStrLn . unwords . map show $ sol m

sol :: [[Int]] -> [Int]
sol = map ((+1) . fst) . filter (\(i,xs) -> all (f i) $ zip [0..] xs) . zip [0..]
  where
  f j (k,x) = j==k || x`mod`2==0


{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad (replicateM, guard)
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromJust)
import Data.List (elemIndex)

main :: IO ()
main = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines

type InputTy = [Int]
type OutputTy = Maybe [Int]

input :: Scanner InputTy
input = numberOf int

solve :: InputTy -> OutputTy
solve [_] = Just []
solve as = do
  i <- elemIndex n as
  guard $ even i
  as <- rev (i + 1) as
  j <- elemIndex (n - 1) as
  guard $ odd j
  as <- rev j as
  as <- rev (j + 2) as
  as <- rev 3 as
  let as' = reverse (drop 2 as)
  ([i + 1, j, j + 2, 3, n] ++) <$> solve as'
    where
      n = length as
      rev k as = let (ls, rs) = splitAt k as in Just $ reverse ls ++ rs

output :: OutputTy -> C.ByteString
output Nothing = C.pack "-1"
output (Just xs) = C.pack $ show (length xs) ++ "\n" ++ unwords (map show xs)

-------------------------- Template ------------------------------------------
type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = gets head

bstr :: Scanner C.ByteString
bstr = get >>= \case s : ss -> put ss >> return s

str :: Scanner String
str = C.unpack <$> bstr

int :: Scanner Int
int = fst . fromJust . C.readInt <$> bstr

integer :: Scanner Integer
integer = read . C.unpack <$> bstr

double :: Scanner Double
double = read . C.unpack <$> bstr

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t
    then return []
    else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)

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

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

import Data.List

rev :: Int -> State [Int] ()
rev k = do
  ~(sp, ss) <- splitAt k <$> get
  put (reverse sp ++ ss)

solve :: Int -> State [Int] [Int]
solve 1 = pure []
solve n = do
  ~(Just npos) <- elemIndex n <$> get
  rev (npos + 1)
  ~(Just ppos) <- elemIndex (n-1) <$> get
  rev ppos
  rev (ppos + 2)
  rev 3
  rev n
  (\res -> npos + 1 : ppos : ppos + 2 : 3 : n : res) <$> solve (n-2)

main :: IO ()
main = (P.words <$> P.getContents >>=) $ evalStateT $ do
  [t] <- getInts 1
  replicateM_ t $ do
    [n] <- getInts 1
    a <- getInts n
    let
      isOK = all even $ zipWith (-) a [1..]
      ans = filter (> 1) $ evalState (solve n) a
    if  isOK
      then  putInts [length ans] >> putInts ans
      else  putInts [0-1]

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

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]

putInts :: [Int] -> SIO ()
putInts li = let
  spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec
  in  lift $ B.hPutBuilder stdout $ case  li  of
  [] -> B.char7 '\n'
  x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\n'


import Data.Char (isSpace)

insertArrows :: String -> String
insertArrows "" = ""
insertArrows (x : xs) = x : concatMap (("->" ++) . pure) xs

arrowsAfterEach :: String -> String
arrowsAfterEach = concatMap (: "->")

solve :: String -> String
solve inp = case  reverse inp  of
  [] -> error "expected input"
  '1' : _  -> "NO\n"
  '0' : [] -> "YES\n0\n"
  '0' : '1' : _ -> "YES\n" ++ insertArrows inp ++ "\n"
  '0' : '0' : xs
    -> case  span (== '1') xs  of
    (_, []) -> "NO\n"
    (ones, '0' : ys) ->
      "YES\n"
      ++ arrowsAfterEach (reverse ys)
      ++ "(0->("
      ++ arrowsAfterEach ones
      ++ "0))->0\n"
    _ -> error "expected 0 or 1"
  _ -> error "expected 0 or 1"

main :: IO ()
main = interact (solve . filter (not . isSpace) . dropWhile (/= '\n'))

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

solve :: [Int] -> IO()
solve (_:a) =
    let
        zeroNum = length $ filter (==0) a
        ra = reverse a
        na = reverse $ tail ra
        r1 = head ra
        r2 = head $ tail ra
        invalid = (r1 == 1) || (zeroNum == 2 && r2 == 0)
    in
        if invalid then
            putStrLn "NO"
        else
            if (null na) then
                putStrLn "YES\n0"
            else do putStr "YES\n("
                    firstZero na True
                    putStrLn "->0)"
    where
        firstZero :: [Int] -> Bool -> IO()
        firstZero []     _              = putStr ")"
        firstZero (a:ax) True  | a == 0 = do putStr "(0->("
                                             incLast ax
                                             putStr "))"
                               | a == 1 = do putStr "(1"
                                             firstZero ax False
        firstZero (a:ax) False | a == 0 = do putStr "->(0->("
                                             incLast ax
                                             putStr ")))"
                               | a == 1 = do putStr "->1"
                                             firstZero ax False

        incLast :: [Int] -> IO()
        incLast (a:ax) | null ax   = putStr $ show a
                       | otherwise = do putStr $ show a
                                        putStr "->"
                                        incLast ax

import Control.Applicative ((<$>))
import Control.Monad (mapM_, (>>=))

solve :: String -> [String]
solve a
    | last a /= '0' = ["NO"]
    | a == "0"      = ["YES", "0"]
    | dropWhile (/= '0') a == "00" = ["NO"]
    | take 2 (reverse a) == "01" = ["YES", loop a]
    | head a == '0' = ["YES", "0->(" ++ (loop . init . tail $ a) ++ ")->0"]
    | otherwise = ["YES", loop a' ++ "->(0->(" ++ loop a'' ++ "))->0"]
    where
    a' = takeWhile (/= '0') a
    a'' = init . tail . dropWhile (/= '0') $ a
    loop :: String -> String
    loop "1" = "1"
    loop "0" = "0"
    loop (i:rest) = i:"->" ++ loop rest

main :: IO ()
main = getLine >>= \_ -> solve . filter (/= ' ') <$> getLine >>= mapM_ putStrLn

import Data.Char (isSpace)

insertArrows :: String -> String
insertArrows "" = ""
insertArrows (x : xs) = x : concatMap (("->" ++) . pure) xs

arrowsAfterEach :: String -> String
arrowsAfterEach = concatMap (: "->")

solve :: String -> String
solve inp = case  reverse inp  of
  [] -> error "expected input"
  '1' : _  -> "NO\n"
  '0' : [] -> "YES\n0\n"
  '0' : '1' : _ -> "YES\n" ++ insertArrows inp ++ "\n"
  '0' : '0' : xs
    -> case  span (== '1') xs  of
    (_, []) -> "NO\n"
    (ones, '0' : ys) ->
      "YES\n"
      ++ arrowsAfterEach ys
      ++ "(0->("
      ++ arrowsAfterEach ones
      ++ "0))->0\n"
    _ -> error "expected 0 or 1"
  _ -> error "expected 0 or 1"

main :: IO ()
main = interact (solve . filter (not . isSpace) . dropWhile (/= '\n'))


{-# LANGUAGE LambdaCase #-}

import Control.Monad

main = do
    n <- read <$> getLine
    replicateM_ n $ do
        map read . words <$> getLine >>= \case
            [n, d] ->
                if minDays d <= n
                then putStrLn "YES"
                else putStrLn "NO"
            _ -> undefined

minDays d = minimum [i + ceiling (fromInteger d / fromInteger (i + 1)) | i <- [(guess-1)..(guess+2)]]
  where
    guess = floor $ sqrt (fromInteger d) - 1

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

a ! b = (a - 1) `div` b + 1

works n d = let x = floor $ sqrt $ fromIntegral d in any (<= n) $ (\a -> a + d ! (a + 1)) <$> [max (x - 10) 0..x + 10]

main = getLine >>= test.read

test 0 = return ()
test n = do
  (a:b:_) <- map read.words <$> getLine
  output $ works a b
  test $ pred n

output True = putStrLn "YES"
output _ = putStrLn "NO"

f :: Integer -> Integer -> Integer
f d x = x + ceiling( fromIntegral(d) / fromIntegral(x+1) )

solveTask :: (Integer, Integer) -> String
solveTask (n, d)
    | d <= n = "YES\n"
    | otherwise =
      let x = sqrt (fromIntegral  d) - 1
          x0 = floor x
          x1 = ceiling x
      in if f d x0 <= n || f d x1 <=n
        then "YES\n" else "NO\n"

groupTaskInput :: [String] -> [(Integer, Integer)]
groupTaskInput [] = []
groupTaskInput (n:(d:xs)) = (read n, read d) : groupTaskInput(xs)

makeTaskInput :: String -> [(Integer, Integer)]
makeTaskInput s = groupTaskInput $ tail $ words $ s

solve :: String -> String
solve s = concat $ (map solveTask) $ makeTaskInput s

main' :: IO ()
main' = do interact $ solve

main = main'

import Control.Monad
import Data.Int

getToken :: IO String
getToken = do
    x <- getChar
    if x == ' ' || x == '\t' || x == '\n'
        then return [x]
        else liftM2 (\x y -> x : y) (return x) getToken

get :: Read a => IO a
get = liftM read getToken

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

putln :: Show a => a -> IO ()
putln = putStrLn . show

main :: IO ()
main = do
    t <- get :: IO Int
    replicateM_ t f1

f1 :: IO ()
f1 = do
    n <- get :: IO Int32
    d <- get :: IO Int32
    putStrLn (if f2 n d then "YES" else "NO")

f2 :: Int32 -> Int32 -> Bool
f2 n d = let x = bs 0 (fromIntegral d) (fromIntegral d) in
    (x + (div ((fromIntegral d) + x) (x + 1)) <= (fromIntegral n))

bs :: Int64 -> Int64 -> Int64 -> Int64
bs min max d = let aux x = x < (div (d + x) (x + 1)) in
    if min + 1 >= max then
        min
    else
        let mid = div (min + max) 2 in
        if aux mid then
            bs mid max d
        else
            bs min mid d

import System.IO
-- import Prelude

readInt :: IO Int
readInt = readLn

readTuple :: IO (Int, Int)
readTuple = readLn

castToInt x = read x::Int

main = do
    t <- readInt
    mainLoop t

mainLoop t = do
    if t == 0 then
        return ()
    else do
        line <- getLine
        let test_case = (map castToInt . take 2 . words) line

        solveTask test_case

        mainLoop (t - 1)

solveTask test_case = do
    let (n, d) = (head test_case, (head . tail) test_case)
    let x = sqrt (fromIntegral d) - 1

    let lower_x = floor x
    let upper_x = ceiling x

    let xs = [lower_x, upper_x]
    let ys = map (getActualDays d) xs
    let max_days = maximum ys

    if max_days <= n then putStrLn "YES"
        else putStrLn "NO"

getActualDays :: Int -> Int -> Int
getActualDays d x = x + ceiling (fromIntegral d / (fromIntegral x + 1))

{-# LANGUAGE Strict #-}

import Control.Monad
import Data.Ratio

solve n d i
  | i >= n = "NO"
  | total > n = solve n d (i+1)
  | otherwise = "YES"
  where
    total = i + run
    run = ceiling $ d % (i+1)

main = do
  t <- readLn :: IO Int
  replicateM_ t $ do
    [n,d] <- map read . words <$> getLine :: IO [Int]
    putStrLn $ solve n d 0

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

a ! b = (a - 1) `div` b + 1

works n d = let x = floor $ sqrt $ fromIntegral d in any (<= n) $ (\a -> a + d ! (a + 1)) <$> [max (x - 10) 0..x + 10]

main = getLine >>= test.read

test 0 = return ()
test n = do
  (a:b:_) <- map read.words <$> getLine
  output $ works a b
  test $ pred n

output True = print "YES"
output _ = print "NO"

import Control.Monad
import Data.Int

getToken :: IO String
getToken = do
    x <- getChar
    if x == ' ' || x == '\t' || x == '\n'
        then return [x]
        else liftM2 (\x y -> x : y) (return x) getToken

get :: Read a => IO a
get = liftM read getToken

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

putln :: Show a => a -> IO ()
putln = putStrLn . show

main :: IO ()
main = do
    n <- get :: IO Int64
    m <- get :: IO Int64
    a <- get :: IO Int64
    putln $ f1 n m a

f1 :: Int64 -> Int64 -> Int64 -> Int64
f1 n m a = ((div (n + a - 1) a) * (div (m + a - 1) a))

import Control.Monad
import Data.Int

getToken :: IO String
getToken = do
    x <- getChar
    if x == ' ' || x == '\t' || x == '\n'
        then return [x]
        else liftM2 (\x y -> x : y) (return x) getToken

get :: Read a => IO a
get = liftM read getToken

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

putln :: Show a => a -> IO ()
putln = putStrLn . show

main :: IO ()
main = do
    t <- get :: IO Int
    replicateM_ t f1

f1 :: IO ()
f1 = do
    n <- get :: IO Int32
    d <- get :: IO Int32
    putln (if f2 n d then "YES" else "NO")

f2 :: Int32 -> Int32 -> Bool
f2 n d = let x = bs 0 (fromIntegral d) (fromIntegral d) in
    (x + (div ((fromIntegral d) + x) (x + 1)) <= (fromIntegral n))

bs :: Int64 -> Int64 -> Int64 -> Int64
bs min max d = let aux x = x < (div (d + x) (x + 1)) in
    if min + 1 >= max then
        min
    else
        let mid = div (min + max) 2 in
        if aux mid then
            bs mid max d
        else
            bs min mid d


import Control.Applicative( (<$>))
import Data.Bool( bool)
import Control.Monad( replicateM)
main = do
    [vic1_, vic2_] <- words <$> getLine
    n <- readLn::IO Int
    changes_ <- replicateM n (words <$> getLine)
    let
	proc [vic1, vic2]	[]	    = [vic1++" "++vic2]
	proc [vic1, vic2] ([from,to]:rem) = let
			    l = vic1++" "++vic2
			    candi1 = [to,vic2]
			    candi2 = [vic1,to]
			    next = bool candi2 candi1 (vic1==from)
			in
			    l:(proc next rem)
    mapM_ putStrLn $ proc [vic1_, vic2_] changes_

f::String->String->[String]->[String]
f _ _ []=[]
f a b (s:str)=let (c:d:[])=words s
              in if c==a then (d++" "++b):(f d b str) else (a++" "++d):(f a d str)

main = do
       e<-getLine
       e2<-getLine
       e3<-getContents
       let (a:b:[])=words e
       mapM_ putStrLn $ (a++" "++b) :f a b (lines e3)

f (a, b) (c, d) = if a == c then (b, d) else (a, d)

g s = (l !! 0, l !! 1)
    where l = words s

g' t = (fst t) ++ " " ++ (snd t)

main = do
        initialNames <- getLine
        nS <- getLine
        let n = read nS :: Int
        restOfTheNames <- sequence (take n (repeat getLine))
        let result = unlines (map g' (scanl f (g initialNames) (map g restOfTheNames)))
        putStrLn result


-- Codeforces Round #531 (C), Contest 1102, Problem set ?.

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.Function

main :: IO ()
main = do
  [n,x,y] <- map read . words <$> getLine :: IO [Int]
  as <- unfoldr (BS.readInt . BS.dropWhile(<'!')) <$> BS.getLine :: IO [Int]
  let breakableInOne = length $ filter (<= x) as
  print $ if x > y then n else (breakableInOne+1) `shiftR` 1

import Data.Function -- on
import Data.Functor -- <$>
import Data.List hiding (sortOn)

toList :: (Read a) => String -> [a]
toList = map read <$> words

main = do
    [n, x, y] <- toList <$> getLine :: IO [Int]
    as <- toList <$> getLine :: IO [Int]
    let ans = if x > y then n
              else (succ $ length $ filter (<= x) as) `div` 2
    print ans

import Control.Monad
readInts = liftM (map read . words) getLine
solve [[n, x, y], s] = if x > y then n else (1 + length (filter (<=x) s)) `div` 2
main = replicateM 2 readInts >>= putStrLn . show . solve

import Control.Monad
readInts = liftM (map read . words) getLine
solve [[n, x, y], s] = if x > y then n else (1 + length (filter (<x) s)) `div` 2
main = replicateM 2 readInts >>= putStrLn . show . solve

import Control.Monad
readInts = liftM (map read . words) getLine
solve [n, x, y] s = if x > y then n else length $ takeWhile (< x) s
main = readInts >>= \s -> readInts >>= putStrLn . show . solve s


main = interact $ rounded

rounded :: String -> String
rounded s =
    let (intPart,fracPart) = span (/= '.') s
        (leadDigits, lastDigit) = (init intPart, last intPart)
        roundUp = (fracPart !! 1) `elem` ['5'..'9']
    in  if lastDigit == '9'
            then "GOTO Vasilisa."
            else if roundUp then leadDigits ++ [succ lastDigit] else intPart

import Data.Maybe
import Data.List
import Data.Bifunctor

main = do
    x <- getLine
    let (y,z) = splitAt (fromJust $ findIndex (=='.') x) x
    let int = read :: String -> Integer
    putStrLn $ case bimap int int (y, [head  $ tail z]) of
        (a,_) | a`mod`10 == 9 -> "GOTO Vasilisa."
        (a,b) | b < 5         -> show a
        (a,b)                 -> show $ succ a

import Char

bigTest = take 1000 (repeat '0') ++ ".9"

myRound :: String -> String
myRound line = myRound' "" line
  where
    myRound' prefix (a:'.':b:_)
      |  a == '9'  =  "GOTO Vasilisa."
      |  b <  '5'  =  prefix ++ [a]
      |  otherwise =  prefix ++ [intToDigit (digitToInt a + 1)]
    myRound' prefix (a:as) = myRound' (prefix ++ [a]) as
    myRound' _ _ = error "Not found '.'"

main = do
  line <- getLine
  putStrLn $ myRound line

import Data.List (delete)
import Data.Char (ord, chr)

remove (x:xs) = xs

solve s = roundNumber $ span (/='.') s
       where roundNumber (x,y) | last x == '9' = "GOTO Vasilisa."
                               | (head $ remove y) >= '5' = init x ++ [chr . (+1) . ord $ last x]
                               | otherwise = x

main = do number <- getLine
          putStrLn $ solve number

main = do
  n <- getLine
  putStrLn (round' n)
round' n | last i == '9' = "GOTO Vasilisa."
         | f!!1 < '5'    = i
         | otherwise     = show (read i + 1)
    where (i,f) = break (== '.') n

s(a,b)|last a=='9'="GOTO Vasilisa."|b!!1>'4'=init a++[succ$last a]|1>0=a
main=interact$s.span(/='.')

main = do d <- getLine
          let (d_int,(_:d_frac)) = span (/='.') d
          putStrLn $ if last d_int == '9' then
                         "GOTO Vasilisa."
                     else if (read [head d_frac]::Int) < 5 then
                              d_int
                          else
                              show ((read d_int::Integer)+1)

import Data.Maybe
import Data.List

f str | str !! (inx - 1) == '9' = "GOTO Vasilisa."
      | str !! (inx + 1) >= '5' = (take (inx - 1) str) ++  (show . (+) 1 . read $ [str !! (inx - 1)])
      | otherwise = take inx str
 where inx = fromJust . elemIndex '.'$ str

main = do
   str <- getLine
   putStrLn . f $ str

module Main where

import Data.List

main = do
    inputLine <- getLine
    let (prefix, postfix) = span (/='.') inputLine

    let result = if last prefix == '9'
            then "GOTO Vasilisa."
            else if postfix !! 1 >= '5'
                then show ( 1 + read prefix :: Integer )
                else prefix

    putStrLn result

import Data.Maybe
import Data.List
import Data.Bifunctor

main = do
    x <- getLine
    let (y,z) = splitAt (fromJust $ findIndex (=='.') x) x
    let int = read :: String -> Integer
    putStrLn $ case bimap int int (y, [head  $ tail z]) of
        (a,_) | a`mod`10 == 9 -> "GOTO Vasilasa."
        (a,b) | b < 5         -> show a
        (a,b)                 -> show $ succ a

import Data.Maybe
import Data.List
import Data.Bifunctor

main = do
    x <- getLine
    let (y,z) = splitAt (fromJust $ findIndex (=='.') x) x
    let int = read :: String -> Integer
    putStrLn $ case bimap int int (y, [head  $ tail z]) of
        (a,_) | a`mod`10 == 9 -> "GOTO Vasilasa"
        (a,b) | b < 5         -> show a
        (a,b)                 -> show $ succ a

main = (readLn :: IO Double) >>= \x ->  putStrLn $
    let (y,z) = (truncate x,x-fromIntegral y) in
    case (y,z) of
        (a,b) | a`mod`10 == 9 -> "GOTO Vasilasa"
        (a,b) | b < 0.5       -> show a
        _                     -> show $ succ y

main = interact $ rounded

rounded :: String -> String
rounded s =
    let (intPart,fracPart) = span (/= '.') s
        (leadDigits, lastDigit) = (init intPart, last intPart)
        roundUp = (fracPart !! 1) `elem` ['5'..'9']
    in  if roundUp
            then if lastDigit == '9'
                then "GOTO Vasilisa."
                else leadDigits ++ [succ lastDigit]
            else
                intPart

main = do d <- getLine
          let (d_int,(_:d_frac)) = span (/='.') d
          putStrLn $ if last d_int == '9' then
                         "GOTO Vasilisa."
                     else if (read [head d_frac]::Int) < 5 then
                              d_int
                          else
                              show ((read d_int::Int)+1)

s(a,b)|last a=='9'="GOTO Vasilisa."|b!!2>'4'=init a++[succ$last a]|1>0=a
main=interact$s.span(/='.')

import Data.Maybe
import Data.List

f str | str !! (inx - 1) == '9' = "GOTO Vasilisa"
      | str !! (inx + 1) >= '5' = (take (inx - 1) str) ++  (show . (+) 1 . read $ [str !! (inx - 1)])
      | otherwise = take inx str
 where inx = fromJust . elemIndex '.'$ str

main = do
   str <- getLine
   putStrLn . f $ str


{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P
import Data.List as L
import Data.Int (Int64)
import Data.Bits as B
import System.IO as Io
--import Data.Char as C
--import Data.IntSet as S

solve :: IO ()
solve = do
  n <- readLn :: IO Int
  let q = takeWhile (<n) $ scanl (+) 1 [3, 5..]
    in print $ length q + 1

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

main = interact $ unlines . map (show . ceiling . sqrt . read) . tail . lines

import Control.Monad

solve n = div ((n + 1) * (div n 2 + 1)) 2

printResult = do
    n <- readLn :: IO Int
    let xs = takeWhile (\x->solve x < n) [1,3..]
        r = if null xs then 1 else div (last xs) 2 + 2
    print r

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

import Control.Monad ( replicateM_ )

solve :: IO ()
solve = do
    s <- readLn :: IO Int
    let go x y = if y >= s then 0 else 1 + go (x + 2) (y + x + 2)
    print $ go (-1) 0

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

{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromJust, fromMaybe)

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

solve :: Int -> Int
solve s = (1 +) . length . takeWhile (< s) $ scanl1 (+) [1, 3 ..]

--- Template ---
type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = gets head

str :: Scanner C.ByteString
str = get >>= \case s : ss -> put ss >> return s

int :: Scanner Int
int = fst . fromJust . C.readInt <$> str

integer :: Scanner Integer
integer = read . C.unpack <$> str

double :: Scanner Double
double = read . C.unpack <$> str

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t then return [] else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)


import qualified Data.ByteString.Char8 as BS
import Data.ByteString (ByteString)
import Data.Char
import Data.Int

readInt :: IO Int
readInt = do line <- BS.getLine
             let Just (n,_) = BS.readInt line
             return n

parseInts :: Int -> ByteString -> [Int]
parseInts k bs | k <= 0 = []
parseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of
                   Nothing -> []
                   Just (n,bs') -> n : parseInts (k-1) bs'

main = do
  n <- fmap read getLine
  s <- fmap (sum . map fromIntegral . parseInts n) BS.getLine :: IO Int64
  let n' = fromIntegral n
      answer = div (n'*(n'+1)) 2 - s
  print answer

main = do
    let i = fmap (map read . words) getLine :: IO [Integer]
    n <- fmap (!! 0) i
    a <- i
    print $ n * (n + 1) `div` 2 - sum a

import Data.List
import Data.Function

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

getAns :: [Int] -> Int
getAns (n:xs) = sum [1..n] - sum xs

import Data.List
import Data.Int
import Data.Function

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

getAns :: [Int64] -> Int64
getAns (n:xs) = n * (n + 1) `div` 2 - sum xs

{-# LANGUAGE NoMonomorphismRestriction #-}
import Control.Applicative ((<$>))
import Control.Monad
import Text.Printf (printf)
import Data.Maybe (Maybe, fromMaybe)
import Data.List (sort, foldl')
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as BS

solve :: [Int] -> Int
solve s = fst . head . dropWhile (\(x, y) -> x == y) . zip [1..] $ sort s

main :: IO ()
main = do
  n <- getInt
  a <- getInts
  print . solve $ a ++ [n+1]

toNumber = fst . fromMaybe (0, BS.pack "")
getInt = toNumber . BS.readInt <$> BS.getLine
getInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))
countup = foldl' (\x y -> M.insertWith' (+) y 1 x) M.empty
countof m x = M.findWithDefault 0 x m

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

solve i [] = i
solve i (a:as) = if i /= a then i else solve (i+1) as

main = print =<<  solve 1 . sort <$> (map (fst . fromJust . B.readInt) . B.words <$> (getLine >> B.getLine))

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
-- hiding clauses are to allow Data.Foldable's generalizations
import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)
import Control.Monad.ST

import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (ByteString)
import Data.Bits
import Data.Char
import Data.Either
import Data.Foldable
import Data.Function
import Data.IORef
import Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Traversable
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
import System.IO
-- }}}
-- silly utilities {{{
-- stolen from lens:
a & f = f a
a <&> f = fmap f a
infixl 1 &, <&>

fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)
-- }}}
-- input and output {{{
bsGetLine :: IO ByteString
bsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine

inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]

ssUnwords :: [ShowS] -> ShowS
ssUnwords [] = id
ssUnwords (x:xs) = x . (' ':) . ssUnwords xs

ssUnlines :: [ShowS] -> ShowS
ssUnlines [] = id
ssUnlines (x:xs) = x . ('\n':) . ssUnlines xs

showMany :: (Show a) => [a] -> String
showMany xs = ssUnwords (map shows xs) ""
showMatrix :: (Show a) => [[a]] -> String
showMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) ""

printMany :: (Show a) => [a] -> IO ()
printMany xs = putStrLn (showMany xs)
printMatrix :: (Show a) => [[a]] -> IO ()
printMatrix xs = putStr (showMatrix xs)
-- }}}

main :: IO ()
main = do
	n <- inputInteger
	xs <- inputIntegers
	print $ n * (n + 1) `div` 2 - foldl' (+) 0 xs

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

main = do
		n<- read <$> getLine ::IO Int
		k<-sort <$> map read <$> words <$> getLine ::IO [Int]
		let m= take 1 $  dropWhile (\(a,b)-> a==b) $ zip k [1..]
		print $ if m==[] then n else (snd (head m))

import Data.List
import Data.Function

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

getAns :: [Int] -> Int
getAns (n:xs) = n * (n + 1) `div` 2 - sum xs

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
-- hiding clauses are to allow Data.Foldable's generalizations
import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)
import Control.Monad.ST

import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (ByteString)
import Data.Bits
import Data.Char
import Data.Either
import Data.Foldable
import Data.Function
import Data.IORef
import Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Traversable
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
import System.IO
-- }}}
-- silly utilities {{{
-- stolen from lens:
a & f = f a
a <&> f = fmap f a
infixl 1 &, <&>

fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)
-- }}}
-- input and output {{{
bsGetLine :: IO ByteString
bsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine

inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]

ssUnwords :: [ShowS] -> ShowS
ssUnwords [] = id
ssUnwords (x:xs) = x . (' ':) . ssUnwords xs

ssUnlines :: [ShowS] -> ShowS
ssUnlines [] = id
ssUnlines (x:xs) = x . ('\n':) . ssUnlines xs

showMany :: (Show a) => [a] -> String
showMany xs = ssUnwords (map shows xs) ""
showMatrix :: (Show a) => [[a]] -> String
showMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) ""

printMany :: (Show a) => [a] -> IO ()
printMany xs = putStrLn (showMany xs)
printMatrix :: (Show a) => [[a]] -> IO ()
printMatrix xs = putStr (showMatrix xs)
-- }}}

main :: IO ()
main = do
	n <- inputInt
	xs <- inputInts
	print $ n * (n + 1) `div` 2 - foldl' (+) 0 xs

main = do
    let i = fmap (map read . words) getLine :: IO [Int]
    n <- fmap (!! 0) i
    a <- i
    print $ n * (n + 1) `div` 2 - sum a


import qualified Data.Map as M
import Control.Monad
import Data.List
import Data.Monoid
main = do
    name <- getLine
    n <- read `fmap` getLine :: IO Int
    let y = takeWhile (/= '\'')
        add m x ys n = let xy = [x, y ys] in if name `elem` xy then
                M.insertWith (+) (head $ delete name xy) n m
                else M.insertWith (+) x 0 $ M.insertWith (+) (last xy) 0 m
    a <- foldM (\m _ -> do
        l <- getLine
        return $ case words l of
            [x, "posted", _, ys, "wall"] -> add m x ys 15
            [x, "commented", _, ys, "post"] -> add m x ys 10
            [x, "likes", ys, "post"] -> add m x ys 5) M.empty [1..n]
    forM (sortBy (\(a1, a2) (b1, b2) -> compare b2 a2 `mappend` compare a1 b1) $
            M.toList a) (putStrLn . fst)

import Data.List
import Data.Monoid
import Data.Ord

solve myName lines =
		map snd $ sortBy compare costs
	where
		cost "posted" = 15
		cost "commented" = 10
		cost "likes" = 5

		fixName2 = takeWhile (/= '\'')
		parse [name1, action, _, name2', _] = (name1, cost action, fixName2 name2')
		parse [name1, action, name2', _] = (name1, cost action, fixName2 name2')

		lines' = map (parse . words) lines

		names = (nub $ map (\(name1, _, _) -> name1) lines' ++ map (\(_, _, name2) ->  name2) lines')
			\\ [myName]

		lines'' = filter (\(name1, _, name2) -> name1 == myName || name2 == myName) lines'

		items = map (\(name1, cost, _) -> (name1, cost)) lines'' ++
			map (\(_, cost, name2) -> (name2, cost)) lines''

		costs = [(s, name) | name <- names, let s = sum $ [snd i | i <- items, fst i == name]]

		compare =  flip (comparing fst) `mappend` comparing snd

main = do
	myName <- getLine
	_ <- getLine
	actions <- lines `fmap` getContents
	putStrLn $ unlines $ solve myName actions

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

import Data.Char
import Data.List
import qualified Data.Map as M
-- import Data.Map ((!))
import qualified Data.IntMap as IM
-- import Data.IntMap ((!))

import Data.Array
import Data.Function

import Debug.Trace

import Numeric

debug = flip trace
-- debug = const

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

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

double :: IO Double
double = read <$> getLine

doubles :: IO [Double]
doubles = map read . words <$> getLine

sum' = foldl' (+) 0
product' = foldl' (*) 1

fi = fromIntegral

parseLine yourname line
  | ws !! 1 == "posted"     = get (ws !! 0) (name (ws !! 3)) 15
  | ws !! 1 == "commented"  = get (ws !! 0) (name (ws !! 3)) 10
  | ws !! 1 == "likes"      = get (ws !! 0) (name (ws !! 2)) 5
  where ws = words line
        get a b s
          | a == yourname = [(b, s)]
          | b == yourname = [(a, s)]
          | otherwise     = [(a, 0), (b, 0)]
        name s = take (length s - 2) s

main = do
  yourname <- getLine
  nLines <- int
  s <- replicateM nLines getLine
  let scores = concatMap (parseLine yourname) s
      resultMap = foldl' (flip (uncurry (M.insertWith' (+)))) M.empty scores
      resultAss = sortBy c (M.assocs resultMap)
      c (a, b) (c, d)
        | b > d = LT
        | b < d = GT
        | a < c = LT
        | a > c = GT
        | otherwise = EQ
      result = map fst resultAss
  mapM_ putStrLn result

import Control.Applicative
import Control.Monad
import Data.List
import Data.Function
import qualified Data.Map as M
import Data.Maybe

parseLine :: String -> (String, String, Int)
parseLine line = (head sp, init $ init target, score)
  where
    sp = words line
    target = head $ filter (elem '\'') sp
    score = case head (sp !! 1) of
        'p' -> 15
        'c' -> 10
        'l' -> 5

type MyMap = M.Map String Int

solve :: String -> [(String, String, Int)] -> [String]
solve myName pairs = filter (/=myName) . map fst . reverse . sortBy (compare `on` snd) . reverse .  sortBy (compare `on` fst) $ M.assocs mp
  where
    incr :: MyMap -> (String, String, Int) -> MyMap
    incr mp (f,r,s) = mp2
      where
        mp1 = M.insertWith' (+) f (if r == myName then s else 0) mp
        mp2 = M.insertWith' (+) r (if f == myName then s else 0) mp1
    mp = foldl incr M.empty pairs

main = do
    myName <- getLine
    n <- read <$> getLine :: IO Int
    pairs <- replicateM n (parseLine <$> getLine)
    let sorted = solve myName pairs
    mapM_ putStrLn sorted

import Control.Monad
import Data.List

split = rec [] []
  where
    rec res cur [] = reverse $ reverse cur:res
    rec res [] (' ':s) = rec res [] s
    rec res cur (' ':s) = rec (reverse cur:res) [] s
    rec res cur (s:ss) = rec res (s:cur) ss

process = do
  expr <- getLine
  return $ case split $ map (\c -> if c == '\'' then ' ' else c) expr of
    [n1, "posted", "on", n2, "s", "wall"] -> (n1, n2, 15)
    [n1, "commented", "on", n2, "s", "post"] -> (n1, n2, 10)
    [n1, "likes", n2, "s", "post"] -> (n1, n2, 5)

main = do
  you <- getLine
  n <- fmap read getLine :: IO Int
  acts <- replicateM n process :: IO [(String, String, Int)]
  mapM_ (putStrLn . fst) $ sortBy cmp $
    foldr (\(n1, n2, p) ls ->
            if you == n1
            then incr n2 p $ ls
            else if you == n2
                 then incr n1 p $ ls
                 else incr n2 0 $ incr n1 0 $ ls
          ) [] acts
  where
    (n1, p1) `cmp` (n2, p2) = (-p1, n1) `compare` (-p2, n2)
    incr :: String -> Int -> [(String, Int)] -> [(String, Int)]
    incr n p l =
      case lookup n l of
        Nothing -> (n, p) : l
        _ -> map (\(n', p') -> if n == n' then (n, p + p') else (n', p')) l
    swap (a, b) = (b, a)

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

import Data.Char
import Data.List
import qualified Data.Map as M
-- import Data.Map ((!))
import qualified Data.IntMap as IM
-- import Data.IntMap ((!))

import Data.Array
import Data.Function

import Debug.Trace

import Numeric

debug = flip trace
-- debug = const

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

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

double :: IO Double
double = read <$> getLine

doubles :: IO [Double]
doubles = map read . words <$> getLine

sum' = foldl' (+) 0
product' = foldl' (*) 1

fi = fromIntegral

parseLine yourname line
  | ws !! 1 == "posted"     = get (ws !! 0) (name (ws !! 3)) 15
  | ws !! 1 == "commented"  = get (ws !! 0) (name (ws !! 3)) 10
  | ws !! 1 == "likes"      = get (ws !! 0) (name (ws !! 2)) 5
  where ws = words line
        get a b s
          | a == yourname = [(b, s)]
          | b == yourname = [(a, s)]
          | otherwise     = [(a, 0), (b, 0)]
        name s = take (length s - 2) s

main = do
  yourname <- getLine
  nLines <- int
  s <- replicateM nLines getLine
  let scores = concatMap (parseLine yourname) s
      resultMap = foldl' (flip (uncurry (M.insertWith' (+)))) M.empty scores
      resultAss = sortBy c (M.assocs resultMap)
      c (a, b) (c, d)
        | a < c = LT
        | a > c = GT
        | b > d = LT
        | b < d = GT
        | otherwise = EQ
      result = map fst resultAss
  mapM_ putStrLn result


jump x n d m l
        | zone >= n = x
        | x `mod` m > l = x
        | otherwise = jump (x + needs * d) n d m l
        where zone = x `div` m
              end = m * zone + l
              needs = (end - x) `div` d + 1

main = do
    line <- getLine
    let [n, d, m, l] = map read $ words $ line :: [Integer]
    putStrLn $ show $ jump 0 n d m l

import Data.Int

inf :: Int64
inf = 1000000000000000

gap :: Int64 -> Int64 -> Int64 -> Int64 -> Int64
gap d m l cur
	| cur > d * m		= inf
	| (mod cur m) > l	= cur
	| otherwise			= gap d m l (cur + d)

runout :: Int64 -> Int64 -> Int64 -> Int64 -> Int64
runout n d m l = end + d - mod (end + d) d
	where end = (n - 1) * m + l

main :: IO()
main = do
	str <- getLine
	let input = map read (words str)
	let n = input !! 0
	let d = input !! 1
	let m = input !! 2
	let l = input !! 3
	putStrLn (show (min (gap d m l 0) (runout n d m l)))

jump x n d m l
        | zone >= n = x
        | x `mod` m > l = x
        | otherwise = jump (x + needs * d) n d m l
        where zone = x `div` m
              end = m * zone + l
              needs = (end - x) `div` d + 1

main = do
    line <- getLine
    let [n, d, m, l] = map read $ words $ line :: [Int]
    putStrLn $ show $ jump 0 n d m l


import Control.Monad (liftM)
import Data.Array.ST
import Data.Array.Unboxed
import Data.Char (ord)
import Data.List (group)
import Prelude hiding (reads)

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

solve :: Int -> [Int] -> Int
solve k as  =  head $ filter ((== maxStress) . (array !)) [1..k]
  where
    maxStress  =  maximum $ elems array
    array :: UArray Int Int
    array  =  runSTUArray $ do
        array  <-  newArray (1, k) 0
        writeArray array (head as) 1
        update array $ map head $ group as
        return array
    update array (x:y:z:gs)  =  do
        a  <-  readArray array y
        writeArray array y (a + if x == z then 2 else 1)
        update array (y:z:gs)
    update array (x:y:[])  =  do
        a  <-  readArray array y
        writeArray array y (a+1)
    update array _  =  return ()

main :: IO ()
main  =  do
    [n, k]  <-  reads
    as  <-  reads
    print $ solve k as

import Data.Array
import Data.List
import Data.Maybe
import qualified Data.ByteString.Char8 as C

go [x, y] = [(y, 1)]
go (x:t@(y:z:_)) = (y, if x == z then 2 else 1): go t

main = do
  (n:m:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents
  let b@(x:y:_) = map head $ group a
      c = [(-e, i) | (i, e) <- assocs $ accumArray (+) 0 (1,m) $ (x, 1): go b]
  print $ snd $ minimum c

import Data.Array

main = do
    [_, k] <- fmap (map read . words) getLine :: IO [Int]
    a <- fmap (squeeze . map read . words) getLine :: IO [Int]
    let triples = allTriples a
    let saves = accumArray (+) 0 (0, k) $ map (\(x,y,z) -> (y, if x == z then 2 else 1)) triples
    let best = maximum $ elems $ saves
    print $ head $ filter ((== best) . (saves !)) [1..k]

squeeze xs = squeeze' xs []
    where
        squeeze' [] ys = ys
        squeeze' (x:xs) [] = squeeze' xs [x]
        squeeze' (x:xs) (y:ys) = squeeze' xs $ if x == y then y:ys else x:y:ys

allTriples (x:y:xs) = allTriples' (x:y:xs) [(0,x,y)]
    where
        allTriples' [x,y] ts = (x,y,0):ts
        allTriples' (x:y:z:xs) ts = allTriples' (y:z:xs) $ (x,y,z):ts

import Control.Applicative
import Data.Array.Base
import Data.Array.IO (IOUArray)
import Data.List
import Data.Ord
import qualified Data.ByteString.Char8 as B

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

main = do
  [n,k] <- map read.words <$> getLine
  xs <- map head.group.map readInt.B.words <$> B.getLine
  arr <- newArray (0,k) 0 :: IO (IOUArray Int Int)
  let solve (x:y:z:rest)
        | x==z = do
            cntx <- unsafeRead arr x
            unsafeWrite arr x $! cntx-1
            cnty <- unsafeRead arr y
            unsafeWrite arr y $! cnty-1
            solve (y:z:rest)
        | otherwise = do
            cntx <- unsafeRead arr x
            unsafeWrite arr x $! cntx-1
            solve (y:z:rest)
      solve [x,y] = do
        cntx <- unsafeRead arr x
        unsafeWrite arr x $! cntx-1
        cnty <- unsafeRead arr y
        unsafeWrite arr y $! cnty-1
  solve xs
  ans <- zip[1..] <$> mapM (unsafeRead arr) [1..k]
  print.fst $ minimumBy (comparing snd) ans

import Data.Array

compress::(Eq a) => [a] -> [a]
compress (x:y:xs) = if x == y then t else x:t
    where t = compress (y:xs)
compress [x] = [x]
compress [] = []

analysis [_, x] = [(x, 1)]
analysis (x:xs@(y:z:_)) = (y, if x == z then 2 else 1):analysis xs

main = do
    line <- getLine
    let (n:m:_) = map read $ words line :: [Int]
    line <- getLine
    let a = map read $ words line :: [Int]
    let c = assocs $ accumArray (+) 0 (1, m) $ (head a, 1) : (analysis $ compress a)
    putStrLn $ show $ snd $ minimum $ map (\(a, b) -> (-b, a)) c

import Data.Array

compress (x:xs@(y:_)) = (if x == y then [] else [x]) ++ compress xs
compress [x] = [x]
compress [] = []

analysis [_, x] = [(x, 1)]
analysis (x:xs@(y:z:_)) = (y, if x == z then 2 else 1):analysis xs

main = do
    line <- getLine
    let (n:m:_) = map read $ words line :: [Int]
    line <- getLine
    let a = map read $ words line :: [Int]
    let c = assocs $ accumArray (+) 0 (1, m) $ (head a, 1) : (analysis $ compress a)
    putStrLn $ show $ snd $ minimum $ map (\(a, b) -> (-b, a)) c

import Data.List
import Data.Array

analysis :: [Int] -> [(Int, Int)]
analysis [_, x] = [(x, 1)]
analysis (x:xs@(y:z:_)) = (y, if x == z then 2 else 1) : analysis xs

answer :: Int -> [Int] -> Int
answer m a = snd $ minimum $ map (\(a, b) -> (-b, a)) c
  where b = map head $ group a
        c = assocs $ accumArray (+) 0 (1, m) $ (head a, 1) : analysis b

main = do
    line <- getLine
    let (n:m:_) = map read $ words line :: [Int]
    line <- getLine
    let a = map read $ words line :: [Int]
    putStrLn $ show $ answer m a

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

import Data.Array.ST
import Data.STRef
import Control.Monad.ST
import Control.Monad
import Data.List
import Debug.Trace

import Numeric
readInt :: String -> Int
readInt !s = case readDec s of [(n, "")] -> n
-- readInt ('-':s) = case readDec s of [(n, "")] -> -n

preprocess = map head . group

maxN = 500000

ex1 = [1, 1, 2, 3, 2, 3, 3, 1, 1, 3]

solve :: [Int] -> Int
solve [x] = 1
solve xs@(x:_) = runST $ do
  ar <- (newArray (1, maxN) 0)::ST s (STArray s Int Int)
  solve' (x:xs) ar
  res <- newSTRef 1
  forM_ [1..maxN] $ (\i -> do
    a <- readArray ar i
    r <- readSTRef res
    b <- readArray ar r
    when (a > b)
      (writeSTRef res i))
  readSTRef res

modifyArray :: (MArray a e m, Ix i) => a i e -> (e -> e) -> i -> m ()
modifyArray ar f i = do
  x <- readArray ar i
  writeArray ar i (f x)

solve' (a:b:c:rest) ar = do
  if a == c
  then modifyArray ar (+2) b
  else modifyArray ar (+1) b
  solve' (b:c:rest) ar
solve' (a:[b]) ar = do
  modifyArray ar (+1) (b::Int)

main = do
  _ <- getLine
  movies <- getLine >>= (return . map Main.readInt . words)
  print . solve . preprocess $  movies

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

import Data.Array.ST
import Data.STRef
import Control.Monad.ST
import Control.Monad
import Data.List
import Debug.Trace

import Numeric
readInt :: String -> Int
readInt !s = case readDec s of [(n, "")] -> n
-- readInt ('-':s) = case readDec s of [(n, "")] -> -n

preprocess = map head . group

maxN = 500000

ex1 = [1, 1, 2, 3, 2, 3, 3, 1, 1, 3]

solve :: [Int] -> Int
solve [x] = 1
solve !xs@(x:_) = runST $ do
  ar <- (newArray (1, maxN) 0)::ST s (STArray s Int Int)
  solve' (x:xs) ar
  res <- newSTRef 1
  forM_ [1..maxN] $ (\i -> do
    a <- readArray ar i
    r <- readSTRef res
    b <- readArray ar r
    when (a > b)
      (writeSTRef res i))
  readSTRef res

modifyArray :: (MArray a e m, Ix i) => a i e -> (e -> e) -> i -> m ()
modifyArray ar f i = do
  x <- readArray ar i
  writeArray ar i (f x)

solve' (a:b:c:rest) ar = do
  if a == c
  then modifyArray ar (+2) b
  else modifyArray ar (+1) b
  solve' (b:c:rest) ar
solve' (a:[b]) ar = do
  modifyArray ar (+1) (b::Int)

main = do
  _ <- getLine
  movies <- getLine >>= (return . map Main.readInt . words)
  print . solve . preprocess $  movies

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

import Data.Array.ST
import Data.STRef
import Control.Monad.ST
import Control.Monad
import Data.List
import Debug.Trace

preprocess = map head . group

maxN = 500000

ex1 = [1, 1, 2, 3, 2, 3, 3, 1, 1, 3]

solve :: [Int] -> Int
solve [x] = 1
solve xs@(x:_) = runST $ do
  ar <- (newArray (1, maxN) 0)::ST s (STArray s Int Int)
  solve' (x:xs) ar
  res <- newSTRef 1
  forM_ [1..maxN] $ (\i -> do
    a <- readArray ar i
    r <- readSTRef res
    b <- readArray ar r
    when (a > b)
      (writeSTRef res i))
  readSTRef res

modifyArray :: (MArray a e m, Ix i) => a i e -> (e -> e) -> i -> m ()
modifyArray ar f i = do
  x <- readArray ar i
  writeArray ar i (f x)

solve' (a:b:c:rest) ar = do
  if a == c
  then modifyArray ar (+2) b
  else modifyArray ar (+1) b
  solve' (b:c:rest) ar
solve' (a:[b]) ar = do
  modifyArray ar (+1) (b::Int)

main = do
  _ <- getLine
  movies <- getLine >>= (return . map read . words)
  print . solve . preprocess $  movies

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

import Data.Array.ST
import Data.STRef
import Control.Monad.ST
import Control.Monad
import Data.List
import Debug.Trace

import Numeric
readInt :: String -> Int
readInt !s = case readDec s of [(n, "")] -> n
-- readInt ('-':s) = case readDec s of [(n, "")] -> -n

preprocess = map head . group

maxN = 500000

ex1 = [1, 1, 2, 3, 2, 3, 3, 1, 1, 3]

solve :: [Int] -> Int
solve [x] = 1
solve xs@(x:_) = runST $ do
  ar <- (newArray (1, maxN) 0)::ST s (STArray s Int Int)
  solve' (x:xs) ar
  res <- newSTRef 1
  forM_ [1..maxN] $ (\i -> do
    a <- readArray ar i
    r <- readSTRef res
    b <- readArray ar r
    when (a > b)
      (writeSTRef res i))
  readSTRef res

modifyArray :: (MArray a e m, Ix i) => a i e -> (e -> e) -> i -> m ()
modifyArray ar f i = do
  x <- readArray ar i
  writeArray ar i (f x)

solve' (a:b:c:rest) ar = do
  if a == c
  then modifyArray ar (+2) b
  else modifyArray ar (+1) b
  solve' (b:c:rest) ar
solve' (a:[b]) ar = do
  modifyArray ar (+1) (b::Int)

main = do
  _ <- getLine
  movies <- getLine >>= (return . map Main.readInt . words)
  print . solve . preprocess $  movies


{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P
import Data.List as L
import Data.Int (Int64)
--import Data.Char as C
--import Data.IntSet as S

expval :: Double -> Double -> Double -> Double -> Double -> Double -> Double
expval c m p v rounds acc = expc + expm + expp
  where (validc, validm) = (c*rounds*acc > 1e-11, m*rounds*acc > 1e-11)
        expc = (if not validc then 0 else (let r = min c v
                                               (pp, mm) = (if validm then (r/2, r/2) else (r, 0))
                                       in expval (c-v) (m+mm) (p+pp) v (rounds+1) (acc*c)))
        expm = (if not validm then 0 else (let r = min m v
                                               (pp, cc) = (if validc then (r/2, r/2) else (r, 0))
                                       in expval (c+cc) (m-v) (p+pp) v (rounds+1) (acc*m)))
        expp = acc*p*rounds

solve :: IO ()
solve = do
  s <- getLine
  let [c, m, p, v] = map read $ words s :: [Double]
      expected = expval c m p v 1 1.0
    in print expected

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

import Control.Monad ( replicateM_ )
import Data.Int ( Int64 )
import Numeric ( showFFloat )

solve :: IO ()
solve = do
    [c, m, p, v] <- readMany :: IO [Double]
    let ans = go c m p 1 1
        go c m p d pr =
            let tryP = d * pr * p
                tryC | c <= v + eps = go' (m + c / 2) (p + c / 2) (d + 1) (pr * c)
                     | otherwise    = go (c - v) (m + v / 2) (p + v / 2) (d + 1) (pr * c)
                tryM | m <= v + eps = go' (c + m / 2) (p + m / 2) (d + 1) (pr * m)
                     | otherwise    = go (c + v / 2) (m - v) (p + v / 2) (d + 1) (pr * m)
            in tryC + tryM + tryP
        go' c p d pr =
            let tryP = d * pr * p
                tryC | c <= v + eps = (d + 1) * (pr * c)
                     | otherwise    = go' (c - v) (p + v) (d + 1) (pr * c)
            in tryP + tryC
        eps = 1e-8
    putStrLn $ showFFloat (Just 12) ans ""

readMany :: Read a => IO [a]
readMany = map read . words <$> getLine

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


import Control.Monad

solve :: [(Int, Int, Int)] -> [Int]
solve [] = []
solve ((p, _, _) : xs) = let
  go _ [] = []
  go prev ((x, y, z) : zs) = let
    next = head [v | v <- [x, y, z], notElem v [p, prev]]
    in  next : go next zs
  in  p : go p xs

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    _nStr <- getLine
    [a, b, c] <- replicateM 3 $ map read . words <$> getLine
    putStrLn . unwords . map show . solve $ zip3 a b c

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

main :: IO ()
main = getLine >>= flip replicateM_ test . read

test :: IO ()
test = do
  _ <- getLine
  as <- map read . words <$> getLine
  bs <- map read . words <$> getLine
  cs <- map read . words <$> getLine
  let trips = zip3 as bs cs :: [(Integer, Integer, Integer)]
  putStrLn $ unwords . map show $ solve trips

solve :: Eq t => [(t, t, t)] -> [t]
solve [] = []
solve ((end, _, _) : trips) = end : f trips end
  where
    f [] _ = []
    f [(a, b, c)] pre = pure $ head $ filter (`notElem` [pre, end]) [a, b, c]
    f ((a, b, c) : t) pre = let e = head $ filter (/= pre) [a, b, c] in e : f t e


{-# LANGUAGE OverloadedStrings #-}

import Prelude
import Control.Monad
import Data.Functor
import Data.List
import Data.Maybe
import qualified Data.ByteString.Char8 as B8
import Text.Printf

readIntB8 :: B8.ByteString -> Int
readIntB8 = fst . fromJust . B8.readInt

solve :: String -> Int
solve s = sum oddOneGroupLengths
    where
        oddOneGroupLengths = map snd . filter (odd . fst) . zip [1..] $ oneGroupLengths
        oneGroupLengths = reverse . sort . map snd $ oneGroups
        oneGroups = filter fst groups
        groups = map (\s -> (head s == '1', length s)) $ group s

main :: IO ()
main = do
    t <- readIntB8 <$> B8.getLine
    forM_ [1..t] $ \_ -> do
        s <- B8.getLine
        let answer = solve $ B8.unpack s
        printf "%d\n" answer

import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric

fastRead :: String -> Int64
fastRead ('-':s) = case readDec s of [(n, "")] -> -n
fastRead s = case readDec s of [(n, "")] -> n

main = interact solve

type Input = String
type Output = Int

solve :: String -> String
solve input = intercalate "\n" formattedOutputs
    where
        _:xs = words input
        inputs = inputParser xs
        outputs = map solver inputs
        formattedOutputs = map outputFormatter outputs

inputParser :: [String] -> [Input]
inputParser x = x

outputFormatter :: Output -> String
outputFormatter x = show x

solver :: Input -> Output
solver x =
    let
        nums = sortBy (\a b -> compare b a) . map length . filter (('1' ==) . head) $ group x
        folder :: [Int] -> Int
        folder [] = 0
        folder (x:[]) = x
        folder (x:xx:[]) = x
        folder (x:xx:xs) = x + folder xs
    in folder nums

import Data.List

readOneInt :: IO Int
readOneInt = do
    line_ <- getLine
    return $ read line_

strangeSum :: [Int] -> Int
strangeSum [] = 0
strangeSum [a] = a
strangeSum [a,_] = a
strangeSum (a:_:cs) = a + (strangeSum cs)

main :: IO ()
main = do
    t <- readOneInt
    for t where
        for 0 = return ()
        for t' = do
            line_ <- getLine
            -- foldr is more correct, but i am jerk
            let counts = foldl (\acc c ->
                    if null acc
                        then [(c, 1)]
                        else if c == (fst $ head acc)
                            then (c, 1 + (snd $ head acc)) : (tail acc)
                            else (c, 1) : acc) [] line_
            let oneCounts = reverse $ sort $ snd $ unzip $ filter (\(c,_) -> c=='1') counts
            putStrLn $ show $ strangeSum oneCounts
            for (t'-1)

import Control.Monad
import Data.List
import Data.Function
import Data.Ord

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

routine :: IO ()
routine = do
  n <- getLine
  print $ solve n

solve :: String -> Int
solve s = compute grp
  where
    grp = (sortBy (compare `on` Down)  .map length.filter (\(x:_) -> x=='1').group) s

compute :: [Int] -> Int
compute (x:_:xs) = x + compute xs
compute [x] = x
compute [] = 0

import Data.List
--import Data.Sort
getBlocks :: String -> [Int]
getBlocks x = reverse $ getBlocks' 0 [] x
getBlocks' :: Int -> [Int] -> String -> [Int]
getBlocks' cur a "" = if cur > 0 then (cur : a) else a
getBlocks' cur a ('0' : xs) = if cur > 0 then getBlocks' 0 (cur : a) xs else getBlocks' cur a xs
getBlocks' cur a ('1' : xs) = getBlocks' (cur + 1) a xs
solveTestCase :: String -> Int
solveTestCase s = let decreasingBlocks = (reverse . sort . getBlocks) s in
                  let numBlocks = length decreasingBlocks in
                  let indices = [0 .. numBlocks - 1] in
                  let valuesAtEvenIndices = map fst $ filter (even . snd) $ zip decreasingBlocks indices in
                  sum valuesAtEvenIndices
doCasesIO :: Int -> IO ()
doCasesIO 0 = return ()
doCasesIO t = do
              s <- getLine
              (putStrLn . show . solveTestCase) s
              doCasesIO (t - 1)
main :: IO ()
main = do
         t <- readLn :: IO Int
         doCasesIO t


import Control.Monad (liftM, replicateM)
import Data.Array ((!), accumArray, listArray, elems)
import Data.Char (ord)
import Data.List (intercalate)

solve :: [(Int, Int)] -> [Int]
solve ms  =  solve' 0 0 0 ms
  where
    solve' t 0 maxQ []  =  [t, maxQ]
    solve' t q maxQ []  =  solve' (t+q) 0 (max maxQ q) []
    solve' t q maxQ ((ti, ci) : ms)
      | q <= (ti - t)  =  solve' ti ci (max maxQ q) ms
      | otherwise  =  solve' ti (q - (ti - t) + ci) (max maxQ q) ms

main :: IO ()
main  =  do
    n  <-  readLn
    ms  <-  replicateM n readPair
    prints $ solve ms

  where

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

    readPair :: Num a => IO (a, a)
    readPair  =  do
        [a, b]  <-  reads
        return (a, b)

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

get::String->Int
get x=read x

gao::(Int,Int,Int)->(Int,Int)->(Int,Int,Int)
gao (nowmaxPeople,nowTime,nowres) (t,k) = ( max nowmaxPeople nw,t,nw )
	where nw=( max (nowres-(t-nowTime)) 0 )+k

myfst::(Int,Int,Int)->Int
myfst (x,_,_)=x

mysnd::(Int,Int,Int)->Int
mysnd (_,x,_)=x

mythd::(Int,Int,Int)->Int
mythd (_,_,x)=x

work::[(Int,Int)]->(Int,Int,Int)->String
work [] x = show ( mysnd x + mythd x ) ++ " " ++ show ( myfst x )
work (a:as) x = work as (gao x a)

get2::[Int]->[(Int,Int)]
get2 xs = zip ( map (xs!!) [1,3..2*n] ) ( map (xs!!) [2,4..2*n] )
	where n=xs!!0

main::IO()
main = do
	input<-getContents
	let
		number=map read (words input)::[Int]
	putStr $ work ( get2 number ) (0,0,0)

import Control.Applicative
import Data.Maybe
import qualified Data.ByteString.Char8 as C

pairs :: [a] -> [(a, a)]
pairs (x:y:z) = (x, y): pairs z
pairs _ = []

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

main :: IO ()
main = do
  a <- pairs . tail . map readInt . C.words <$> C.getContents
  let (t, c, maxc) = foldl gao (0, 0, 0) a
  print $ t + c
  print $ maxc
  where
    gao (t, c, maxc) (tt, cc) = let c' = cc + max 0 (c - (tt - t)) in (tt, c', max maxc $ c')

toList::[Int]->[(Int,Int)]
toList [] = []
toList (a:b:c) = (a,b):(toList c)

getAns::[(Int,Int)]->(Int,Int)
getAns lst =
 let
  getAns'::[(Int,Int)]->Int->Int->Int->(Int,Int)
  getAns' [] unfinishedTask currentTime maxTask = (currentTime+unfinishedTask,maxTask)
  getAns' ((t,c):xs) unfinishedTask currentTime maxTask =
   if t==currentTime
    then getAns' xs (unfinishedTask+c) currentTime (max maxTask (unfinishedTask+c))
    else getAns' ((t,c):xs) (max (unfinishedTask-t+currentTime) 0) t maxTask
 in getAns' lst 0 0 0

main::IO()
main =
 do
 input <- getContents
 let
  numbers = map read (words input)::[Int]
  ans = getAns $ toList $ tail numbers
 putStr $ show $ fst ans
 putStr " "
 putStr $ show $ snd ans
 putStr "\n"

toList::[Int]->[(Int,Int)]
toList [] = []
toList (a:b:c) = (a,b):(toList c)

getAns::[(Int,Int)]->(Int,Int)
getAns lst =
 let
  getAns'::[(Int,Int)]->Int->Int->Int->(Int,Int)
  getAns' [] unfinishedTask currentTime maxTask = (currentTime+unfinishedTask,maxTask)
  getAns' ((t,c):xs) unfinishedTask currentTime maxTask =
   if t==currentTime
    then getAns' xs (unfinishedTask+c) currentTime (max maxTask ((max (unfinishedTask-1) 0)+c))
    else getAns' ((t,c):xs) (max (unfinishedTask-t+currentTime) 0) t maxTask
 in getAns' lst 0 0 0

main::IO()
main =
 do
 input <- getContents
 let
  numbers = map read (words input)::[Int]
  ans = getAns $ toList $ tail numbers
 putStr $ show $ fst ans
 putStr " "
 putStr $ show $ snd ans
 putStr "\n"


{-# LANGUAGE DeriveFunctor     #-}
{-# LANGUAGE FlexibleContexts  #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs             #-}
{-# LANGUAGE LambdaCase        #-}
{-# LANGUAGE RecordWildCards   #-}
{-# LANGUAGE TupleSections     #-}
{-# LANGUAGE TypeApplications  #-}

import           Control.Applicative        (liftA2)
import           Control.Arrow
import           Control.Monad.State
import           Data.Array.Unboxed
import           Data.Bits
import           Data.Bool
import           Data.ByteString.Lazy.Char8 (ByteString)
import qualified Data.ByteString.Lazy.Char8 as C
import           Data.Char
import qualified Data.Foldable              as F
import           Data.Function
import           Data.Graph
import           Data.List
import           Data.Map                   (Map, (!))
import qualified Data.Map                   as M
import           Data.Maybe
import           Data.Ord
import           Data.Ratio
import           Data.Sequence              (Seq, ViewL (..), ViewR (..), (<|),
                                             (|>))
import qualified Data.Sequence              as Seq
import           Data.Set                   (Set)
import qualified Data.Set                   as S
import           Data.Tree
import           Text.Printf

-- import Text.Parsec
-- import Text.Parsec.Expr
-- import Text.Parsec.Language (emptyDef)
-- import Text.Parsec.String
-- import qualified Text.Parsec.Token as T

infixl 0 >$>
(>$>) = flip ($)

data TC = TC { slots :: [[Choice]], banned :: [[Int]] }

tc = do
  n <- int
  TC <$> (n >< (zipWith Choice [1 ..] <$> numberOf int)) <*> numberOf (n >< int)

main = C.interact $
  runScanner tc >>> solve >>> map (show >>> C.pack) >>> C.unwords

solve :: TC -> [Int]
solve TC{..} = choices . fromJust $ find ((`S.notMember` bannedSet) . choices) bs
  where
    bannedSet = S.fromList banned
    revSlots = map reverse slots
    bs = builds revSlots

-- Sorted in *decreasing* order.

data Choice = Choice { index :: !Int, value :: !Int }

data Build = Build { strength :: !Int, choices :: [Int] }
  deriving (Eq, Show, Ord)

singletonBuild :: Choice -> Build
singletonBuild (Choice i v) = Build v [i]

mkBuild xs = Build (sum xs) xs

-- Pre: all input lists are sorted descending.
-- All possible builds, sorted in descending order of strength.
builds :: [[Choice]] -> [Build]
builds []     = []
builds (i:is) = chooseFrom i (builds is)

chooseFrom :: [Choice] -> [Build] -> [Build]
chooseFrom [] _  = []
chooseFrom xs [] = map singletonBuild xs
chooseFrom (x:xs) (b:bs) = addToBuild x b : mergeBuilds (map (addToBuild x) bs) (chooseFrom xs (b:bs))

addToBuild :: Choice -> Build -> Build
addToBuild (Choice i v) (Build s xs) = Build (v+s) (i:xs)

mergeBuilds xs [] = xs
mergeBuilds [] ys = ys
mergeBuilds (x:xs) (y:ys) = case compare (strength x) (strength y) of
  GT -> x : mergeBuilds xs (y:ys)
  _  -> y : mergeBuilds (x:xs) ys

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

type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = head <$> get

str :: Scanner C.ByteString
str = get >>= \case { s:ss -> put ss >> return s }

int :: Scanner Int
int = (fst . fromJust . C.readInt) <$> str

integer :: Scanner Integer
integer = (read . C.unpack) <$> str

double :: Scanner Double
double = (read . C.unpack) <$> str

decimal :: Int -> Scanner Int
decimal p = (round . ((10^p)*)) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case { [] -> return []; _ -> (:) <$> s <*> many s }

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  case p t of
    True  -> return []
    False -> (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2..4]

pair :: Scanner a -> Scanner b -> Scanner (a,b)
pair = liftA2 (,)

import Control.Monad
import Data.Array
import Data.Int
import Data.List
import Data.Maybe
import Data.Ord
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as C

solve :: IO ()
solve = do
    [n] <- readInts
    cas <- replicateM n $ (\(x:cs) -> listArray (1, x) cs) <$> readInts
    [m] <- readInts
    bs <- S.fromList <$> replicateM m readInts
    let next = init . go where
            go [] = [[]]
            go (1:is) = map (1:) $ go is
            go ~(i:is) = (i - 1 : is) : map (i:) (go is)
        candidates = filter (`S.notMember` bs) $ [snd $ bounds ca | ca <- cas] : concatMap next (S.elems bs)
        score is = sum $ [fromIntegral $ ca!i | (i, ca) <- zip is cas] :: Int64
    putStrLn $ unwords $ map show $ maximumBy (comparing score) candidates

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

main :: IO ()
main = solve

import Control.Monad
import Data.Array.Unboxed
import Data.Int
import Data.List
import Data.Maybe
import Data.Ord
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as C

solve :: IO ()
solve = do
    [n] <- readInts
    cas <- replicateM n $ (\(x:cs) -> listArray (1, x) cs :: UArray Int Int) <$> readInts
    [m] <- readInts
    bs <- S.fromList <$> replicateM m readInts
    let next = init . go where
            go [] = [[]]
            go (1:is) = map (1:) $ go is
            go (i:is) = (i - 1 : is) : map (i:) (go is)
        candidates = filter (`S.notMember` bs) $ map (snd . bounds) cas : concatMap next (S.elems bs)
        score is = sum $ [fromIntegral $ ca!i | (i, ca) <- zip is cas] :: Int64
    putStrLn $ unwords $ map show $ maximumBy (comparing score) candidates

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

main :: IO ()
main = solve

import Control.Monad
import Data.List
import Data.Maybe
import Data.Ord
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as C

solve :: IO ()
solve = do
    [n] <- readInts
    cs <- replicateM n $ reverse . zip [1..] . tail <$> readInts
    [m] <- readInts
    bs <- S.fromList <$> replicateM m readInts
    let pop [x] = [x]
        pop ~(_:xs) = xs
        diff [x] = 10^9
        diff ~(x:x':_) = snd x - snd x'
        sub [] [] = [[]]
        sub ~(x:xs) ~(y:ys) = (y:xs) : map (x:) (sub xs ys)
        go cs
            | sig `S.notMember` bs = sig
            | otherwise = go cs'
          where
            sig = map (fst . head) cs
            diffs = map diff cs
            newcs = init $ sub cs $ map pop cs
            cs' = snd $ minimumBy (comparing fst) $ zip diffs newcs
    putStrLn $ unwords $ map show $ go cs

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

main :: IO ()
main = solve