{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification,
             RankNTypes, FlexibleContexts, DeriveFunctor #-}

import Control.Monad
import Control.Applicative
--import Control.Lens
--import Control.Zipper
import Control.Arrow
import qualified Data.Map as M
import qualified Data.Set as S
import Data.List
--import Control.Comonad
import Data.Monoid
--import Data.Functor.Foldable
--import Test.QuickCheck
import Data.Tree
--import Data.Machine
--import Data.Traversable
--import Data.Distributive
--import Linear
import Control.Monad.Cont

data Ops = Take Integer | Carrier Integer deriving (Eq, Ord, Show, Read)

main = do
  [n, x] <- fmap (map read . words) getLine
  inp <- forM [1..n] $ \_ -> do
         let g ('+':' ':r) = Carrier (read r)
             g ('-':' ':r) = Take (read r)
         fmap g getLine

  let (a, b) = solve inp x
  putStrLn $ show a ++ " " ++ show b

solve :: [Ops] -> Integer -> (Integer, Integer)
solve ops x = (numLeft, numDistressed)
    where
      (numLeft, numDistressed) = foldl f (x, 0) ops
      f (n, d) (Carrier c) = (n+c, d)
      f (n, d) (Take m) | n >= m = (n-m, d)
                        | otherwise = (n, d+1)

inp = [Carrier 5,
       Take 10,
       Take 20,
       Carrier 40,
       Take 20]

getInput :: Integer -> IO [(String, Integer)]
getInput 0 = return []
getInput n = do
                inpStr <- getLine
                let w = words inpStr
                let vals = (w !! 0, read $ w !! 1 :: Integer)
                rest <- getInput (n - 1)
                return (vals : rest)

process' :: Integer -> [(String, Integer)] -> (Integer, Integer)
process' n [] = (n, 0)
process' n (("+",x):xs) = process' (n + x) xs
process' n (("-",x):xs) | n >= x = process' (n - x) xs
                        | n < x = (a, b + 1)
                        where (a, b) = process' n xs

main :: IO ()
main = do
        inpStr <- getLine
        let w = words inpStr
        let (n, x) = (read $ w !! 0 :: Integer, read $ w !! 1 :: Integer)
        allInp <- getInput n
        let (a, b) = process' x allInp
        putStrLn $ show a ++ " " ++ show b

getInput :: Integer -> IO [(String, Integer)]
getInput 0 = return []
getInput n = do
                inpStr <- getLine
                let w = words inpStr
                let vals = (w !! 0, read $ w !! 1 :: Integer)
                rest <- getInput (n - 1)
                return (vals : rest)

process :: Integer -> [(String, Integer)] -> (Integer, Integer)
process n [] = (n, 0)
process n ((op,x):xs) = case op of
                            "+" -> process (n + x) xs
                            "-" -> process1 n x xs
                                where process1 n x xs | n >= x = process (n - x) xs
                                                      | n < x = (a, b + 1)
                                                           where (a, b) = process n xs

main :: IO ()
main = do
        inpStr <- getLine
        let w = words inpStr
        let (n, x) = (read $ w !! 0 :: Integer, read $ w !! 1 :: Integer)
        allInp <- getInput n
        let (a, b) = process x allInp
        putStrLn $ show a ++ " " ++ show b

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

main = do
  [n, x] <- map read . words <$> getLine
  [ss, ds] <- transpose . map words <$> replicateM n getLine
  let ans = solve (fromIntegral x) 0 ss (map read ds)
  putStrLn $ show (ans !! 0) ++ " " ++ show (ans !! 1)

solve :: Integer -> Integer -> [String] -> [Integer] -> [Integer]
solve x y [] [] = [x, y]
solve x y (s:ss) (d:ds)
    | s == "+" = solve (x + d) y ss ds
    | s == "-" && d <= x = solve (x - d) y ss ds
    | otherwise = solve x (y + 1) ss ds

main = do
    n:[x] <- return . map read . words =<< getLine
    let dataread = do
	    flag:[amountstr] <- return . words =<< getLine
	    return (flag=="+", read amountstr)
	dataread::IO (Bool, Integer)
    (i,d) <- return . (foldl f (x::Integer,0)) =<< sequence (take (fromIntegral n) $ repeat dataread)
    putStr $ (show i)++" "++show d
	where
	    f (ice, distress) (f,amo) =
		case f	of
		True	-> (ice+amo, distress)
		False	-> if ice >= amo
			    then (ice-amo, distress)
			    else (ice, succ distress)

solve :: [String] -> String
solve (l:ls) = case foldl parser (m, 0) ls of (x, y) -> (show x) ++ " " ++ (show y)
    where [_,m] = map read (words l)
parser :: (Integer, Integer) -> String -> (Integer, Integer)
parser (i,d) (c:' ':str) =
    let k = read str in case c of
    '+' -> (i + k, d)
    '-' -> if k > i then (i, d + 1) else (i - k, d)
main = putStrLn.solve.lines =<< getContents

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

process::(Integer,Integer)->Integer->(Integer,Integer)
process (a,c) d | d>0 = (a+d,c)
                | d<0 && a+d<0= (a,c+1)
		| otherwise = (a+d,c)

tr '+' = ' '
tr x = x

main = do
		[n,x]<- map read <$> words <$> getLine::IO [Integer]
		y1<-map (\z-> [head z]++ (drop 2 z)) <$>lines <$> getContents
		let y2= map (map tr) y1
		let y= map read y2 ::[Integer]
                let (a,c) = foldl process (x,0) y
		putStr  $ show a
		putStr " "
		putStrLn $ show c

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

runCommand :: (String, Integer) -> State (Integer, Integer) ()
runCommand ("+", n) = modify $ first (+n)
runCommand ("-", n) = do
  x <- fst <$> get
  if x >= n
    then modify $ first (+ (-n))
    else modify $ second (+1)

getCommand :: IO (String, Integer)
getCommand = do
  [a, b] <- words <$> getLine
  return $ (a, read b)

main = do
  [n, x] <- map read . words <$> getLine
  commands <- replicateM n getCommand
  let (a, b) = execState (mapM_ runCommand commands) (fromIntegral x, 0)
  putStrLn $ show a ++ " " ++ show b

process :: Integer -> [(Char, Integer)] -> (Integer, Integer)
process x fs = foldl f (x,0) fs
    where
        f (x,y) (c,d)
            | c == '-' = if x < d then (x,y+1) else (x-d,y)
            | otherwise = (x+d,y)

readInt :: String -> Integer
readInt = read

processLine :: String -> (Char, Integer)
processLine line = (char,d)
    where
        [char:_,dStr] = words line
        d = read dStr

main :: IO ()
main = do
    line <- getLine
    let [n,x] = map readInt (words line)
    fs <- fmap (map processLine.lines) getContents
    let (x',y') = process x fs
    putStrLn $ show x' ++ " " ++ show y'

myShow :: (Integer, Integer) -> String
myShow (a, b) = show a ++ " " ++ show b

simulate :: [[String]] -> Integer -> Integer -> (Integer, Integer)
simulate [] x k = (x, k)
simulate (["+", am]:rest) x k = simulate rest (x + read am) k
simulate (["-", am]:rest) x k
  | read am <= x = simulate rest (x - read am) k
  | otherwise    = simulate rest x (k + 1)

solve :: String -> String
solve str =
  let (h:b)  = lines str
      [n, x] = map read . words $ h
      queue  = map words $ take (fromIntegral n) b
  in myShow $ simulate queue x 0

main :: IO()
main = interact solve

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

solve :: [String] -> [Integer]
solve (xs:cs) = solve' (read xs) 0 cs

solve' :: Integer -> Integer -> [String] -> [Integer]
solve' x c [] = [x, c]
solve' x c (o:ds:s) | o == "+" = solve' (x + read ds) c s
                    | otherwise = let d = read ds
                                  in if x >= d
                                     then solve' (x - d) c s
                                     else solve' x (c + 1) s

{-# 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, x] <- fmap (map read . words) getLine
  ls <- replicateM n $ (\[a, b] -> (head a, read b)) . words <$> getLine

  let
    (c, s) = f (0, fromIntegral x) ls :: (Int, Int64)
      where
        f (c, s) [] = (c, s)
        f (c, s) (('+', d):xs) = f (c, s+d) xs
        f (c, s) (('-', d):xs)
          | s >= d = f (c, s-d) xs
          | otherwise = f (c+1, s) xs

  putStrLn $ show s ++ " " ++ show c

{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification,
             RankNTypes, FlexibleContexts, DeriveFunctor #-}

import Control.Monad
import Control.Applicative
--import Control.Lens
--import Control.Zipper
import Control.Arrow
import qualified Data.Map as M
import qualified Data.Set as S
import Data.List
--import Control.Comonad
import Data.Monoid
--import Data.Functor.Foldable
--import Test.QuickCheck
import Data.Tree
--import Data.Machine
--import Data.Traversable
--import Data.Distributive
--import Linear
import Control.Monad.Cont

data Ops = Take Integer | Carrier Integer deriving (Eq, Ord, Show, Read)

main = do
  [n, x] <- fmap (map read . words) getLine
  inp <- forM [1..n] $ \_ -> do
         let g ('+':' ':r) = Carrier (read r)
             g ('-':' ':r) = Take (read r)
         fmap g getLine

  let (a, b) = solve inp x
  putStrLn $ show a ++ " " ++ show b

solve :: [Ops] -> Integer -> (Integer, Integer)
solve ops x = res
    where
      res = foldl f (x, 0) ops
          where
            f (x, y) (Carrier d) = (x + d, y)
            f (x, y) (Take d) | x < d = (x, y+1)
                         | otherwise = (x - d, y)

{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE OverlappingInstances #-}

module Main where

import           Control.Applicative
import           Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as B
import           Data.Function
import           Data.List
import           Data.Maybe
import           System.Environment
import           System.IO

type BString = B.ByteString
type Result = [Integer]

solve :: Int -> [Int] -> Result
solve x  = foldl' deal_with [fromIntegral x, 0] . map fromIntegral
    where deal_with [left, distressed] num
            | left + num >= 0 = [left + num, distressed]
            | otherwise       = [left, distressed + 1]

process :: State Reader Result
process = do
    [n, x] <- parse
    ds <- replicateM n $ scan . B.filter (/=' ') <$> parse
    return $ solve x ds

main :: IO ()
main = do
    args <- getArgs
    reader <- if not (null args) && head args == "MINE"
              then B.lines <$> (openFile "input.txt" ReadMode >>= B.hGetContents)
              else B.lines <$> B.getContents
    say $ evalState process reader

say :: Display a => a -> IO ()
say = putStrLn . display

toNum :: Num a => Bool -> a
toNum False = 0
toNum True  = 1

type Reader = [BString]

class Display a => EIO a where
    parse :: State Reader a
    parse = state $ \(line:rest) -> (scan line, rest)

instance EIO Int where

instance EIO [Int] where
    parse = state $ \(line:rest) -> (map scan . B.words $ line, rest)

instance EIO BString where

class (Read a, Show a) => Display a where
    display :: a -> String
    scan :: BString -> a
    display = show
    scan = read . B.unpack

instance Display String where
    display = id

instance Display BString where
    display = B.unpack
    scan = id

instance Display [a] => Display [[a]] where
    display = unlines . map display

instance Display a => Display [a] where
    display = unwords . map display

instance Display Int where
    scan = fst . fromJust . B.readInt

instance Display Integer

instance Display Double

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Function
import Data.Ord
import Data.Bits
import Data.Monoid
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main= someFunc
rIn x= fst $ fromJust  $ C.readInteger x
someFunc::IO()
someFunc = C.getLine >>= \ns-> let [n,x] =map rIn $ C.words ns in solve.((:) x)=<<forM [1..n] (\i->rIn.C.filter (/=' ')<$>C.getLine)
solve (x:xs) =(\(t1,t2)->putStr (show t1 ++" "++show t2)) $ foldl (\(b1,b2) a->if b1+a<0 then (b1,b2+1) else (b1+a,b2)) (x,0) xs

module Main where

import Control.Applicative
import Control.Monad

main :: IO ()
main =
    (map read . words <$> getLine :: IO [Integer]) >>=
        \[n, x] -> step n x 0

step :: Integer -> Integer -> Integer -> IO ()
step 0 x d =
    putStrLn (show x ++ " " ++ show d)

step n x d =
    words <$> getLine >>=
        \[c, s] ->
            let
                r = (read s :: Integer)
            in
                if c == "+" then
                    step (n - 1) (x + r) d

                else if x >= r then
                    step (n - 1) (x - r) d

                else
                    step (n - 1) x (d + 1)

import Data.List
import Control.Monad

-- solve 5 7 [('+', 5), ('-', 10), ('-', 20), ('+', 40), ('-', 20)]
-- solve 5 17 [('-', 16), ('-', 2), ('-', 98), ('+', 100), ('-', 98)]

solve :: Integer -> [(Char, Integer)] -> (Integer, Integer)
solve x ops = foldl' updateState (x, 0) ops
    where updateState (total, sads) ('+', amount) = (total + amount, sads)
          updateState (total, sads) ('-', amount) =
              if amount > total
              then (total, sads + 1)
              else (total - amount, sads)

parseOps :: String -> (Char, Integer)
parseOps s = let [[op], amount] = words s
              in (op, read amount)

parseNx :: String -> (Int, Integer)
parseNx s = let [n, x] = words s
            in (read n, read x)

main = do (n, x) <- fmap parseNx getLine
          ops <- replicateM n (fmap parseOps getLine)
          let (total, sads) = solve x ops
          putStr $ show total
          putStr " "
          putStrLn $ show sads

import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric
-- import Debug.Trace(trace)

trace x y = y

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

main = interact solve

solve input = (show final_val)++" "++(show distress)
    where
    n_s:x_s:as_w = words input
    n::Int64
    n = read n_s
    x::Int64
    x = read x_s

    entries = parseInput as_w

    (distress, final_val) = foldl' foldOp (0,x) entries

parseInput::[String] -> [(String, Int64)]
parseInput [] = []
parseInput (x:y:xs) = trace ("x is "++x++" Y is "++y) (x, read y):parseInput(xs)

foldOp::(Int64, Int64) -> (String, Int64) -> (Int64, Int64)
foldOp (distress, current) (op, ice_cream)
    | op == "+" = (distress, current+ice_cream)
    | current >= ice_cream = (distress, current-ice_cream)
    | otherwise = (distress+1, current)

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

process::Integer->Integer->[[String]]->String
process x n [] = (show x) ++ " " ++ (show n)
process x n ((a:b:[]):cs) | a=="+" = process (x+bb) n cs
                          | bb<= x = process (x-bb) n cs
                          | otherwise = process x (n+1) cs
      where bb = read b ::Integer

main = do
   [a,b]<-map read <$> words <$> getLine ::IO [Integer]
   d<- map words <$> lines <$> getContents ::IO [[String]]
   putStrLn $ process b 0 d

main = do
  [n,x] <- map read . words <$> getLine
  (x',d) <- foldl process (x,0) . map words . lines <$> getContents
  putStrLn $ show x' ++ " " ++ show d
process (x,d) ["+",y] = (x + read y,d)
process (x,d) ["-",y] | x >= read y = (x - read y,d)
                      | otherwise = (x,d+1)

{-# 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, x] <- fmap (map read . words) getLine
  ls <- replicateM n $ (\[a, b] -> (head a, read b)) . words <$> getLine

  let
    (c, s) = f (0, x) ls
      where
        f (c, s) [] = (c, s)
        f (c, s) (('+', d):xs) = f (c, s+d) xs
        f (c, s) (('-', d):xs)
          | s >= d = f (c, s-d) xs
          | otherwise = f (c+1, s) xs

  putStrLn $ show s ++ " " ++ show c

{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification,
             RankNTypes, FlexibleContexts, DeriveFunctor #-}

import Control.Monad
import Control.Applicative
--import Control.Lens
--import Control.Zipper
import Control.Arrow
import qualified Data.Map as M
import qualified Data.Set as S
import Data.List
--import Control.Comonad
import Data.Monoid
--import Data.Functor.Foldable
--import Test.QuickCheck
import Data.Tree
--import Data.Machine
--import Data.Traversable
--import Data.Distributive
--import Linear
import Control.Monad.Cont

data Ops = Take Int | Carrier Int deriving (Eq, Ord, Show, Read)

main = do
  [n, x] <- fmap (map read . words) getLine
  inp <- forM [1..n] $ \_ -> do
         let g ('+':' ':r) = Carrier (read r)
             g ('-':' ':r) = Take (read r)
         fmap g getLine

  let (a, b) = solve inp x
  putStrLn $ show a ++ " " ++ show b

solve :: [Ops] -> Int -> (Int, Int)
solve ops x = res
    where
      res = foldl f (x, 0) ops
          where
            f (x, y) (Carrier d) = (x + d, y)
            f (x, y) (Take d) | x < d = (x, y+1)
                         | otherwise = (x - d, y)

{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE OverlappingInstances #-}

module Main where

import           Control.Applicative
import           Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as B
import           Data.Function
import           Data.List
import           Data.Maybe
import           System.Environment
import           System.IO

type BString = B.ByteString
type Result = [Int]

solve :: Int -> [Int] -> Result
solve x  = foldl' deal_with [x, 0]
    where deal_with [left, distressed] num
            | left + num >= 0 = [left + num, distressed]
            | otherwise       = [left, distressed + 1]

process :: State Reader Result
process = do
    [n, x] <- parse
    ds <- replicateM n $ scan . B.filter (/=' ') <$> parse
    return $ solve x ds

main :: IO ()
main = do
    args <- getArgs
    reader <- if not (null args) && head args == "MINE"
              then B.lines <$> (openFile "input.txt" ReadMode >>= B.hGetContents)
              else B.lines <$> B.getContents
    say $ evalState process reader

say :: Display a => a -> IO ()
say = putStrLn . display

toNum :: Num a => Bool -> a
toNum False = 0
toNum True  = 1

type Reader = [BString]

class Display a => EIO a where
    parse :: State Reader a
    parse = state $ \(line:rest) -> (scan line, rest)

instance EIO Int where

instance EIO [Int] where
    parse = state $ \(line:rest) -> (map scan . B.words $ line, rest)

instance EIO BString where

class (Read a, Show a) => Display a where
    display :: a -> String
    scan :: BString -> a
    display = show
    scan = read . B.unpack

instance Display String where
    display = id

instance Display BString where
    display = B.unpack
    scan = id

instance Display [a] => Display [[a]] where
    display = unlines . map display

instance Display a => Display [a] where
    display = unwords . map display

instance Display Int where
    scan = fst . fromJust . B.readInt

instance Display Double

module Main where

import Control.Applicative
import Control.Monad

main :: IO ()
main =
    (map read . words <$> getLine :: IO [Int]) >>=
        \[n, x] -> step n x 0

step :: Int -> Int -> Int -> IO ()
step 0 x d =
    putStrLn (show x ++ " " ++ show d)

step n x d =
    words <$> getLine >>=
        \[c, s] ->
            let
                r = (read s :: Int)
            in
                if c == "+" then
                    step (n - 1) (x + r) d

                else if x >= r then
                    step (n - 1) (x - r) d

                else
                    step (n - 1) x (d + 1)

import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric
-- import Debug.Trace(trace)

trace x y = y

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

main = interact solve

solve input = (show final_val)++" "++(show distress)
    where
    n_s:x_s:as_w = words input
    n::Int
    n = read n_s
    x::Int
    x = read x_s

    entries = parseInput as_w

    (distress, final_val) = foldl' foldOp (0,x) entries

parseInput::[String] -> [(String, Int)]
parseInput [] = []
parseInput (x:y:xs) = trace ("x is "++x++" Y is "++y) (x, read y):parseInput(xs)

foldOp::(Int, Int) -> (String, Int) -> (Int, Int)
foldOp (distress, current) (op, ice_cream)
    | op == "+" = (distress, current+ice_cream)
    | current >= ice_cream = (distress, current-ice_cream)
    | otherwise = (distress+1, current)

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

process::Int->Int->[[String]]->String
process x n [] = (show x) ++ " " ++ (show n)
process x n ((a:b:[]):cs) | a=="+" = process (x+bb) n cs
                          | bb<= x = process (x-bb) n cs
                          | otherwise = process x (n+1) cs
      where bb = read b ::Int

main = do
   [a,b]<-map read <$> words <$> getLine ::IO [Int]
   d<- map words <$> lines <$> getContents ::IO [[String]]
   putStrLn $ process b 0 d

main = do
    n:[x] <- return . map read . words =<< getLine
    let dataread = do
	    flag:[amountstr] <- return . words =<< getLine
	    return (flag=="+", read amountstr)
	dataread::IO (Bool, Int)
    (i,d) <- return . (foldl f (x,0)) =<< sequence (take n $ repeat dataread)
    putStr $ (show i)++" "++show d
	where
	    f (ice, distress) (f,amo) =
		case f	of
		True	-> (ice+amo, distress)
		False	-> if ice >= amo
			    then (ice-amo, distress)
			    else (ice, succ distress)

solve :: [String] -> String
solve (l:ls) = case foldl parser (m, 0) ls of (x, y) -> (show x) ++ " " ++ (show y)
    where [_,m] = map read (words l)
parser :: (Int, Int) -> String -> (Int, Int)
parser (i,d) (c:' ':str) =
    let k = read str in case c of
    '+' -> (i + k, d)
    '-' -> if k > i then (i, d + 1) else (i - k, d)
main = putStrLn.solve.lines =<< getContents

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

process (a,c) d | d>0 = (a+d,c)
                | d<0 && a+d<0= (a,c+1)
		| otherwise = (a+d,c)

tr '+' = ' '
tr x = x

main = do
		[n,x]<- map read <$> words <$> getLine::IO [Int]
		y1<-map (\z-> [head z]++ (drop 2 z)) <$>lines <$> getContents
		let y2= map (map tr) y1
		let y= map read y2 ::[Int]
                let (a,c) = foldl process (x,0) y
		putStr  $ show a
		putStr " "
		putStrLn $ show c

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

runCommand :: (String, Int) -> State (Int, Int) ()
runCommand ("+", n) = modify $ first (+n)
runCommand ("-", n) = do
  x <- fst <$> get
  if x >= n
    then modify $ first (+ (-n))
    else modify $ second (+1)

getCommand :: IO (String, Int)
getCommand = do
  [a, b] <- words <$> getLine
  return $ (a, read b)

main = do
  [n, x] <- map read . words <$> getLine
  commands <- replicateM n getCommand
  let (a, b) = execState (mapM_ runCommand commands) (x, 0)
  putStrLn $ show a ++ " " ++ show b

process :: Int -> [(Char, Int)] -> (Int, Int)
process x fs = foldl f (x,0) fs
    where
        f (x,y) (c,d)
            | c == '-' = if x < d then (x,y+1) else (x-d,y)
            | otherwise = (x+d,y)

readInt :: String -> Int
readInt = read

processLine :: String -> (Char, Int)
processLine line = (char,d)
    where
        [char:_,dStr] = words line
        d = read dStr

main :: IO ()
main = do
    line <- getLine
    let [n,x] = map readInt (words line)
    fs <- fmap (map processLine.lines) getContents
    let (x',y') = process x fs
    putStrLn $ show x' ++ " " ++ show y'


import Control.Monad
import Data.List

doit :: Int -> Int -> String -> Int
doit _ _ [] = 0
doit k sz ('*':xs) = doit k 0 xs
doit k sz ('.':xs) = doit k (sz + 1) xs + cur
  where cur = if sz + 1 >= k then 1 else 0

main = do
  [n,m,k] <- fmap (fmap read . words) getLine
  l <- replicateM n getLine
  print $ if k == 1
          then sum . map (length . filter (=='.')) $ l
          else sum . map sum . map (map (doit k 0)) $ [l, transpose l]

import Control.Monad
import Data.List

doit :: Int -> Int -> String -> Int
doit k sz l = length . filter (>= k) $ scanl f 0 l
  where f sz '*' = 0
        f sz '.' = sz + 1

main = do
  [n,m,k] <- fmap (fmap read . words) getLine
  l <- replicateM n getLine
  print $ if k == 1
          then sum . map (length . filter (=='.')) $ l
          else sum . map sum . map (map (doit k 0)) $ [l, transpose l]

{-# LANGUAGE BangPatterns #-}
import           Control.Applicative
import           Control.Monad
import           Data.List
main = do
  [n, _, k]  <- map read.words <$> getLine
  css <- replicateM n getLine
  print $ solve k css

solve :: Int -> [String] -> Int
solve k css
  | k == 1 = sum $ map step css
  | otherwise =  sum (map step css) + sum (map step (transpose css))
  where
    step cs = sum [l - k + 1 | g@('.':_)<-group cs, let !l=length g, l >= k]


import Control.Monad
import Data.List

toShow True = "Bob"
toShow False = "Alice"

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let n = read  input ::Int
        input <- getLine
        let od = length . filter odd. map (read::String -> Int) . words $ input
        putStrLn .toShow $ odd (div od 2) && even od || odd n && odd (div (od+1) 2)
    return ()

import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase = read <$> getLine >>=
        \n -> map read . words <$> getLine >>=
        print . whoWins n

data Player = Alice | Bob deriving (Eq, Show)

whoWins :: Int -> [Int] -> Player
whoWins n as = let o = foldl (\acc e -> if (mod e 2 == 0) then acc else acc+1) 0 as
                   p x = mod x 2 == 0
                   k = div n 2
                   m = div o 2
               in
                 case (p n, p o) of
                   (_, True) -> if (mod m 2 == 0) then Alice else Bob
                   (True, False) -> Alice
                   (False, False) -> if (mod (m+1) 2 == 0) then Alice else Bob

import Control.Monad
import Data.List

toShow True = "Bob"
toShow False = "Alice"

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let n = read  input ::Int
        input <- getLine
        let a = map read . words $ input ::[Int]
            od = length $ filter odd a

        putStrLn .toShow $ od==2 || (od/=1 || odd n) && odd (div (od+1) 2)
    return ()

import Control.Monad
import Data.List

toShow True = "Bob"
toShow False = "Alice"

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let n = read  input ::Int
        input <- getLine
        let a = map read . words $ input ::[Int]
            od = length $ filter odd a

        putStrLn .toShow $ od==2 || od==1 && odd n || odd (div (od+1) 2)
    return ()

import Control.Monad
import Data.List

toShow True = "Bob"
toShow False = "Alice"

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let n = read  input ::Int
        input <- getLine
        let a = map read . words $ input ::[Int]
            od = length $ filter odd a

        putStrLn .toShow $ od==2 || od==1 && odd n || odd n  && odd (div (od+1) 2)
    return ()

import Control.Monad
import Data.List

toShow True = "Bob"
toShow False = "Alice"

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let n = read  input ::Int
        input <- getLine
        let a = map read . words $ input ::[Int]
            od = length $ filter odd a

        putStrLn .toShow $ od==2 || od==1 && odd n
    return ()

import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase = read <$> getLine >>=
        \n -> map read . words <$> getLine >>=
        print . whoWins n

data Player = Alice | Bob deriving (Eq, Show)

whoWins :: Int -> [Int] -> Player
whoWins n as = let o = foldl (\acc e -> if (mod e 2 == 0) then acc else acc+1) 0 as
                   p x = mod x 2 == 0
                   k = div n 2
                   m = div o 2
               in
                 case (p n, p o) of
                   (_, True) -> if (mod m 2 == 0) then Alice else Bob
                   (True, False) -> Alice
                   (False, False) -> if (k > m)
                                     then Alice
                                     else if (mod (m+1) 2 == 0) then Alice else Bob


import qualified Data.ByteString.Char8 as B
import qualified Data.Set as ST
import Control.Monad
import Data.List
import Data.Maybe

solve xs = loop st
  where
    st = foldl' (flip ST.insert) ST.empty xs
    loop st
      | ST.null st = 0
      | m == 0 = 1 + loop (ST.insert d st')
      | otherwise = loop st'
      where
        m = a `mod` 2
        d = a `div` 2
        (a,st') = ST.deleteFindMax st

main = do
  t <- readLn :: IO Int
  replicateM_ t $ do
    n <- readLn :: IO Int
    xs <- map read . words <$> getLine :: IO [Int]
    print $ solve xs

import qualified Data.Set as Set
import Control.Monad

solve :: Set.Set Int -> Int -- only for even elements
solve s
  |Set.null s = 0
  |otherwise = if odd m2 then 1 + solve s' else 1 + solve (Set.insert m2 s')
  where
    m = Set.findMax s
    m2 = m `div` 2
    s' = Set.delete m s

routine :: IO ()
routine = do
  _ <- getLine
  l <-(filter even . map read . words) <$> getLine
  print $ solve $ Set.fromList l

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

import qualified Data.ByteString.Char8 as B
import qualified Data.Set as ST
import Control.Monad
import Data.List
import Data.Maybe

solve xs = loop st
  where
    st = foldl' (flip ST.insert) ST.empty xs
    loop st
      | ST.null st = 0
      | m == 0 = 1 + loop (ST.insert d st')
      | otherwise = loop st'
      where
        m = a `mod` 2
        d = a `div` 2
        (a,st') = ST.deleteFindMax st

main = do
  t <- readLn :: IO Int
  replicateM_ t $ do
    n <- readLn :: IO Int
    xs <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine :: IO [Int]
    print $ solve xs

{-# LANGUAGE Strict #-}

import qualified Data.ByteString.Char8 as B
import qualified Data.Map as MP
import Data.Array
import Data.Maybe
import Data.Maybe
import Control.Monad

count :: MP.Map Int Int -> Int -> Int -> MP.Map Int Int
count mp x acc =
    case MP.lookup k mp of
      Just _ -> MP.adjust (max v) k mp
      Nothing -> MP.insert k v mp
  where
    (k,v) = loop x (0,0)
    loop a (k,v)
      | m == 1 = (d,v)
      | otherwise = loop d (k,v+1)
      where
        d = a `div` 2
        m = a `mod` 2

solve arr n = MP.foldl (+) 0 mp
  where
    mp = loop 0 MP.empty
    loop i m
      | i > n = m
      | otherwise =
        let
          v = arr ! i
          m' = count m v 0
        in
          loop (i+1) m'
main = do
  t <- readLn :: IO Int
  replicateM_ t $ do
    n <- readLn :: IO Int
    arr <- listArray (0, n-1) <$> map (fst . fromJust . B.readInt) . B.words <$> B.getLine :: IO (Array Int Int)
    print $ solve arr (n-1)


import Control.Monad ( replicateM )

main = do
  n <- readLn
  replicateM n $ do
    getLine
    arr <- fmap (fmap read . words) getLine
    print $ ceiling $ fromIntegral (sum arr) / fromIntegral (length arr)

import Control.Monad
main = do
  q <- readLn
  replicateM_ q $ do
    n <- readLn
    s <- sum . map read . words <$> getLine
    print $ (s + n - 1) `div` n

import Control.Monad
import Data.Ratio

solve :: [Int] -> Int
solve nums = ceiling (sum nums % length nums)

main = do
  numQueries <- read <$> getLine
  replicateM numQueries $ do
    _ <- getLine
    prices <- fmap read <$> words <$> getLine
    print $ solve prices

module Main where

import Control.Monad
import Data.List

cdiv num den = (num + den - 1) `div` den
avg vals = let l = length vals in cdiv (sum vals) l

main :: IO ()
main = do
    let ri = read::String->Int
    q <- ri <$> getLine

    replicateM_ q $ do
        _ <- ri <$> getLine
        vals <- fmap ri . words <$> getLine

        print $ avg vals
        return ()
    return ()

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

onecase= do
	   r<-read <$>getLine ::IO Int
	   a<-sum <$> map read <$> words <$> getLine::IO Int
           let ans =  div a r+ if mod a r>0 then 1 else 0
	   print ans

main::IO ()
main=do
  t<- read <$> getLine ::IO Int
  replicateM_ t onecase

import Control.Monad
divUp a b
	| a `mod` b == 0 = a `div` b
	| otherwise      = (a `div` b) + 1

doQuery = do
	nStr <- getLine
	listStr <- getLine
	let ans = (sum $ map read $ words listStr) `divUp` (read nStr)
	putStrLn $ show ans

main = do
	q <- getLine
	replicateM_ (read q) doQuery

handle = do
	line <- getLine
	l2 <- getLine
	let n = read line :: Int
	let ar = map read (words l2) :: [Int]
	let s = sum ar
	let res = (s+n-1) `div` n
	putStrLn (show res)

handleCase 0 = return ()
handleCase n = do
	handle
	handleCase (n-1)

main = do
	lineq <- getLine
	let q = (read lineq :: Int)
	handleCase q
	{-
	line2 <- getLine
	let n = (read line :: Int)
	let x = n+1
	let s = show x
	let z = words line2
	let ar = map read z :: [Int]
	let s2 = map (show . (+ 1)) ar
	putStrLn s
	putStrLn (concat s2) -}

import Control.Monad (replicateM_)
import Control.Arrow ((>>>))
main :: IO ()
main = do
  q <- read <$> getLine ::IO Int
  replicateM_ q solve
solve :: IO()
solve = do
  n <- read <$> getLine :: IO Int
  xs <- (words >>> map read) <$> getLine
  print $ ceiling $ fromIntegral (sum xs) / fromIntegral n

import Control.Monad ( replicateM )

main = do
  n <- readLn
  replicateM n $ do
    getLine
    arr <- fmap (fmap read . words) getLine
    print $ sum arr `div` length arr

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

onecase= do
	   r<-read <$>getLine ::IO Int
	   a<-sum <$> map read <$> words <$> getLine::IO Int
           let ans = 1+ div a r
	   print ans

main::IO ()
main=do
  t<- read <$> getLine ::IO Int
  replicateM_ t onecase


solv :: [Integer] -> Bool
solv l = let s = sum l in
             let mx = maximum l in
                 (mod s 2 == 0) && (mx <= (div s 2))

main = do
  l <- getLine
  let n = (read l) :: Int
  inp <- getLine
  let inn = map read $ words inp
  let res = solv inn
  putStrLn $ if res then "YES" else "NO"

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

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

countLetters :: [Char] -> Char -> Int
countLetters array_ char_ = length (filter (==char_) array_)

scoreCount :: [String] -> Int -> [Int]
scoreCount answList questionNumber =
  if (0 == length (answList!!0))
  then []
  else do
    let currentAnswer = (!!0) <$> answList
    let restAnswers = (drop 1) <$> answList
    let answers = ['A','B','C','D','E']
    let maxScore = maximum ((countLetters currentAnswer) <$> answers)
    maxScore : scoreCount restAnswers (questionNumber + 1)

myDot :: [Int] -> [Int] -> Int
myDot x y = sum (zipWith (*) x y)

main = do
  getLine
  dataInts <- getLine
  let array_ = parseLineToInt dataInts
  let sum_ = sum array_
  let max_ = maximum array_
  if ((mod sum_  2 == 0) &&((2 * max_) <= sum_))
  then putStrLn $ "YES"
  else putStrLn $ "NO"

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

main::IO()
main = do
    n <- getLine
    a <- map read . words <$> getLine
    let suma = foldl (+) 0 a
    let maxa = maximum a
    if suma `rem` 2 == 1
        then putStrLn "NO"
        else if suma `div` 2 < maxa
            then putStrLn "NO"
            else putStrLn "YES"

main :: IO ()
main = do
  _ <- getLine
  num <- getLine
  let nums = (read :: String -> Integer) <$> words num
  let sum_ = sum nums
  let max_ = maximum nums
  if (mod sum_ 2 == 0) && ((2 * max_) <= sum_)
     then putStrLn "YES"
  else putStrLn "NO"

main :: IO ()
main = do
  _ <- getLine
  num <- getLine
  let nums = (read :: String -> Int) <$> words num
  if ( (== 0) $ mod (sum nums) 2) && ((2*) $ maximum nums) <= sum nums
     then putStrLn "YES"
  else putStrLn "NO"

main :: IO ()
main = do
  _ <- getLine
  num <- getLine
  let nums = (read :: String -> Int) <$> words num
  if ( (== 0) $ mod (sum nums) 2) && maximum nums <= sum nums
     then putStrLn "YES"
  else putStrLn "NO"

main :: IO ()
main = do
  _ <- getLine
  num <- getLine
  let nums = (read :: String -> Int) <$> words num
  let sum_ = sum nums
  let max_ = maximum nums
  if (mod sum_ 2 == 0) && ((2 * max_) <= sum_)
     then putStrLn "YES"
  else putStrLn "NO"

main :: IO ()
main = do
  _ <- getLine
  num <- getLine
  let nums = (read :: String -> Int) <$> words num
  let sum_ = sum nums
  let max_ = maximum nums
  if (sum_ `mod` 2 == 0) && (2 * max_ <= sum nums)
     then putStrLn "YES"
  else putStrLn "NO"

main :: IO ()
main = do
  _ <- getLine
  num <- getLine
  let nums = (read :: String -> Int) <$> words num
  if ( (== 0) $ mod (sum nums) 2) && maximum nums <= sum nums
     then print "YES"
  else print "NO"

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

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

countLetters :: [Char] -> Char -> Int
countLetters array_ char_ = length (filter (==char_) array_)

scoreCount :: [String] -> Int -> [Int]
scoreCount answList questionNumber =
  if (0 == length (answList!!0))
  then []
  else do
    let currentAnswer = (!!0) <$> answList
    let restAnswers = (drop 1) <$> answList
    let answers = ['A','B','C','D','E']
    let maxScore = maximum ((countLetters currentAnswer) <$> answers)
    maxScore : scoreCount restAnswers (questionNumber + 1)

myDot :: [Int] -> [Int] -> Int
myDot x y = sum (zipWith (*) x y)

main = do
  getLine
  dataInts <- getLine
  let array_ = parseLineToInt dataInts
  let sum_ = sum array_
  let max_ = maximum array_
  if ((mod sum_  2 == 0) &&((2 * max_) <= sum_))
  then putStrLn $ "YES"
  else putStrLn $ "NO"

solv :: [Int] -> Bool
solv l = let s = sum l in
             let mx = maximum l in
                 (mod s 2 == 0) && (mx <= (div s 2))

main = do
  l <- getLine
  let n = (read l) :: Int
  inp <- getLine
  let inn = map read $ words inp
  let res = solv inn
  putStrLn $ if res then "YES" else "NO"


main=interact$f.map read.words
f[1,1]="a"
f[n,k]|n<k||k<2="-1"|0<1=take(n-k+2)(cycle"ab")++take(k-2)['c'..]

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

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

import qualified Data.ByteString.Lazy.Builder as BB

import Data.Monoid
import System.IO

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

main = do
  [n, k] <- getInts

  let
    r
      | n < k = Nothing
      | k == 1 = if n == 1 then Just "a" else Nothing
      | otherwise = Just $ (take (n-(k-2)) $ concat $ repeat "ab") ++ take (k-2) ['c'..]

  putStrLn $ case r of
               Nothing -> show (-1)
               Just k -> k

s[1,1]="a"
s[n,1]="-1"
s[n,k]|n<k="-1"
 |otherwise=take n(take i(cycle "ab")++['c'..]) where
  i = n - (k-2)
main=interact$s.map read.words

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

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

-- | templ

main :: IO ()
main = do
  [n, k] <- getNums
  case () of
    _ | n < k || (k == 1 && n > 1) -> print (-1)
      | even (n-k) -> putStrLn $ concat ["a", concat (replicate ((n-k)`div`2) "ba"), take (k-1) ['b'..]]
      | otherwise -> putStrLn $ concat ["a", concat (replicate ((n-k+1)`div`2) "ba"), take (k-2) ['c'..]]

import Data.Char
f a b | b > a || (b == 1 && a > 1) = "-1"
      | b == 1 && a == 1 = "a"
      | otherwise = (concat $ replicate delta "ab") ++ s' ++ ['c'..maxLet]
        where delta = (a - b + 2) `div` 2
              s' = if odd (a - b) then "a" else ""
              maxLet = chr $ ord 'c' + (b - 3)
main = do
    a:b:_ <- fmap (map (read :: String -> Int) . words) getLine
    putStrLn $ f a b

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

import Data.List
import Data.Maybe

main = do
    [n,k] <- map read . words <$> getLine
    putStrLn $ solve n k

alphabet = "abcdefghijklmnopqrstuvwxyz"

solve :: Int -> Int -> String
solve 1 1 = "a"
solve 1 n = "-1"
solve n 1 = "-1"
solve n 2 = take n (cycle "ab")
solve n k | k > n       = "-1"
          | even (n-k)  = take (n-k) (cycle "ab") ++ take k alphabet
          | otherwise   = take (n-k) (cycle "ab") ++ "ba" ++ take (k-2) (drop 2 alphabet)

import Control.Applicative
import Data.List
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Char8 as B
showBI :: Int -> B.ByteString
showBI = B.pack . show
readBI :: B.ByteString -> Int
readBI = fst . fromJust . B.readInt

main = B.interact $ B.pack . go . map readBI . B.words
go (n:k:[]) | k == 1 = if n == 1 then "a" else "-1"
            | n >= k = (take (n-k+2) . cycle $ "ab") ++ (take (k-2) ['c'..'z'])
            | otherwise = "-1"

import Control.Applicative
import Data.List
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Char8 as B
showBI :: Int -> B.ByteString
showBI = B.pack . show
readBI :: B.ByteString -> Int
readBI = fst . fromJust . B.readInt

main = interact $ go . map read . words
go (n:k:[]) | k == 1 = if n == 1 then "a" else "-1"
            | n >= k = (take (n-k+2) . cycle $ "ab") ++ (take (k-2) ['c'..'z'])
            | otherwise = "-1"

import System.IO
import Data.Char(chr)

main :: IO ()
main = interact (handle)

handle :: String -> String
handle str =
   let ints = pair_up $ map (\x -> read x :: Int) $ take 2 $ words str
   in  solve False ints

pair_up :: [Int] -> (Int, Int)
pair_up (x:y:_) = (x, y)
pair_up _ = undefined

solve :: Bool -> (Int, Int) -> String
solve False (l,d)
    | l < d            = "-1"
    | d == 1 && l > 1  = "-1"
    | d == 1 && l == 1 = "a"
    | l == d           = 'a':'b':(make_tail (l-2) (d-2))
    | l == d + 1       = 'a':'b':(make_tail (l-2) (d-2))
    | otherwise        = 'a':'b':(solve True (l-2,d))
solve True (l,d)
    | l == d           = 'a':'b':(make_tail (l-2) (d-2))
    | l == d + 1       = 'a':'b':(make_tail (l-2) (d-2))
    | otherwise        = 'a':'b':(solve True (l-2,d))

make_tail :: Int -> Int -> String
make_tail m n
    | m == n + 1         = 'a':(map chr [99..(99+n-1)])
    | m == n             = map chr [99..(99+n-1)]
    | otherwise          = undefined

import Control.Applicative
import Data.List
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Char8 as B
showBI :: Int -> B.ByteString
showBI = B.pack . show
readBI :: B.ByteString -> Int
readBI = fst . fromJust . B.readInt

main = B.interact $ B.pack . go . map readBI . B.words
go (n:k:[]) | n >= k = (take (n-k+2) . cycle $ "ab") ++ (take (k-2) ['c'..'z'])
            | otherwise = "-1"

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

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

-- | templ

main :: IO ()
main = do
  [n, k] <- getNums
  case () of
    _ | n < k -> print (-1)
      | even (n-k) -> putStrLn $ concat ["a", concat (replicate ((n-k)`div`2) "ba"), take (k-1) ['b'..]]
      | otherwise -> putStrLn $ concat ["a", concat (replicate ((n-k+1)`div`2) "ba"), take (k-2) ['c'..]]


import Control.Monad
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as C

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

main :: IO ()
main = do
  [n, k] <- getInts
  let maxChar = toEnum (fromEnum 'a' + k - 1) :: Char
      func _ [] = []
      func ch (x : xs) = x : ch : func ch xs
      s = concat ['a' : func ch [ch..maxChar] | ch <- ['b'..maxChar]] ++ "a"
      t = take n $ 'a' : concat (repeat s)
  C.putStrLn $ C.pack t

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

readArray :: Read a => IO [a]
readArray = fmap (map read . words) getLine

readInts :: IO [Int]
readInts = readArray

lyndonCut :: Char -> String -> String
lyndonCut m [] = []
lyndonCut m (c:s)
  | c == m = lyndonCut m s
  | otherwise = ((toEnum (fromEnum c + 1)):s)

nextLyndonWord :: Int -> Char -> String -> String
nextLyndonWord n m s =
  reverse $ lyndonCut m $ reverse $ take n $ concat $ repeat s

lyndonWords :: Int -> Char -> [String]
lyndonWords n c =
  takeWhile (not . null) $ iterate (nextLyndonWord n c) "a"

deBruijn :: Int -> Char -> String
deBruijn n =
  concat . filter (\a -> n `mod` length a == 0) . lyndonWords n

solve :: Int -> Int -> String
solve n k =
  take n $ concat $ repeat $ deBruijn 2 $ toEnum $ fromEnum 'a' + k - 1

solveCase :: IO String
solveCase = do
  [n, k] <- readInts
  return $ solve n k

main :: IO ()
main = solveCase >>= putStrLn

--solveCase :: IO String
--solveCase = do
--  (n:x:[]) <- readInts
--  fmap (show . solve x) readInts
--
--main :: IO ()
--main = readLn >>= flip replicateM_ (solveCase >>= putStrLn)


main = do
    getLine
    interact $ unlines . map (show . solve' . words) . lines

solve' [x, y] = solve ((read x) :: Integer) ((read y) :: Integer)

solve n k = if (mod n 2) == 0
                then let a = mod k n in if a == 0 then n else a
                else soleven n k

soleven n k = let x = mod (apos + r) n in if x == 0 then n else x
  where
    t = div (n - 1) 2
    m = div (k - 1) t
    r = k - 1 - m * t
    apos = (n + 1) - let a = (mod (m * t) n) in if a == 0 then n else a

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

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

type SIO = StateT P.ByteString IO

solve :: Int -> Int -> Int
solve n k
  | even n  = mod k n
  | odd n  = let
      per = div n 2
      (x, y) = divMod (k-1) per
      totSteps = x * (per + 1) + y + 1
      in  mod totSteps n

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n, k] <- readInts
    let
      ans0 = solve n k
      ans = if  ans0 == 0  then  n  else  ans0
    putInts [ans]

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

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

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

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

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

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    [n, k] <- getInts
    let
      result
        | even n = (k - 1) `mod` n + 1
        | otherwise = solve (1 + (p `div` m) `mod` n) (p `mod` m)
        where
        m = n - 1
        p = k - 1
      solve s p
        | p < n `div` 2 = (s + p - 1) `mod` n + 1
        | otherwise = (s + p) `mod` n + 1
    C.putStrLn $ C.pack $ show result

main = interact $ unlines.map show.f.map read.tail.words

f [] = []
f (n:k_:xs) =
    let k = k_ - 1; fl = n `div` 2
    in ((k + (n `mod` 2) * k `div` fl) `mod` n + 1) : f xs

{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
module Main where

import           Control.Monad                  ( replicateM_ )

catCycle :: Int -> Int -> Int
catCycle n (pred -> k) | even n    = (k `mod` n) + 1
                       | otherwise = ((k + step) `mod` n) + 1
  where step = k `div` ((n - 1) `div` 2)

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n, k] <- fmap read . words <$> getLine
    print $ catCycle n k

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

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

------

type Hopper r = State [r]

type HopperT r = StateT [r]

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

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

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

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

type MonadHopper r m = MonadState [r] m

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

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

------

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

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

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

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

------

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

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

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

------

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

run1 = do
  ~[n, k] <- popIntegers
  return $ bshow (solve n (k - 1))

solve !n !k
  | n `rem` 2 == 0 = k `rem` n + 1
  | otherwise =
    let c = n `quot` 2
        k' = k `rem` (n * c)
        (p, q) = k' `quotRem` c in
      (p * (c + 1) + q) `rem` n + 1

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

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

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    [n, k] <- getInts
    let
      result
        | even n = (k - 1) `mod` n + 1
        | otherwise = solve (1 + (p `div` m) `mod` n) (p `mod` m)
        where
        m = n - 1
        p = k - 1
      solve s p
        | p < n `div` 2 = s + p
        | otherwise = (s + p) `mod` n + 1
    C.putStrLn $ C.pack $ show result

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

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

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    [n, k] <- getInts
    let
      result
        | even n = (k - 1) `mod` n + 1
        | otherwise = solve (1 + (p `div` m) `mod` n) (p `mod` m)
        where
        m = n - 1
        p = k - 1
      solve s p
        | p < n `div` 2 = s + p
        | otherwise = s + 1 + p
    C.putStrLn $ C.pack $ show result

main = do
    getLine
    interact $ unlines . map (show . solve' . words) . lines

solve' [x, y] = solve ((read x) :: Integer) ((read y) :: Integer)

solve n k = if (mod n 2) == 0
                then let a = mod k n in if a == 0 then n else a
                else soleven n k

soleven n k = apos + r
  where
    t = div (n - 1) 2
    m = div (k - 1) t
    r = k - 1 - m * t
    apos = (n + 1) - let a = (mod (m * t) n) in if a == 0 then n else a


{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad
import Control.Monad.State (State, evalState, get, gets, put)
import Data.Bool
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Function
import Data.Int
import Data.List
import Data.Maybe
import Debug.Trace

----- Solution
data TC = TC {n :: Int64, k :: Int64, ss :: [Int64]}

type Output = Bool

input :: Scanner TC
input = do
  n <- int64
  k <- int64
  ss <- (fromIntegral k :: Int) >< int64
  return TC {..}

solve :: TC -> Output
solve TC {..} = sorted as && (null as || head as * (n - k + 1) >= head ss)
  where
    as = zipWith (-) (tail ss) ss

sorted :: Ord a => [a] -> Bool
sorted xs = and $ zipWith (<=) xs (tail xs)

output :: Int -> Output -> C.ByteString
output _ = showYesNo

main :: IO ()
main = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1 ..] >>> map (uncurry output) >>> C.unlines

-------------------------- Template ------------------------------------------
-- Debug
debug :: Show a => a -> a
debug a = trace (show a) a

-- helpers
(>$>) = flip ($)

infixl 0 >$>

-- Lists
groupOn :: Eq b => (a -> b) -> [a] -> [[a]]
groupOn = groupBy . on (==)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts

adjacents :: [a] -> [(a, a)]
adjacents xs = zip xs (tail xs)

adjacentsWith :: (a -> a -> b) -> [a] -> [b]
adjacentsWith f xs = zipWith f xs (tail xs)

count :: Eq a => a -> [a] -> Int
count = countBy . (==)

countBy :: (a -> Bool) -> [a] -> Int
countBy p = length . filter p

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

readStr :: Read a => Scanner a
readStr = read <$> str

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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

showYesNo :: Bool -> C.ByteString
showYesNo = bool "NO" "YES" >>> C.pack

{-# LANGUAGE OverloadedStrings #-}

import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Internal as BSI
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Maybe

main =
  cf $ do
    [n, k] <- readInts
    nums <- readInts
    let hn = head nums
        v1 = (nums !! 1) - head nums
        dh = n - k + 1
        p =
          if k < 2
            then True
            else hn - v1 * dh <= 0
        diffs =
          zipWith3
            (\p c n -> (p - (2 * c) + n >= 0))
            nums
            (tail nums)
            (drop 2 nums)
        q = and diffs
    BS.putStrLn $
      if p && q
        then "Yes"
        else "No"

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

readInt :: IO Int
readInt = readLn

cf x = readInt >>= (`replicateM_` x)

import Control.Monad

toShow True = "YES"
toShow False = "NO"

solve n m = (div (n+1) 2,div (m+1) 2)

isAsc (x:y:xs) = x<=y && isAsc (y:xs)
isAsc _ = True

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let [n,k] = map read . words $ input ::[Integer]
        input <- getLine
        let s = map read . words $ input ::[Integer]
        let a = zipWith (-) (tail s) s
        putStrLn.toShow $ (isAsc a && (a==[] || (head s) <= (n-k+1)*head a))
    return ()

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

solve _ [_] = True
solve n ps = sorted && head ps <= mxsum where
  xs = zipWith (-) (tail ps) ps
  sorted = and $ zipWith (<=) xs (tail xs)
  mxsum = head xs * (n - length xs)

yesno True = "Yes"
yesno False = "No"

main = do
  [t] <- readInts
  replicateM_ t $
    solve . head <$> readInts <*> readInts >>= putStrLn . yesno

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

import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase = map read . words <$> getLine >>=
        \[n, k] -> map read . words <$> getLine >>=
        \ss -> putStrLn $ if possible n k ss then "YES" else "NO"

possible :: Int -> Int -> [Int] -> Bool
possible n k ss = let (finalTerms, _) = foldl (\(acc, s) s1 -> (s1-s:acc, s1))
                                        ([], head ss) (tail ss)
                      isSorted xs = all (\(x, y) -> x >= y) (zip xs (tail xs))
                      realizable n k maxTerm left = maxTerm*(n-k+1) >= left

                  in
                    if finalTerms == []
                    then True
                    else (isSorted finalTerms) &&
                         (realizable n k (last finalTerms) (head ss))

{-# LANGUAGE OverloadedStrings #-}

import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Internal as BSI
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Maybe

main =
  cf $ do
    [n, k] <- readInts
    nums' <- readInts
    let nums = drop (n - k) (0 : nums')
        diffs =
          zipWith3
            (\p c n -> (p - (2 * c) + n >= 0))
            nums
            (tail nums)
            (drop 2 nums)
        q = and diffs
    BS.putStrLn $
      if q
        then "Yes"
        else "No"

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

readInt :: IO Int
readInt = readLn

cf x = readInt >>= (`replicateM_` x)

{-# LANGUAGE OverloadedStrings #-}

import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Internal as BSI
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Maybe

main =
  cf $ do
    [a, b] <- readInts
    nums <- readInts
    let diffs =
          zipWith3
            (\p c n -> (p - (2 * c) + n >= 0))
            (0 : nums)
            nums
            (tail nums)
        q = and diffs
    BS.putStrLn $
      if q
        then "Yes"
        else "No"

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

readInt :: IO Int
readInt = readLn

cf x = readInt >>= (`replicateM_` x)

import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase = map read . words <$> getLine >>=
        \[n, k] -> map read . words <$> getLine >>=
        \ss -> putStrLn $ if possible n k ss then "YES" else "NO"

possible :: Int -> Int -> [Int] -> Bool
possible n k ss = let (finalTerms, _) = foldl (\(acc, s) s1 -> (s1-s:acc, s1))
                                        ([], head ss) (tail ss)
                      isSorted xs = all (\(x, y) -> x >= y) (zip xs (tail xs))
                      realizable n k maxTerm left | n == k = maxTerm >= left
                                                  | otherwise = maxTerm*(n-k) >= left

                  in
                    if finalTerms == []
                    then True
                    else (isSorted finalTerms) &&
                         (realizable n k (last finalTerms) (head ss))

import Control.Monad

toShow True = "YES"
toShow False = "NO"

solve n m = (div (n+1) 2,div (m+1) 2)

isAsc (x:y:xs) = x<=y && isAsc (y:xs)
isAsc _ = True

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let [n,k] = map read . words $ input ::[Integer]
        input <- getLine
        let s = map read . words $ input ::[Integer]
        let a = zipWith (-) (tail s) s
        putStrLn .show$a
        putStrLn.toShow $ (isAsc a && (a==[] || (head s) <= (n-k+1)*head a))
    return ()


import Control.Monad ( replicateM_ )

cGood :: Char -> String -> Int
cGood c [x] = fromEnum (c /= x)
cGood c str = min (f a + g b) (g a + f b)
  where
    f = length . filter (/= c)
    g = cGood (succ c)
    (a, b) = splitAt (length str `div` 2) str

main :: IO ()
main = do
  n <- read <$> getLine
  replicateM_ n $ getLine >> getLine >>= print . cGood 'a'

import Data.List
import Control.Monad

notChar char xs = length $ filter (/= char) xs

good char [x]
  | x == char = True
  | otherwise = False
good char xs = (all (== char) start && good (succ char) end) || (all (== char) end && good (succ char) start)
  where
    (start, end) = splitAt n xs
    n = length xs `quot` 2

makeGood xs = go xs 'a' 0
  where
    go xs char m | good char xs = m
    go [x] char m = m + 1
    go xs char m = min (go end (succ char) (m + notChar char start)) (go start (succ char) (m + notChar char end))
      where
        (start, end) = splitAt n xs
        n = length xs `quot` 2

getTest :: IO String
getTest = do
  _ <- getLine
  getLine

main :: IO ()
main = do
  n <- getLine
  let n' = (read n :: Int)
  tests <- replicateM n' getTest
  mapM_ (print . makeGood) tests

import Data.List
import Control.Monad

data Half = Start | End deriving Show

notChar char xs = length $ filter (/= char) xs

mostHalf char xs = case nStart `compare` nEnd of
  GT -> Just Start
  LT -> Just End
  EQ -> Nothing
  where
    nStart = length $ filter (== char) start
    nEnd = length $ filter (== char) end

    (start, end) = splitAt n xs
    n = length xs `quot` 2

good char [x]
  | x == char = True
  | otherwise = False
good char xs = (all (== char) start && good (succ char) end) || (all (== char) end && good (succ char) start)
  where
    (start, end) = splitAt n xs
    n = length xs `quot` 2

makeGood xs = go xs 'a' 0
  where
    go xs char m | good char xs = m
    go [x] char m = m + 1
    go xs char m = case mostHalf char xs of
      Just Start -> go end (succ char) (m + notChar char start)
      Just End -> go start (succ char) (m + notChar char end)
      Nothing -> min (go end (succ char) (m + notChar char start)) (go start (succ char) (m + notChar char end))
      where
        (start, end) = splitAt n xs
        n = length xs `quot` 2

getTest :: IO String
getTest = do
  _ <- getLine
  getLine

main :: IO ()
main = do
  n <- getLine
  let n' = (read n :: Int)
  tests <- replicateM n' getTest
  mapM_ (print . makeGood) tests


import Control.Monad
main = do
    n <- fmap read getLine
    ps <- forM [1..n] (\_ -> getLine)
    print $ solve ps
solve :: [String] -> Int
solve = foldl f 0
    where f :: Int -> String -> Int
          f n s = if elem s $ map show [0..1000] then if read s < 18 then n + 1
                                                                     else n
                                                 else if s `elem` alcohol then n + 1
                                                                          else n
alcohol :: [String]
alcohol = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"]

module Main where

main
  = interact in2out

in2out input
  = output
  where
    output = show ans
    ans = count (<18) ages + count (\x->any (==x) alcohols) drinks
    ages = map (read::String->Int) [age | age@(x:xs)<-items, '0'<=x, x<='9']
    alcohols = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"]
    drinks = items
    items = tail . lines $ input
    count f []
      = 0
    count f (x:xs)
      | f x
      = 1 + count f xs
      | otherwise
      = count f xs

main = do
n <- getLine >>= return . read
ls <- getContents >>= return . (take n) . lines
print $ sum $ map wrong ls where
wrong l = if (l!!0) <= '9'
 then if (read l) < 18 then 1 else 0
 else if l `elem` al then 1 else 0
al = "ABSINTH":"BEER":"BRANDY":"CHAMPAGNE":"GIN":"RUM":"SAKE":"TEQUILA":"VODKA":"WHISKEY":"WINE":[]

import Char

type Visitor = Either Int String

alcohols :: [String]
alcohols =  ["ABSINTH", "BEER",
             "BRANDY", "CHAMPAGNE",
             "GIN", "RUM",
             "SAKE", "TEQUILA",
             "VODKA", "WHISKEY",
             "WINE"]

checkVisitor :: Visitor -> Bool
checkVisitor (Left  age)    =  age < 18
checkVisitor (Right drink)  =  elem drink alcohols

parseVisitor :: String -> Visitor
parseVisitor line
  |  isDigit headLine  =  Left (read line)
  |  otherwise         =  Right line
  where
    headLine = head line

readVisitor :: Int -> IO Visitor
readVisitor _  =  getLine >>= return . parseVisitor

--readVisitor :: Int -> IO Visitor
--readVisitor _ = do
--  line <- getLine
--  return $ parseVisitor line

main :: IO()
main = do
  n <- readLn
  visitors <- sequence (map readVisitor [1..n])
  print $ length (filter checkVisitor visitors)

import Data.Char
import Data.List

solve = show.(foldl' f 0).tail.words
  where f ans ss | all isDigit ss = if (read ss) < 18 then
                                      ans + 1
                                    else
                                      ans
                 | otherwise      = if (ss `elem` alco) then
                                      ans + 1
                                    else
                                      ans
        alco = ["ABSINTH", "BEER", "BRANDY",
                "CHAMPAGNE", "GIN", "RUM",
                "SAKE", "TEQUILA", "VODKA",
                "WHISKEY", "WINE"]

main = interact solve

main=interact$show.sum.map f.tail.lines
f a=fromEnum$elem a$[show x|x<-[0..17]]++words"ABSINTH BEER BRANDY CHAMPAGNE GIN RUM SAKE TEQUILA VODKA WHISKEY WINE"

import Prelude
import Data.Char
import Data.List
import Data.Functor

alc = words "ABSINTH BEER BRANDY CHAMPAGNE GIN RUM SAKE TEQUILA VODKA WHISKEY WINE"

main = interact q

q = func . tail . words

func::[String]->String
func x = case solve x of
           Just a -> show a
           Nothing-> "Error occurred"

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

reverseTuple::(a,b)->(b,a)
reverseTuple (a,b) = (b,a)

isVailed::String->Bool
isVailed "" = False
isVailed "0" = True
isVailed ('0':_) = False
isVailed _ = True

solve::[String]->Maybe Int
solve [] = Just 0
solve (x:xs) | isAlpha (x!!0) && x `elem` alc  = (+1) <$> solve xs
             | isDigit (x!!0) && (read x) < 18 = (+1) <$> solve xs
             | otherwise                       = solve xs

main = interact $ show . solve . tail . lines
solve = length . filter (\x -> elem x alc)
alc = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE",
  "TEQUILA", "VODKA", "WHISKEY", "WINE"] ++ map show [0..17]

{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE BangPatterns #-}

import qualified Data.ByteString.Lazy.Char8 as LB
import qualified Data.ByteString as SB
import Data.ByteString.Internal (inlinePerformIO)
import Foreign.C.String (CString)
import Foreign.C (CDouble)
import Data.Maybe
import Data.List (mapAccumL, sort, maximumBy, minimum, foldl')
import Data.Array
import qualified Data.Map as M
import qualified Data.IntMap as IM
import Debug.Trace
import Data.Function (on)
import Data.Ord (comparing)
import System.Random(mkStdGen, random)
import Data.Int(Int64)
import Data.Sequence (iterateN)

foreign import ccall unsafe "stdlib.h atof" c_atof :: CString -> IO Double
unsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof
{-# INLINE unsafeReadDouble #-}
readDouble = unsafeReadDouble . SB.concat . LB.toChunks
readInt = fst . fromJust . LB.readInt

debug :: Show a => a -> a
debug v = trace (show v) v
--debug _ = id

main = do (sn:desc) <- fmap LB.lines LB.getContents
          let n = readInt sn
              desc' = map (head . LB.words) . take n $ desc
              f s = case LB.readInt s of
                      Just (m, _)    -> m<18
                      otherwise      -> s `elem` (map LB.pack ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"])

              c = length . filter f . take n $ desc'
          print c

import Prelude
import Data.Char
import Data.List
import Data.Functor

alc = words "ABSINTH BEER BRANDY CHAMPAGNE GIN RUM SAKE TEQUILA VODKA WHISKEY WINE"

main = interact q

q = func . init . words

func::[String]->String
func x = case solve x of
           Just a -> show a
           Nothing-> "Error occurred"

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

reverseTuple::(a,b)->(b,a)
reverseTuple (a,b) = (b,a)

isVailed::String->Bool
isVailed "" = False
isVailed "0" = True
isVailed ('0':_) = False
isVailed _ = True

solve::[String]->Maybe Int
solve [] = Just 0
solve (x:xs) | isAlpha (x!!0) && x `elem` alc  = (+1) <$> solve xs
             | isDigit (x!!0) && (read x) < 18 = (+1) <$> solve xs
             | otherwise                       = solve xs

import Prelude
import List
import Char

main = interact q

q = func.tail.lines

func::[String]->String
func = show.solve

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

solve::[String]->Int
solve (x:xs) | (isNumber x) && (((read::String->Int) x) < 18) = 1 + solve xs
             | (isAlc x)                                     = 1 + solve xs
             | otherwise                                     =     solve xs
               where
                isNumber (x:_) | '0' < x && x <='9' = True
                              | otherwise          = False
                isAlc x = x `elem`  ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"]
solve [] = 0

import Prelude
import Data.Char
import Data.List
import Data.Functor

alc = words "ABSINTH BEER BRANDY CHAMPAGNE GIN RUM SAKE TEQUILA VODKA WHISKEY WINE"

main = interact q

q = func . init . words

func::[String]->String
func x = case solve x of
           Just a -> show a
           Nothing-> "Error occurred"

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

reverseTuple::(a,b)->(b,a)
reverseTuple (a,b) = (b,a)

isVailed::String->Bool
isVailed "" = False
isVailed "0" = True
isVailed ('0':_) = False
isVailed _ = True

solve::[String]->Maybe Int
solve [] = Just 0
solve (x:xs) | isAlpha (x!!0) && x `elem` alc  = (+1) <$> solve xs
             | isDigit (x!!0) && (read x) < 19 = (+1) <$> solve xs
             | otherwise                       = solve xs

import qualified Data.ByteString.Lazy.Char8 as LB
import Data.Maybe(fromJust)
readInt = fst . fromJust . LB.readInt

main = do
  s <- getContents
  print . map (s!!) $ [1, 4, 10]

{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE BangPatterns #-}

import qualified Data.ByteString.Lazy.Char8 as LB
import qualified Data.ByteString as SB
import Data.ByteString.Internal (inlinePerformIO)
import Foreign.C.String (CString)
import Foreign.C (CDouble)
import Data.Maybe
import Data.List (mapAccumL, sort, maximumBy, minimum, foldl')
import Data.Array
import qualified Data.Map as M
import qualified Data.IntMap as IM
import Debug.Trace
import Data.Function (on)
import Data.Ord (comparing)
import System.Random(mkStdGen, random)
import Data.Int(Int64)
import Data.Sequence (iterateN)

foreign import ccall unsafe "stdlib.h atof" c_atof :: CString -> IO Double
unsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof
{-# INLINE unsafeReadDouble #-}
readDouble = unsafeReadDouble . SB.concat . LB.toChunks
readInt = fst . fromJust . LB.readInt

debug :: Show a => a -> a
debug v = trace (show v) v
--debug _ = id

main = do (sn:desc) <- fmap LB.lines LB.getContents
          let n = readInt sn
              desc' = take n desc
              c1 = length . filter (`elem`
                    (map LB.pack ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"]))
                    $ desc'
              f s = case LB.readInt s of
                      Just (m, _)    -> m<18
                      otherwise -> False
              c2 = length . filter f $ desc'
          print (c1 + c2)

import qualified Data.ByteString.Lazy.Char8 as LB
import Data.Maybe(fromJust)
import Data.Char(ord)
readInt = fst . fromJust . LB.readInt

main = do
  s <- LB.getContents
  print . map (LB.index s) $ [1, 4, 10]

{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE BangPatterns #-}

import qualified Data.ByteString.Lazy.Char8 as LB
import qualified Data.ByteString as SB
import Data.ByteString.Internal (inlinePerformIO)
import Foreign.C.String (CString)
import Foreign.C (CDouble)
import Data.Maybe
import Data.List (mapAccumL, sort, maximumBy, minimum, foldl')
import Data.Array
import qualified Data.Map as M
import qualified Data.IntMap as IM
import Debug.Trace
import Data.Function (on)
import Data.Ord (comparing)
import System.Random(mkStdGen, random)
import Data.Int(Int64)
import Data.Sequence (iterateN)

foreign import ccall unsafe "stdlib.h atof" c_atof :: CString -> IO Double
unsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof
{-# INLINE unsafeReadDouble #-}
readDouble = unsafeReadDouble . SB.concat . LB.toChunks
readInt = fst . fromJust . LB.readInt

debug :: Show a => a -> a
debug v = trace (show v) v
--debug _ = id

main = do (sn:desc) <- fmap LB.lines LB.getContents
          let n = readInt sn
              desc' = take n $ desc
              f s = case LB.readInt s of
                      Just (m, _)    -> m<18
                      otherwise      -> s `elem` (map LB.pack ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"])

              c = length . filter f . take n $ desc'
          print c

{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE BangPatterns #-}

import qualified Data.ByteString.Lazy.Char8 as LB
import qualified Data.ByteString as SB
import Data.ByteString.Internal (inlinePerformIO)
import Foreign.C.String (CString)
import Foreign.C (CDouble)
import Data.Maybe
import Data.List (mapAccumL, sort, maximumBy, minimum, foldl')
import Data.Array
import qualified Data.Map as M
import qualified Data.IntMap as IM
import Debug.Trace
import Data.Function (on)
import Data.Ord (comparing)
import System.Random(mkStdGen, random)
import Data.Int(Int64)
import Data.Sequence (iterateN)

foreign import ccall unsafe "stdlib.h atof" c_atof :: CString -> IO Double
unsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof
{-# INLINE unsafeReadDouble #-}
readDouble = unsafeReadDouble . SB.concat . LB.toChunks
readInt = fst . fromJust . LB.readInt

debug :: Show a => a -> a
debug v = trace (show v) v
--debug _ = id

main = do (sn:desc) <- fmap LB.lines LB.getContents
          let n = readInt sn
              f s = case LB.readInt s of
                      Just (m, _)    -> m<18
                      otherwise      -> s `elem` (map LB.pack ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"])

              c = length . filter f . take n $ desc
          print c


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.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
--import Data.List
--import Data.Array.Unboxed

csort :: [Int] -> [Int]
csort [] = []
csort li = let
  tar = minimum li
  (pref, _tar : suff) = span (> tar) li
  in  length pref : csort (suff ++ pref)

mainFun :: SO
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    a <- getInts n
    let
      res = csort a
      ans = [[l, n, v] | (l, v) <- zip [1..n] res, v > 0]
    pure $ putInts [length ans] <> foldMap putInts ans

type SP = State [P.ByteString]
type SO = SP Builder

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

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

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

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  cat -- input.txt | ./a.out > tmp.txt  &&  diff -sdu -- output.txt tmp.txt  &&  cat -- tmp.txt)

-- (echo 1000; for i in {1..1000}; do apg -a'1' -M'N' -m'9' -x'9' -n'50' | { echo 50; echo `cat`; };  done) > large_input.txt
--
-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  cat -- large_input.txt | time ./a.out | wc --bytes)

import Prelude
-- import System.IO
import Control.Monad
import Data.List
import Data.Maybe

-- import Debug.Trace
-- trF showFunc x = trace msg x  where  msg = "\n" ++ "trF: " ++ showFunc x ++ "."
-- tr s x = trace msg x  where  msg = "\n" ++ "tr: " ++ s ++ ": " ++ show x ++ "."

main :: IO ()
main = do
    -- hSetBuffering stdout NoBuffering

    t <- readLn
    tcs <- replicateM t getTC

    (putStr . concatMap solve) tcs

getTC = do
    n <- readLn
    map read <$> wordsN n <$> getLine     :: IO [Int]

wordsN n s = ww  where  w = words s; ww | (length w == n) = w
                                        | otherwise = error "arr len"

unlinesN strs = (unlines . ([show $ length strs]++)) strs

solve xs = unlinesN . map showOp . filter ((/= 0) . snd) . zip [1..] $ minIndices
  where
    minIndices = map fst . take (length xs - 1) . tail . iterate step $ (undefined, xs)

    showOp (i, off) = show i ++ " " ++ show (i+off) ++ " " ++ show off

step (_, xs) = removeMin xs

removeMin [] = error "can not remove"
removeMin xs = (i, h ++ tail t)
  where
    i = (fromJust . findMinIndex) xs

    (h,t) = splitAt i xs

findMinIndex xs = let m = minimum xs
                  in  findIndex (== m) xs

import Control.Monad ( replicateM_, forM_ )
import Data.List ( intercalate )

calc n i a
  | n == i + 1 = [[]]
  | id == 0 = calc n (i + 1) na
  | otherwise = [i + 1, n, id] : calc n (i + 1) na
  where
      id = snd $ minimum $ zip a [0..]
      na = tail $ drop id a <> take id a

solve = do
    [n] <- map read.words <$> getLine :: IO [Int]
    a <- map read.words <$> getLine :: IO [Int]
    let f = init $ calc n 0 a
    print (length f)
    forM_ f $ \item -> do
      putStrLn $ unwords $ map show item

main = readLn >>= flip replicateM_ solve

import Control.Monad ( replicateM_, forM_ )
import Data.List ( intercalate, delete )

calc' :: [Int] -> Int -> [[Int]] -> [[Int]]
calc' [] _ acc = acc
calc' lst j acc =
  let (mn, i) = minimum $ zip lst [1..]
      lst' = delete mn lst
  in
    if i == 1 then calc' lst' (j + 1) acc
    else calc' lst' (j + 1) ([j + 1, j + i, i - 1] : acc)

calc :: [Int] -> [[Int]]
calc lst = reverse $ calc' lst 0 []

solve = do
    [n] <- map read.words <$> getLine :: IO [Int]
    a <- map read.words <$> getLine :: IO [Int]
    let f = calc a
    print (length f)
    forM_ f $ \item -> do
      putStrLn $ unwords $ map show item

main = readLn >>= flip replicateM_ solve

import Control.Monad ( replicateM_, forM_ )
import Data.List ( intercalate )

mix :: [Int] -> Int -> Int -> Int
mix (a : as) m i = if a == m then i else mix as m i + 1
mix [] _ _ = 0

shift :: [Int] -> Int -> [Int]
shift a s = drop s a <> take s a

calc :: Int -> Int -> [Int] -> [[Int]]
calc n i a
  | n == i + 1 = [[]]
  | id == 0 = calc n (i + 1) (tail $ shift a id)
  | otherwise = [i + 1, n, id] : calc n (i + 1) (tail $ shift a id)
  where
      id = mix a (minimum a) 0

solve = do
    [n] <- map read.words <$> getLine :: IO [Int]
    a <- map read.words <$> getLine :: IO [Int]
    let f = init $ calc n 0 a
    print (length f)
    forM_ f $ \item -> do
      putStrLn $ unwords $ map show item

main = readLn >>= flip replicateM_ solve

import Control.Monad
import Data.List

-- 2 5 1 -> 5 1 2 -> 1 2 5
-- 5 2 1 -> 2 1 5 -> 1 5 2

-- 2 5 1 4 3
-- 1 2 3 4 5
--
-- 1 2 3 4 5
-- 3 1 5 4 2

-- 5 2 1 4 3
-- 1 2 3 4 5
--
-- 1 2 3 4 5
-- 3 2 5 4 1

calc' :: [Int] -> Int -> [[Int]] -> [[Int]]
calc' [] j acc = acc
calc' lst j acc =
  let (mn,i) = minimum $ zip lst [1..]
      lst' = delete mn lst
  in
    if i == 1 then calc' lst' (j+1) acc
    else calc' lst' (j+1) ([j+1,j+i,i-1]:acc)

calc :: [Int] -> [[Int]]
calc lst = reverse $ calc' lst 0 []

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let n = read line :: Int
    line <- getLine
    let lst = map read $ words line :: [Int]
    let ans = calc lst
    putStrLn $ show $ length ans
    forM_ ans $ \item -> do
      putStrLn $ intercalate " " $ map show item

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  diff -sdu -- <(cat -- input.txt | ./a.out) output.txt)

import Prelude
import System.IO
import Control.Monad
import Data.List
import Data.Maybe

import Debug.Trace
-- trF showFunc x = trace msg x  where  msg = "\n" ++ "trF: " ++ showFunc x ++ "."
-- tr s x = trace msg x  where  msg = "\n" ++ "tr: " ++ s ++ ": " ++ show x ++ "."

main :: IO ()
main = do
    hSetBuffering stdout NoBuffering

    t <- readLn
    tcs <- replicateM t ((map read . words . head . tail) <$> replicateM 2 getLine) :: IO [[Int]]

    (hPutStr stderr . unlines . map show) tcs

    -- (hPutStr stderr . unlines . map (show . filter (not.isNoop) . solve 1)) tcs
    (hPutStr stderr . concatMap (showAns . filter (not.isNoop) . solve 1)) tcs

showAns xs = show (length xs) ++ "\n" ++ (unlines . map showOp) xs

solve _   [] = []
solve off xs = fix off op : solve (off+1) (tail $ shift xs op)
  where
    i = fromJust . findIndex (== minimum xs) $ xs

    op = (0, i, i)

fix n (l, r, d) = (l+n, r+n, d)

isNoop (_l, _r, d) = (d == 0)

showOp (l, r, d) = show l ++ " " ++ show r ++ " " ++ show d

shift xs (l,r,d) = beg ++ (shiftL mid d) ++ end
  where
    (beg, midEnd) = splitAt l       xs
    (mid, end   ) = splitAt (r-l+1) midEnd

shiftL xs 0 = xs
shiftL xs d = shiftL (tail xs ++ [head xs]) (d-1)

import Control.Monad ( replicateM_, forM_ )
import Data.List ( intercalate )

calc n i a
  | n == i + 1 = [[]]
  | id == 0 = calc n (i + 1) na
  | otherwise = [i + 1, n, id] : calc n (i + 1) na
  where
      id = snd $ minimum $ zip a [1..]
      na = tail $ drop id a <> take id a

solve = do
    [n] <- map read.words <$> getLine :: IO [Int]
    a <- map read.words <$> getLine :: IO [Int]
    let f = init $ calc n 0 a
    print (length f)
    forM_ f $ \item -> do
      putStrLn $ unwords $ map show item

main = readLn >>= flip replicateM_ solve

import Control.Monad
import Data.List

-- 2 5 1 -> 5 1 2 -> 1 2 5
-- 5 2 1 -> 2 1 5 -> 1 5 2

-- 2 5 1 4 3
-- 1 2 3 4 5
--
-- 1 2 3 4 5
-- 3 1 5 4 2

-- 5 2 1 4 3
-- 1 2 3 4 5
--
-- 1 2 3 4 5
-- 3 2 5 4 1

calc' :: [Int] -> Int -> [[Int]] -> [[Int]]
calc' [] j acc = acc
calc' lst j acc =
  let (mn,i) = minimum $ zip lst [1..]
      lst' = delete mn lst
  in
    if i == 1 then calc' lst' (j+1) acc
    else calc' lst' (j+1) ([j+1,j+i,j+i-1]:acc)

calc :: [Int] -> [[Int]]
calc lst = reverse $ calc' lst 0 []

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let n = read line :: Int
    line <- getLine
    let lst = map read $ words line :: [Int]
    let ans = calc lst
    putStrLn $ show $ length ans
    forM_ ans $ \item -> do
      putStrLn $ intercalate " " $ map show item


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

import Control.Monad
import Data.Array.Base
import Data.Array.IO (IOUArray)
import qualified Data.ByteString.Char8 as B
import Data.IORef
import Data.Maybe (fromJust)

rep :: Int -> Int -> (Int -> IO ()) -> IO ()
rep !m !n f=go m where go !i=when(i<n)$f i>>go(i+1)

main :: IO ()
main = do
  n <- readLn
  bs <- fmap(map(fst.fromJust.B.readInt).B.words)B.getLine
  dp <- newArray (0,n*n-1) 0 :: IO (IOUArray Int Int)
  v2i <- newArray (0,1000000) (-1) :: IO (IOUArray Int Int)

  forM_ (zip[0..]bs) $ \(i,b)-> do
    i0 <- unsafeRead v2i b
    when (i0 < 0) $ unsafeWrite v2i b i

  xs <- mapM (unsafeRead v2i) bs

  let get (i,j) = unsafeRead dp (i*n+j)
      put (i,j) v = unsafeWrite dp (i*n+j) v

  forM_ (zip[0..]xs) $ \(i,x) -> do
      if i==x
         then do
           put (i,i) 1
           rep 0 i $ \j -> do
             put (j,x) 2
         else do
           rep 0 i $ \j -> do
             xj <- get (x,j)
             jx <- get (j,x)
             put (j,x) $ max jx (xj+1)

  ans <- newIORef 0 :: IO (IORef Int)

  rep 0 (n*n) $ \ij-> do
    dpij <- unsafeRead dp ij
    x <- readIORef ans
    writeIORef ans $! max dpij x

  readIORef ans >>= print

import Data.List
import Data.Tuple
import GHC.Exts
solve l = maximum $ (2 `min` length l) : (map length s) ++ [ f x y | x@(_:_:_) : t <- tails s, y<-t ]
  where
   s = reverse . sortWith length . groupWith fst $ zip l [0..]
   f x y = length . group $ map fst $ sortWith snd $  x ++ y

main = interact $ show . solve .tail . words

import Data.List
import GHC.Exts
solve l = maximum $ 2 `min` length l : map length s ++ [length . group $ map fst $ sortWith snd $  x ++ y  | x <- s, length x > 1, y<-s, y/=x ]
 where s = groupWith fst $ zip l [0..]

main = interact $ show . solve .tail . words

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

import Control.Monad
import Data.Array.Base
import Data.Array.IO (IOUArray)
import qualified Data.ByteString.Char8 as B
import Data.IORef
import Data.Maybe (fromJust)

rep :: Int -> Int -> (Int -> IO ()) -> IO ()
rep !m !n f=go m where go !i=when(i<n)$f i>>go(i+1)

main :: IO ()
main = do
  n <- readLn
  bs <- fmap(map(fst.fromJust.B.readInt).B.words)B.getLine
  dp <- newArray (0,n*n-1) 0 :: IO (IOUArray Int Int)
  v2i <- newArray (0,1000000) (-1) :: IO (IOUArray Int Int)
  i2v <- newListArray (0,n-1) bs :: IO (IOUArray Int Int)

  forM_ (zip[0..]bs) $ \(i,b)-> do
    i0 <- unsafeRead v2i b
    when (i0 < 0) $ unsafeWrite v2i b i

  forM_ (zip[0..]bs) $ \(i,b)-> do
    i0 <- unsafeRead v2i b
    if i0<i
       then do
         rep 0 i $ \j-> do
           vj <- unsafeRead i2v j
           j0 <- unsafeRead v2i vj
           when (j0==j) $ do
             dpij <- unsafeRead dp $ n*i0+j
             unsafeWrite dp (n*j+i0) $ dpij+1
       else do
         unsafeWrite dp (i*n+i) 1
         rep 0 i $ \j-> do
           unsafeWrite dp (j*n+i) 2

  ans <- newIORef 0 :: IO (IORef Int)

  rep 0 (n*n) $ \ij-> do
    dpij <- unsafeRead dp ij
    x <- readIORef ans
    writeIORef ans $! max dpij x

  readIORef ans >>= print

{-# OPTIONS_GHC -O2 #-}

import Control.Applicative
import Control.Monad
import Data.Array.Base
import Data.Array.IO (IOUArray)
import qualified Data.ByteString.Char8 as B
import Data.IORef
import Data.Maybe

main :: IO ()
main = do
  n <- readLn :: IO Int
  bs <- fmap(map(fst.fromJust.B.readInt).B.words)B.getLine
  dp <- newArray (0,4000*4000-1) 0 :: IO (IOUArray Int Int)
  v2i <- newArray (0,1000000) (-1) :: IO (IOUArray Int Int)

  forM_ (zip[0..]bs) $ \ (i,b)-> do
    visited <- unsafeRead v2i b
    when (visited < 0) $ do
      unsafeWrite v2i b i
      unsafeWrite dp (i*4000+i) 1

  forM_ bs $ \b-> do
    i <- unsafeRead v2i b
    forM_ [0..3999] $ \j-> do
      dpij <- unsafeRead dp $ 4000*i+j
      unsafeWrite dp (4000*i+j) $ dpij+1

  ans <- newIORef 0 :: IO (IORef Int)

  forM_ [0..4000*4000-1] $ \i-> do
    ai <- unsafeRead dp i
    x <- readIORef ans
    writeIORef ans $! max ai x

  readIORef ans >>= print

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

import Control.Monad
import Data.Array.Base
import Data.Array.IO (IOUArray)
import qualified Data.ByteString.Char8 as B
import Data.IORef
import Data.Maybe (fromJust)

rep :: Int -> Int -> (Int -> IO ()) -> IO ()
rep !m !n f=go m where go !i=when(i<n)$f i>>go(i+1)

main :: IO ()
main = do
  _ <- getLine
  bs <- fmap(map(fst.fromJust.B.readInt).B.words)B.getLine
  dp <- newArray (0,4000*4000-1) 0 :: IO (IOUArray Int Int)
  v2i <- newArray (0,1000000) (-1) :: IO (IOUArray Int Int)

  forM_ (zip[0..]bs) $ \(i,b)-> do
    visited <- unsafeRead v2i b
    when (visited < 0) $ unsafeWrite v2i b i

  forM_ (zip[0..]bs) $ \(i,b)-> do
    i0 <- unsafeRead v2i b
    if i0<i
       then do
         rep 0 i $ \j-> do
           dpij <- unsafeRead dp $ 4000*i0+j
           unsafeWrite dp (4000*j+i0) $ dpij+1
       else do
         unsafeWrite dp (i*4000+i) 1
         rep 0 i $ \j-> do
           unsafeWrite dp (j*4000+i) 2

  ans <- newIORef 0 :: IO (IORef Int)

  rep 0 (4000*4000) $ \i-> do
    ai <- unsafeRead dp i
    x <- readIORef ans
    writeIORef ans $! max ai x

  readIORef ans >>= print

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

import Control.Applicative
import Control.Monad
import Data.Array.Base
import Data.Array.IO (IOUArray)
import qualified Data.ByteString.Char8 as B
import Data.IORef
import Data.Maybe (fromJust)

rep :: Int -> Int -> (Int -> IO ()) -> IO ()
rep !m !n f = go m
   where
     go !i
       | i<n = f i >> go (i+1)
       | otherwise = return ()

main :: IO ()
main = do
  _ <- getLine
  bs <- fmap(map(fst.fromJust.B.readInt).B.words)B.getLine
  dp <- newArray (0,4000*4000-1) 0 :: IO (IOUArray Int Int)
  v2i <- newArray (0,1000000) (-1) :: IO (IOUArray Int Int)

  forM_ (zip[0..]bs) $ \ (i,b)-> do
    visited <- unsafeRead v2i b
    if visited < 0
       then unsafeWrite v2i b i
       else unsafeWrite dp (i*4000+i) 1

  forM_ bs $ \b-> do
    i <- unsafeRead v2i b
    let !k = 4000*i
    rep 0 4000 $ \j-> do
      dpij <- unsafeRead dp $ k+j
      unsafeWrite dp (k+j) $ max 2 $ dpij+1

  ans <- newIORef 0 :: IO (IORef Int)

  rep 0 (4000*4000) $ \i-> do
    ai <- unsafeRead dp i
    x <- readIORef ans
    writeIORef ans $! max ai x

  readIORef ans >>= print