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

main = do
  n <- readLn :: IO Int
  names <- replicateM n getLine
  matchResult <- replicateM (n*(n-1)`div`2) getLine
  let mr = concatMap readMatchResult matchResult
      mr1 = sortBy (comparing (fst.fst)) mr
      mr2 = groupBy (on (==) (fst.fst)) mr1
      mr3 = map toScore mr2
      mr4 = reverse $ sortBy cmp mr3
  --mapM_ print mr2
  --mapM_ print mr3
  mapM_ putStrLn . sort . map fst4 $ take (n`div`2) mr4
  where
    fst4 (x,_,_,_) = x
    rev ((a,b),(c,d)) = ((b,a),(d,c))
    split c [] = []
    split c cs = let (a,b) = span (c/=) cs
                     tail' [] = []
                     tail' (a:as) = as
                 in a : split c (tail' b)
    readMatchResult :: String -> [((String,String),(Int,Int))]
    readMatchResult cs = let (ts:ss:[]) = words cs
                             (t1:t2:[]) = split '-' ts
                             (s1:s2:[]) = map read $ split ':' ss
                             res = ((t1,t2),(s1,s2))
                         in [res,rev res]
    toScore :: [((String,String),(Int,Int))] -> (String,Int,Int,Int)
    toScore cs = let (x,y,z) = f (0,0,0) cs
                     name = fst.fst.head$cs
                 in (name,x,y,z)
      where
        f x [] = x
        f (x,y,z) ((_,(s,m)):as)
          | s>m = f (x+3,y+s-m,z+s) as
          | s==m = f (x+1,y+s-m,z+s) as
          | s<m = f (x,y+s-m,z+s) as
    cmp :: (String,Int,Int,Int) -> (String,Int,Int,Int) -> Ordering
    cmp (_,x1,y1,z1) (_,x2,y2,z2)
      | x1 /= x2 = compare x1 x2
      | y1 /= y2 = compare y1 y2
      | z1 /= z2 = compare z1 z2

 import Data.List

 parse :: String -> (String, String, Int, Int)
 parse s = let s0 = s; a = takeWhile (/='-') s0 in
                let s1 = drop (length a + 1) s0; b = takeWhile (/=' ') s1 in
                    let s2 = drop (length b + 1) s1; c = takeWhile (/=':') s2 in
                        let s3 = drop (length c + 1) s2; d = s3 in
                            (a, b, read c, read d)

 table :: [String] -> [(String, String, Int, Int)] -> [String]
 table teams results = snd $ unzip $ sort $ zip scores teams
    where scores = map (score results) teams
            where score results team = (sum [sc result | result <- resultsOfThisTeam],
                                    sum [c - d | (_, _, c, d) <- resultsOfThisTeam],
                                    sum [c | (_, _, c, _) <- resultsOfThisTeam])
                    where sc (a, b, c, d) = case compare c d of GT -> 3
                                                                EQ -> 1
                                                                LT -> 0
                          resultsOfThisTeam = [result | result@(a, _, _, _) <- results, a == team]

 solve :: Int -> [String] -> [String] -> [String]
 solve n teams matches = sort $ drop (n `div` 2) (table teams results)
    where singleResults = map parse matches
          results = singleResults ++ map (\(a, b, c, d) -> (b, a, d, c)) singleResults

 main = do
    contents <- getContents
    let n = read $ head $ lines contents
    let teams = take n $ drop 1 $ lines contents
    let matches = take (n * (n - 1) `div` 2) $ drop (n + 1) $ lines contents
    mapM putStrLn (solve n teams matches)

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

fst3 (a, b, c) = a
snd3 (a, b, c) = b
trd3 (a, b, c) = c
frt4 (a, b, c, d) = d

toMatch ss =
    let (t1, '-':ss2) = break (== '-') ss
        (t2, ' ':ss3) = break (== ' ') ss2
        [(n1, ':':ss4)] = reads ss3
        n2 = read ss4
    in  (t1, t2, n1, n2)

main = do
  n <- readLn
  ns <- replicateM n getLine
  ms <- replicateM (n*(n-1)`div`2) $ toMatch <$> getLine
  let ms' = reverse $ sort [ accum (catMaybes [ conv name match | match <- ms ]) | name <- ns]
  mapM_ putStrLn $ sort $ map frt4 $ take (n `div` 2) ms'
    where
      conv name (t1, t2, n1, n2)
          | t1 == name = Just (name, n1, n2)
          | t2 == name = Just (name, n2, n1)
          | otherwise = Nothing
      accum :: [(String, Int, Int)] -> (Int, Int, Int, String)
      accum ls =
          let sco = sum $ map snd3 ls
              mis = sum $ map trd3 ls
              p = sum $ zipWith point (map snd3 ls) (map trd3 ls)
              name = fst3 $ head ls
          in  (p, sco-mis, sco, name)
      point n1 n2 | n1 < n2 = 0
                  | n1 > n2 = 3
                  | otherwise = 1

import Text.ParserCombinators.Parsec
import Data.Map.Strict hiding (foldl)
import Data.Function( on)
import Data.List( sortBy, intercalate, sort)
import Control.Applicative( (<$>))

main = do
    winScores <- return . (parse parser "(stdin)") =<< getContents
    case winScores  of
	Left _	    -> fail "Parsing failed."
	Right ws    -> do
	    let performance = foldl proc empty $ concat ws
		  where proc mp (team,po) = insertWith plus team po mp
			plus (w1,d1,g1) (w2,d2,g2) = (w1+w2,d1+d2,g1+g2)
		r = toList performance
		winner = take half $ sortBy (descOrder `on` snd) r
		  where
		    half = length r `div` 2
		    descOrder = flip compare
	    putStr $ intercalate "\n" . sort $ fst <$> winner

parser = do
    sz <- szTeams
    spaces
    count sz name
    let szRecords = sz*(sz-1)`div`2
    count szRecords matchRecord

szTeams = many1 digit >>= return . read

name = do
    v <- many1 letter
    spaces
    return v

matchRecord = do
    (t1, t2) <- card
    spaces
    (s1, s2) <- score
    spaces
    return $ if s1>s2
	then [(t1,(3::Int,s1-s2,s1)),(t2,(0,s2-s1,s2))]
	else if s1<s2
		then [(t1,(0,s1-s2,s1)),(t2,(3,s2-s1,s2))]
		else [(t1,(1,0,s1)),(t2,(1,0,s2))]
card = do
    team1 <- name
    char '-'
    team2 <- name
    return (team1, team2)

score = do
    score1 <- many1 digit
    char ':'
    score2 <- many1 digit
    return (read score1, read score2)

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

main = do
  n <- readLn :: IO Int
  names <- replicateM n getLine
  matchResult <- replicateM (n*(n-1)`div`2) getLine
  let mr = concatMap readMatchResult matchResult
      mr1 = sortBy (comparing (fst.fst)) mr
      mr2 = groupBy (on (==) (fst.fst)) mr1
      mr3 = map toScore mr2
      mr4 = reverse $ sortBy cmp mr3
  mapM_ print mr2
  mapM_ print mr3
  mapM_ putStrLn . sort . map fst4 $ take (n`div`2) mr4
  where
    fst4 (x,_,_,_) = x
    rev ((a,b),(c,d)) = ((b,a),(d,c))
    split c [] = []
    split c cs = let (a,b) = span (c/=) cs
                     tail' [] = []
                     tail' (a:as) = as
                 in a : split c (tail' b)
    readMatchResult :: String -> [((String,String),(Int,Int))]
    readMatchResult cs = let (ts:ss:[]) = words cs
                             (t1:t2:[]) = split '-' ts
                             (s1:s2:[]) = map read $ split ':' ss
                             res = ((t1,t2),(s1,s2))
                         in [res,rev res]
    toScore :: [((String,String),(Int,Int))] -> (String,Int,Int,Int)
    toScore cs = let (x,y,z) = f (0,0,0) cs
                     name = fst.fst.head$cs
                 in (name,x,y,z)
      where
        f x [] = x
        f (x,y,z) ((_,(s,m)):as)
          | s>m = f (x+3,y+s-m,z+s) as
          | s==m = f (x+1,y+s-m,z+s) as
          | s<m = f (x,y+s-m,z+s) as
    cmp :: (String,Int,Int,Int) -> (String,Int,Int,Int) -> Ordering
    cmp (_,x1,y1,z1) (_,x2,y2,z2)
      | x1 /= x2 = compare x1 x2
      | y1 /= y2 = compare y1 y2
      | z1 /= z2 = compare z1 z2

 import Data.List

 parse :: String -> (String, String, Int, Int)
 parse s = let s0 = s; a = takeWhile (/='-') s0 in
                let s1 = drop (length a + 1) s0; b = takeWhile (/=' ') s1 in
                    let s2 = drop (length b + 1) s1; c = takeWhile (/=':') s2 in
                        let s3 = drop (length c + 1) s2; d = s3 in
                            (a, b, read c, read d)

 table :: [String] -> [(String, String, Int, Int)] -> [String]
 table teams results = snd $ unzip $ sort $ zip scores teams
    where scores = map (score results) teams
            where score results team = (sum [sc result | result <- resultsOfThisTeam],
                                    sum [c - d | (_, _, c, d) <- resultsOfThisTeam],
                                    sum [c | (_, _, c, _) <- resultsOfThisTeam])
                    where sc (a, b, c, d) = case compare c d of GT -> 3
                                                                EQ -> 1
                                                                LT -> 0
                          resultsOfThisTeam = [result | result@(a, _, _, _) <- results, a == team]

 solve :: Int -> [String] -> [String] -> [String]
 solve n teams matches = drop (n `div` 2) (table teams results)
    where singleResults = map parse matches
          results = singleResults ++ map (\(a, b, c, d) -> (b, a, d, c)) singleResults

 main = do
    contents <- getContents
    let n = read $ head $ lines contents
    let teams = take n $ drop 1 $ lines contents
    let matches = take (n * (n - 1) `div` 2) $ drop (n + 1) $ lines contents
    mapM putStrLn (solve n teams matches)


import Control.Monad
import Data.Array
import Data.Bits
import Data.List
import Data.Maybe
import qualified Data.IntMap as M
import qualified Data.ByteString.Char8 as C

data Color
  = Red
  | Black
  deriving (Enum, Eq, Show)

switch Red = Black
switch Black = Red

type Edge = (Int, Int)
type Vertices = [Int]
type Graph = Array Int Vertices

toGraph :: Int -> [Edge] -> Graph
toGraph n = accumArray (flip (:)) [] (1, n)

color :: Int -> Graph -> Array Int Color
color n e = array (1, n) $ M.assocs $ foldl (dfs Red) M.empty [1 .. n]
  where
    dfs t c v
      | M.member v c  = c
      | otherwise     = foldl (dfs (switch t)) (M.insert v t c) $ e!v

try12 :: Int -> Graph -> Vertices -> Vertices -> Maybe Vertices
try12 n e r b
  | null u    = Nothing
  | otherwise = Just $ (u':v') ++ (delete u' r) ++ (b \\ v')
  where
    m = length b
    u = [i | i <- r, length (e!i) <= m - 2]
    u' = head u
    v = [j | j <- b, notElem u' $ e!j]
    v' = take 2 v

try42 :: Int -> Graph -> Vertices -> Vertices -> Maybe Vertices
try42 n e r b
  | length v' < 6 = Nothing
  | otherwise     = Just $ v' ++ (r \\ v') ++ (b \\ v')
  where
    m = length b
    x = foldr1 xor b
    e' = toGraph n [(foldr xor x $ e!i, i) | i <- r, length (e!i) == m - 1]
    v' = concat $ take 2 [i: take 2 j | (i, j) <- assocs e', length j >= 2]

yes :: Vertices -> IO ()
yes v = putStrLn $ ("YES\n" ++) $ unwords $ map show $ elems w
  where
    n = length v
    w = array (1,n) $ zip v $ concatMap (replicate 3) [1 ..]

no :: IO ()
no = putStrLn "NO"

solve :: Int -> Graph -> IO ()
solve n e =
  if m == 0 then yes $ r ++ b
  else case try12 n e x y of
            Just z  -> yes z
            Nothing -> case try42 n e x y of
                            Just z  -> yes z
                            Nothing -> no
  where
    c = color n e
    r = [i | (i, e) <- assocs c, e == Red]
    b = [i | (i, e) <- assocs c, e == Black]
    m = length r `mod` 3
    (x, y) = if m /= 2 then (r, b) else (b, r)

main = do
  [n, m] <- get
  e <- replicateM m get
  solve n $ toGraph n $ concat [[(i, j), (j, i)] | [i, j] <- e]
  where
    get = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine

import Control.Monad
import Data.Array
import Data.Bits
import Data.List
import Data.Maybe
import qualified Data.IntMap as M
import qualified Data.ByteString.Char8 as C

toGraph n = accumArray (flip (:)) [] (1, n)

color n e = array (1, n) $ M.assocs $ foldl (dfs True) M.empty [1 .. n]
  where
    dfs t c v
      | M.member v c = c
      | True = foldl (dfs (not t)) (M.insert v t c) $ e!v

try12 n e r b
  | null u = Nothing
  | True = Just $ (u':v') ++ (delete u' r) ++ (b \\ v')
  where
    m = length b
    u = [i | i <- r, length (e!i) <= m - 2]
    u' = head u
    v = [j | j <- b, notElem u' $ e!j]
    v' = take 2 v

try42 n e r b
  | length v' < 6 = Nothing
  | True = Just $ v' ++ (r \\ v') ++ (b \\ v')
  where
    m = length b
    x = foldr1 xor b
    e' = toGraph n [(foldr xor x $ e!i, i) | i <- r, length (e!i) == m - 1]
    v' = concat $ take 2 [i: take 2 j | (i, j) <- assocs e', length j >= 2]

yes v = putStrLn $ ("YES\n" ++) $ unwords $ map show $ elems w
  where
    n = length v
    w = array (1,n) $ zip v $ concatMap (replicate 3) [1 ..]

solve n e =
  if m == 0
  then
    yes $ r ++ b
  else
    case try12 n e x y of
      Just z -> yes z
      _      ->
        case try42 n e x y of
          Just z -> yes z
          _      -> putStrLn "NO"
  where
    c = color n e
    r = [i | (i, e) <- assocs c, e]
    b = [i | (i, e) <- assocs c, not e]
    m = length r `mod` 3
    (x, y) = if m /= 2 then (r, b) else (b, r)

get = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine

main = do
  [n, m] <- get
  e <- replicateM m get
  solve n $ toGraph n $ concat [[(i, j), (j, i)] | [i, j] <- e]


main = getContents >>= putStrLn . solve . read . head . words

solve 0 = []
solve n = (if n `mod` 2 == 0 then '0' else '1') : solve (n - 1)

import Data.List.Split as Split
import Data.Bits
import Data.List

stringToInt s = read s :: Int

int_arr = map stringToInt . words

main = do
  n_m <- getLine
  let [n, m] = int_arr n_m
  ss <- (read_strings m)
  let num_arr = map show (most_beauty n (map int_arr ss))
  -- putStrLn (intercalate " " num_arr)
  putStrLn (foldl (\acc s -> acc ++ s) [] num_arr)

read_strings 0 = return []
read_strings n = do
  s <- getLine
  ss <- (read_strings (n - 1))
  return (s:ss)

most_beauty :: Int -> [[Int]] -> [Int]
most_beauty n _ | n > 16 = [x `rem` 2 | x <- [1..n]]
most_beauty n lr_arr =
  variant n lr_arr (2 ^ n) (repr n (2 ^ n)) 0

variant :: Int -> [[Int]] -> Int -> [Int] -> Int -> [Int]
variant _ _ 0 best _best_score = best
variant n lr_arr v1 best best_score =
  let rv = repr n v1
  in case is_suitable rv of
    False -> variant n lr_arr (v1 - 1) best best_score
    True ->
      let b = beauty_sum rv lr_arr
      in if b > best_score
        then variant n lr_arr (v1 - 1) rv b
        else variant n lr_arr (v1 - 1) best best_score

repr :: Int -> Int -> [Int]
repr n v = [(bit 0).&.(shift v (1 - x)) | x <- (reverse [1..n])]

beauty_sum :: [Int] -> [[Int]] -> Int
beauty_sum mask lr_arr = sum (map (beauty mask) lr_arr)

beauty :: [Int] -> [Int] -> Int
beauty mask [l, r] =
  let m = take (r - l + 1) $ drop (l - 1) mask
  in (length $ filter (== 1) m) * (length $ filter (== 0) m)

is_suitable (1:1:1:_) = False
is_suitable (0:0:0:_) = False
is_suitable [] = True
is_suitable (x:xs) = is_suitable xs

-- suitable _n _mask [False, False, False] = False
-- suitable _n _mask [True, True, True] = False
-- suitable 0 _mask _ = True
-- suitable n mask prev =
--   let p = testBit mask 0
--       prev1 = case prev of
--         [p1, p2, p3] -> [p, p1, p2]
--         _ -> (p:prev)
--   in suitable (n - 1) (shift mask (-1)) prev1

-- possible n_d x_n =
--   let [_n, d] = map stringToInt $ Split.splitOn " " n_d
--       x = map stringToInt $ Split.splitOn " " x_n
--   in show (2 + (behind d x))

-- behind d (x1:[]) = 0
-- behind d (x1:x2:xs) =
--   case compare (2*d) (x2 - x1) of
--     EQ -> 1 + behind d (x2:xs)
--     GT -> behind d (x2:xs)
--     LT -> 2 + behind d (x2:xs)

import Data.List.Split as Split
import Data.Bits
import Data.List

stringToInt s = read s :: Int

int_arr = map stringToInt . words

main = do
  n_m <- getLine
  let [n, m] = int_arr n_m
  ss <- (read_strings m)
  let num_arr = map show (most_beauty n (map int_arr ss))
  -- putStrLn (intercalate " " num_arr)
  putStrLn (foldl (\acc s -> acc ++ s) [] num_arr)

read_strings 0 = return []
read_strings n = do
  s <- getLine
  ss <- (read_strings (n - 1))
  return (s:ss)

most_beauty :: Int -> [[Int]] -> [Int]
most_beauty n lr_arr =
  variant n lr_arr (2 ^ n) (repr n (2 ^ n)) 0

variant :: Int -> [[Int]] -> Int -> [Int] -> Int -> [Int]
variant _ _ 0 best _best_score = best
variant n lr_arr v1 best best_score =
  let rv = repr n v1
  in case is_suitable rv of
    False -> variant n lr_arr (v1 - 1) best best_score
    True ->
      let b = beauty_sum rv lr_arr
      in if b > best_score
        then variant n lr_arr (v1 - 1) rv b
        else variant n lr_arr (v1 - 1) best best_score

repr :: Int -> Int -> [Int]
repr n v = [(bit 0).&.(shift v (1 - x)) | x <- (reverse [1..n])]

beauty_sum :: [Int] -> [[Int]] -> Int
beauty_sum mask lr_arr = sum (map (beauty mask) lr_arr)

beauty :: [Int] -> [Int] -> Int
beauty mask [l, r] =
  let m = take (r - l + 1) $ drop (l - 1) mask
  in (length $ filter (== 1) m) * (length $ filter (== 0) m)

is_suitable (1:1:1:_) = False
is_suitable (0:0:0:_) = False
is_suitable [] = True
is_suitable (x:xs) = is_suitable xs

-- suitable _n _mask [False, False, False] = False
-- suitable _n _mask [True, True, True] = False
-- suitable 0 _mask _ = True
-- suitable n mask prev =
--   let p = testBit mask 0
--       prev1 = case prev of
--         [p1, p2, p3] -> [p, p1, p2]
--         _ -> (p:prev)
--   in suitable (n - 1) (shift mask (-1)) prev1

-- possible n_d x_n =
--   let [_n, d] = map stringToInt $ Split.splitOn " " n_d
--       x = map stringToInt $ Split.splitOn " " x_n
--   in show (2 + (behind d x))

-- behind d (x1:[]) = 0
-- behind d (x1:x2:xs) =
--   case compare (2*d) (x2 - x1) of
--     EQ -> 1 + behind d (x2:xs)
--     GT -> behind d (x2:xs)
--     LT -> 2 + behind d (x2:xs)

import Data.List.Split as Split
import Data.Bits

stringToInt s = read s :: Int

int_arr = map stringToInt . words

main = do
  n_m <- getLine
  let [n, m] = int_arr n_m
  ss <- (read_strings m)
  let num_arr = map show (most_beauty n (map int_arr ss))
  putStrLn (foldl (\acc s -> acc ++ s ++ " ") [] num_arr)

read_strings 0 = return []
read_strings n = do
  s <- getLine
  ss <- (read_strings (n - 1))
  return (s:ss)

most_beauty :: Int -> [[Int]] -> [Int]
most_beauty n lr_arr =
  variant n lr_arr (2 ^ n) (repr n (2 ^ n)) 0

variant :: Int -> [[Int]] -> Int -> [Int] -> Int -> [Int]
variant _ _ 0 best _best_score = best
variant n lr_arr v1 best best_score =
  let rv = repr n v1
  in case is_suitable rv of
    False -> variant n lr_arr (v1 - 1) best best_score
    True ->
      let b = beauty_sum rv lr_arr
      in if b > best_score
        then variant n lr_arr (v1 - 1) rv b
        else variant n lr_arr (v1 - 1) best best_score

repr :: Int -> Int -> [Int]
repr n v = [(bit 0).&.(shift v (1 - x)) | x <- (reverse [1..n])]

beauty_sum :: [Int] -> [[Int]] -> Int
beauty_sum mask lr_arr = sum (map (beauty mask) lr_arr)

beauty :: [Int] -> [Int] -> Int
beauty mask [l, r] =
  let m = take (r - l + 1) $ drop (l - 1) mask
  in (length $ filter (== 1) m) * (length $ filter (== 0) m)

is_suitable (1:1:1:_) = False
is_suitable (0:0:0:_) = False
is_suitable [] = True
is_suitable (x:xs) = is_suitable xs

-- suitable _n _mask [False, False, False] = False
-- suitable _n _mask [True, True, True] = False
-- suitable 0 _mask _ = True
-- suitable n mask prev =
--   let p = testBit mask 0
--       prev1 = case prev of
--         [p1, p2, p3] -> [p, p1, p2]
--         _ -> (p:prev)
--   in suitable (n - 1) (shift mask (-1)) prev1

-- possible n_d x_n =
--   let [_n, d] = map stringToInt $ Split.splitOn " " n_d
--       x = map stringToInt $ Split.splitOn " " x_n
--   in show (2 + (behind d x))

-- behind d (x1:[]) = 0
-- behind d (x1:x2:xs) =
--   case compare (2*d) (x2 - x1) of
--     EQ -> 1 + behind d (x2:xs)
--     GT -> behind d (x2:xs)
--     LT -> 2 + behind d (x2:xs)


import qualified Data.ByteString.Char8 as B
import Control.Arrow
import Data.Maybe

main = B.interact $ B.unlines . map (B.pack . show . ( (9*). pred *** id >>> uncurry (+)) . (\[x,y] ->(x,y)) .  map (fst . fromJust . B.readInteger) . B.words ) . tail . B.lines

main :: IO ()
main = do
  n <- readLn :: IO Int
  doQueries n

doQueries :: Int -> IO ()
doQueries 0 = return ()
doQueries n = do
  l <- getLine
  let (k:x:[]) = map read (words l)
  putStrLn $ show $ (k-1) * 9 + x
  doQueries (n-1)

dig_root :: Int -> Int
dig_root n = n - 9 * ((n-1) `div` 9)

import qualified Data.ByteString.Char8 as B
import Control.Arrow
import Data.Maybe

main = B.interact $ B.unlines . map (B.pack . show . ( (9*). pred *** id >>> uncurry (+)) . (\[x,y] ->(x,y)) .  map (fst . fromJust . B.readInt) . B.words ) . tail . B.lines


import Data.List (intercalate, tails, isPrefixOf, head)
import Control.Monad (replicateM)
import Data.Maybe (fromJust, listToMaybe, catMaybes)

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

solve = do getLine
           s <- getLine
           putStrLn (leastNonSubstring s)

leastNonSubstring s = head $ catMaybes [leastOfLength l | l <- [1..]]
  where leastOfLength l = helper "" l
        helper prefix 0 | isSubstring prefix s = Nothing
                        | otherwise            = Just prefix
        helper prefix l = listToMaybe $ catMaybes [helper (prefix ++ [letter]) (l - 1) | letter <- ['a'..'z']]

isSubstring s t = any id (map (isPrefixOf s) (tails t))

import Control.Monad
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as C
import qualified Data.Set as S
import Data.ByteString.Builder
import System.IO

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

getInts :: IO [Int]
getInts = map parseInt . C.words <$> C.getLine

allStrings :: [String]
allStrings = [] : [string ++ [ch] | string <- allStrings, ch <- ['a' .. 'z']]

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    s <- C.unpack <$> C.getLine
    let check str = not $ any (isPrefixOf str) $ tails s
        result = head $ filter check $ tail allStrings
    return $ string7 result `mappend` charUtf8 '\n'
  hPutBuilder stdout output

import Data.List (tails)

alphabet = map pure ['a'..'z'] :: [String]

gen' :: [String]
gen' = "" : ( (++) <$> gen' <*> alphabet )

gen = drop 1 gen'

isPrefixOf :: (Eq a) => [a] -> [a] -> Bool
isPrefixOf xs ys | length xs <= length ys = and $ zipWith (==) xs ys
                 | otherwise = False

isSubstr :: (Eq a) => [a] -> [a] -> Bool
isSubstr xs ys = or $ map (xs `isPrefixOf`) $ tails ys

doTestCase :: IO ()
doTestCase = do _ <- getLine
                str <- getLine
                putStrLn . head $ dropWhile (`isSubstr` str) gen

main = do t <- readLn :: IO Int
          sequence_ $ replicate t doTestCase

import Data.List

-- generate string
genstr :: [Char] -> Int -> [String]
genstr _ 0 = [""]
genstr chars n = prev ++ (concat $ map jimmy chars)
	where prev = genstr chars (n-1)
	      jimmy c = map ((:) c) prev

jimmy :: String -> String
jimmy str = head $ filter (not.(flip isInfixOf str)) jim
	where (_:jim) = genstr "abcdefghijklmnopqrstuvwxyz" (length str)

hoo :: [String] -> [String]
hoo [] = []
hoo (a:b:cs) = b:(hoo cs)

main = interact $ unlines.(map jimmy).hoo.tail.lines

import Data.List (tails, isPrefixOf)

alphabet = map pure ['a'..'z'] :: [String]

gen' :: [String]
gen' = "" : ( (++) <$> gen' <*> alphabet )

gen = drop 1 gen'

isSubstr :: (Eq a) => [a] -> [a] -> Bool
isSubstr xs ys = or $ map (xs `isPrefixOf`) $ tails ys

doTestCase :: IO ()
doTestCase = do getLine
                str <- getLine
                putStrLn . head $ dropWhile (`isSubstr` str) gen

main = do t <- readLn :: IO Int
          sequence_ $ replicate t doTestCase

import Data.List (tails)

alphabet = map pure ['a'..'z'] :: [String]

gen' :: [String]
gen' = "" : ( (++) <$> gen' <*> alphabet )

gen = drop 1 gen'

isPrefixOf :: (Eq a) => [a] -> [a] -> Bool
isPrefixOf xs ys | length xs < length ys = and $ zipWith (==) xs ys
                 | otherwise = False

isSubstr :: (Eq a) => [a] -> [a] -> Bool
isSubstr xs ys = or $ map (xs `isPrefixOf`) $ init $ tails ys

doTestCase :: IO ()
doTestCase = do _ <- getLine
                str <- getLine
                putStrLn . head $ dropWhile (`isSubstr` str) gen

main = do t <- readLn :: IO Int
          sequence_ $ replicate t doTestCase

import Data.List (tails)

alphabet = map pure ['a'..'z'] :: [String]

gen' :: [String]
gen' = "" : ( (++) <$> gen' <*> alphabet )

gen = drop 1 gen'

isPrefixOf :: (Eq a) => [a] -> [a] -> Bool
isPrefixOf xs ys = and $ zipWith (==) xs ys

isSubstr :: (Eq a) => [a] -> [a] -> Bool
isSubstr xs ys = or $ map (xs `isPrefixOf`) $ init $ tails ys

doTestCase :: IO ()
doTestCase = do _ <- getLine
                str <- getLine
                putStrLn . head $ dropWhile (`isSubstr` str) gen

main = do t <- readLn :: IO Int
          sequence_ $ replicate t doTestCase


sq :: Int -> Int -> (Int, Int)
sq k i
  | k < i = (i - 1, k)
  | otherwise = sq (k-i) (i+1)

--  if (k <= i * (i + 1) `div` 2 + i) then (i, k - i * (i+1) `div` 2) else  sq k (i+1)

solve :: Int -> Int -> [Int] -> Int
solve n k ids = ids !! index
      where
        (a,b) = sq k 0
        index = (b + a - 1) `mod` a

main :: IO ()
main = do
  line <- getLine
  let [n,k] = map read (words line) :: [Int]
  line2 <- getLine
  let ids = map read (words line2) :: [Int]
  print (solve n k ids)

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

natureSum :: Int -> Int
natureSum n | odd n = n * div (n + 2) 2
            | otherwise = div n 2 * (n + 1)

findBottom :: Int -> Int -> Int -> Int -> Int
findBottom l r k b | l > r = b
                   | otherwise = let mid = div (l + r) 2
                                     m = natureSum mid
                                 in if m <= k
                                    then findBottom (mid + 1) r k (max b m)
                                    else findBottom l (mid - 1) k b

solve :: [Int] -> Int
solve (n:k:id) = let m = findBottom 1 (min n 63246) (k - 1) 0
                 in id !! (k - m - 1)

module Main where

-- correct, but SLOW
thisSeq = concat $ map (\x->[0..x]) [0..]

triSeq :: [Integer]
triSeq = map (\x-> x * (x + 1) `div` 2) [1..]

revIdx 0 = 0
revIdx k = k - (last $ takeWhile (<= k) triSeq)

pronounce xs k = xs !! (fromInteger (revIdx k))

main = do
    l0 <- getLine
    l1 <- getLine
    let [_, k] = map (\w->read w::Integer) $ words l0
        ids = map (\w->read w::Integer) $ words l1
    print $ pronounce ids (k - 1)

{-
instructions go here...
-}

module Main where

solve :: [Int] -> Int -> Int -> Int
solve ids k me | k <= me   = ids !! (k - 1)
               | otherwise = solve ids (k - me) (me + 1)

main :: IO ()
main = do
  line <- getLine
  let [n,k] = map read (words line) :: [Int]
  line2 <- getLine
  let ids = map read (words line2) :: [Int]
  putStrLn $ show (solve ids k 1)


import Control.Monad
import Data.Bits

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

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [a, b] <- readInts
    let  x = a .|. b
    print $ xor a x + xor b x

import Control.Arrow ((>>>))
import Data.Bits (Bits (xor))

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

solve :: [Int] -> Int
solve [x, y] = x `xor` y

import Data.Bits
import Control.Monad

main :: IO ()
main = do
  numCases <- getLine
  replicateM_ (read numCases) solveTest

solveTest :: IO ()
solveTest = do
  ln <- getLine
  let lnData = map read (words ln)
  let (a, b) = (lnData !! 0, lnData !! 1)
  let answer = minXor a b
  putStrLn (show answer)

minXor :: Int -> Int -> Int
minXor a b =
  let maxBits = max (bitCount a) (bitCount b)
      bits = reverse $ map (combineBits a b) [0..maxBits]
      x = numFromBits bits
  in sumXor a b x

combineBits :: Int -> Int -> Int -> Bool
combineBits a b n = if (testBit a n) == (testBit b n) then testBit a n else False

numFromBits :: [Bool] -> Int
numFromBits bits = sum (zipWith (*) realBits values)
  where realBits = map (\b -> if b == True then 1 else 0) (reverse bits)
        values = map ((^) 2)[0..length bits - 1]

sumXor :: Int -> Int -> Int -> Int
sumXor a b x = (xor a x) + (xor b x)

bitCount :: Int -> Int
bitCount n = 1 + floor (logBase 2 (fromIntegral n))

import Data.Bits

solve :: IO ()
solve = do
    str <- getLine
    let (a:b:[]) = map read $ words str :: [Int]
    print $ a + b - 2 * (a .&. b)

main = do
    tests_str <- getLine
    sequence $ take (read tests_str) $ repeat solve


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

main = interact $ unlines . parse . lines

parse [st,nd] = sol s n
  where
    (s, n) = (fn $ words st, fn $ words nd)
    fn :: [String] -> [Int]
    fn xs = map read xs

sol [h, a, c] [hh, aa] = (show $ length res) : res
  where
    res = sol' h hh
    sol' h hh
      | hha <= 0  = ["STRIKE"]
      | haa <= 0  = "HEAL" : sol' (haa+c) hh
      | otherwise = "STRIKE" : sol' haa hha
      where haa = h-aa
            hha = hh-a

main = getContents >>= putStr . exec
exec = unlines . (\xs -> show (length xs):xs) . solve . map read . words

solve [h1, a1, c1, h2, a2] = go h1 h2
  where
  go h1 h2
    | h2 <= 0 = []
    | h2 > a1 && a2 >= h1 = "HEAL":go (h1 + c1 - a2) h2
    | otherwise = "STRIKE":go (h1 - a2) (h2 - a1)

import Control.Applicative

main :: IO ()
main = do
    [h1, a1, c1, h2, a2] <- map read . words <$> getContents
    let s = ((h2 - 1) `div` a1) + 1;
        h = head [t | t <- [0 ..], h1 + t * c1 > (t + s - 1) * a2]
    print $ s + h
    putStr . unlines $ replicate h "HEAL" ++ replicate s "STRIKE"

main = getContents >>= putStr . exec
exec = unlines . (\xs -> show (length xs):xs) . solve . map read . words

solve [h1, a1, c1, h2, a2] = go h1 h2
  where
  go h1 h2
    | h2 <= 0 = []
    | a2 >= h1 = "HEAL":go (h1 + c1 - a2) h2
    | otherwise = "STRIKE":go (h1 - a2) (h2 - a1)

import Control.Applicative

main :: IO ()
main = do
    [h1, a1, c1, h2, a2] <- map read . words <$> getContents
    let s = ((h2 - 1) `div` a1) + 1;
        h = head [t | t <- [0 ..], h1 + t * c1 > (s - 1) * a2]
    print $ s + h
    putStr . unlines $ replicate h "HEAL" ++ replicate s "STRIKE"

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

main = interact $ unlines . parse . lines

parse [st,nd] = sol s n
  where
    (s, n) = (fn $ words st, fn $ words nd)
    fn :: [String] -> [Int]
    fn xs = map read xs

sol [h, a, c] [hh, aa] = (show $ length res) : res
  where
    res = sol' h hh
    sol' h hh
      | h <= 0 = ["Problem"]
      | hh <= 0 = []
      | haa <= 0 = "HEAL" : sol' (haa+c) hh
      | otherwise = "STRIKE" : sol' haa (hh-a)
      where haa = h-aa


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

solve :: IO ()
solve = do
    ~[n] <- readInts
    as <- readInts
    let (xs, ys) = partition even as
        sorted = and . (zipWith (<=) <*> tail)
    putStrLn $ if sorted xs && sorted ys then "Yes" else "No"

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

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

import Control.Monad (forM_)
import Data.List (sort, partition)

sorted = and . (zipWith (<=) <*> tail)

main :: IO ()
main = do
    t <- readLn :: IO Int
    forM_ [1 .. t] $ \i -> do
        n <- readLn :: IO Int
        l <- getLine
        let arr = map read (words l) :: [Int]
        let (xs, ys) = partition even arr
        putStrLn $ if sorted xs && sorted ys then "Yes" else "No"

{-# LANGUAGE ParallelListComp #-}
{-# LANGUAGE LambdaCase #-}

module Main where

import           Control.Applicative            ( liftA2 )
import           Control.Monad.State
import qualified Data.ByteString.Lazy.Char8    as C
import           Data.Function                  ( (&) )
import           Data.List
import           Data.Maybe                     ( fromJust )

type Scanner = State [C.ByteString]

scan :: Scanner a -> C.ByteString -> a
scan input = evalState input . C.lines

line :: Scanner C.ByteString
line = get >>= \case
  []     -> error "eof"
  s : ss -> put ss >> return s

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

main :: IO ()
main = C.interact solve

solve :: C.ByteString -> C.ByteString
solve input =
  input
    & scan parse
    & map (format . answer)
    & C.unlines

parse :: Scanner [[Int]]
parse = do
  _ <- line
  many $ do
    _ <- line
    map (fst . fromJust . C.readInt) . C.words <$> line

format :: Bool -> C.ByteString
format True  = C.pack "Yes"
format False = C.pack "No"

answer :: [Int] -> Bool
answer xs = sorted os && sorted es
  where (os, es) = partition odd xs

sorted :: Ord a => [a] -> Bool
sorted xs = and [ x <= x' | x <- xs | x' <- tail xs ]

import Control.Monad (forM_)
import Data.List (sort)

solve [] _ _ = True
solve (x:xs) o e
  | (x `rem` 2) == 0 = if (e > x) then False else solve xs o x
  | (x `rem` 2) == 1 = if (o > x) then False else solve xs x e

main :: IO ()
main = do
  t <- readLn :: IO Int
  forM_ [1 .. t] $ \i -> do
    n <- readLn :: IO Int
    l <- getLine
    let arr = map read (words l) :: [Int]
    putStrLn $ if solve arr  0 0 then "YES" else "NO"

import Control.Monad (forM)
import Data.List

solve t = do
  n <- readLn::IO Int
  arr <- getLine >>= \s -> return $ map (read::String -> Int) (words s)
  let e = [ x | x <- arr, even x]
      o = [ x | x <- arr, odd x ]
  if sort e /= e || sort o /= o then putStrLn "NO" else putStrLn "YES"

main = do
tlen <- readLn :: IO Int
forM [0..(tlen - 1)] (\t -> do solve t)

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

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

mainFun :: SP Builder
mainFun = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    n <- getInt
    a <- replicateM n getInt
    let
      (ae, ao) = partition even a
      isSorted li = and $ zipWith (<=) li (tail li)
    pure $ string7 $ if  isSorted ae && isSorted ao
      then  "Yes\n"
      else  "No\n"

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

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

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

getInt :: Monad m => S m Int
getInt = state $ fromJust . P.readInt . dropSpace
{-
putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'
-}
main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun inp
  P.putStr $ toLazyByteString outp

{-# LANGUAGE ParallelListComp #-}
{-# LANGUAGE LambdaCase #-}

module Main where

import           Control.Applicative            ( liftA2 )
import           Control.Monad.State
import qualified Data.ByteString.Lazy.Char8    as C
import           Data.Function                  ( (&) )
import           Data.List
import           Data.Maybe                     ( fromJust )

type Scanner = State [C.ByteString]

scan :: Scanner a -> C.ByteString -> a
scan input = evalState input . C.lines

line :: Scanner C.ByteString
line = get >>= \case
  []     -> error "eof"
  s : ss -> put ss >> return s

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

main :: IO ()
main = C.interact solve

solve :: C.ByteString -> C.ByteString
solve input = input & scan parse & map (format . answer) & C.unlines

parse :: Scanner [[Int]]
parse = do
  _ <- line
  many $ do
    _ <- line
    map (fst . fromJust . C.readInt) . C.words <$> line

format :: Bool -> C.ByteString
format True  = C.pack "Yes"
format False = C.pack "No"

answer :: [Int] -> Bool
answer xs = all (\(x, x') -> odd $ x + x') swaps
  where
    xs'   = sort xs
    swaps = filter (uncurry (/=)) [ (x, x') | x <- xs | x' <- xs' ]


import Data.List as L

dec :: Int -> Int
dec n = n-1

solve' :: [String] -> Int -> Int -> Int -> Int -> Int
solve' [] ans _ _ _ = ans
solve' (option:others) ans a b c = case option of
                                    "A" -> if a /= 0 then solve' others (ans+1) (dec a) b c
                                                     else solve' others ans a b c
                                    "B" -> if b /= 0 then solve' others (ans+1) a (dec b) c
                                                     else solve' others ans a b c
                                    "C" -> if c /= 0 then solve' others (ans+1) a b (dec c)
                                                     else solve' others ans a b c
                                    "AB" -> if a/=0 && b/=0 then solve' others (ans+1) (dec a) (dec b) c
                                                            else solve' others ans a b c
                                    "BC" -> if b/=0 && c/=0 then solve' others (ans+1) a (dec b) (dec c)
                                                            else solve' others ans a b c
                                    "AC" -> if a/=0 && c/=0 then solve' others (ans+1) (dec a) b (dec c)
                                                            else solve' others ans a b c
                                    "ABC" -> if a/=0 && b/=0 && c/=0 then solve' others (ans+1) (dec a) (dec b) (dec c)
                                                                     else solve' others ans a b c

solve :: Int -> Int -> Int -> Int
solve a b c = solve' ["A", "B", "C", "AB", "BC", "AC", "ABC"] 0 c' b' a'
  where [a', b', c'] = L.sort [a, b, c]

parse :: String -> String
parse input = show $ solve a b c
  where [a, b, c] = map (\x -> read x :: Int) $ words input

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

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

main = getLine >>= test.read
test 0 = return ()
test n = getLine >>= print.solve1.map read.words >> test (n - 1)

solve1 as = length (filter (> 0) as) + solve2 (subtract 1 <$> as)
solve2 as
  | length (filter (> 0) as) < 2 = 0
  | length (filter (> 0) as) == 2 = 1
  | length (filter (> 1) as) == 0 = 1
  | length (filter (> 1) as) == 1 = 2
  | length (filter (> 1) as) == 2 = 2
  | otherwise = 3 + solve3 (subtract 2 <$> as)
solve3 as = fromEnum $ all (> 0) as


main = do
	args <- getContents
	let
		(n:xs) = words args
		ab = cov xs
	mapM print $ map cal ab

cov :: [String] -> [(Int,Int)]
cov [] = []
cov (x:y:remain) = (read x, read y):cov remain

cal :: (Int,Int) -> Int
cal (x,y)
	| y == 0 = 0
	| otherwise = x `div` y + cal (y,(x `mod` y))

module Main where

solve :: Int -> Int -> Int
solve 0 _ = 0
solve _ 0 = 0
solve a b
	| a >= b = (a `div` b) + solve b (a  `mod` b)
	| otherwise = solve b a

printSolution :: IO ()
printSolution = do
	numsStr <- getLine
	let [x, y] = map read $ words numsStr
	print $ solve x y

printNSolutions :: Int -> IO ()
printNSolutions 1 = printSolution
printNSolutions n = do
	printSolution
	printNSolutions (n-1)

main = getLine >>= (printNSolutions . read)

main = do
		args <- getContents
		let
			(n:xs) = words args
			ab = go xs
		mapM print $ map calc ab

go :: [String] -> [ (Int, Int) ]
go [] = []
go (a:b:xs) = (read a, read b):go xs

calc :: (Int, Int) -> Int
calc (a, b)
		| a == 0 = 0
		| b == 0 = 0
		| otherwise = div a b + calc(b, mod a b)

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

ans :: (Int, Int) -> Int
ans (a, b)
    | a == 0 || b == 0 = 0
    | a <= b           = div b a + ans (a, mod b a)
    | otherwise        = ans (b, a)

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

main :: IO()
main = do
    str <- getContents
    let pairs = combine (map read ((tail . words) str))
    printAns (map ans pairs)

module Main where
import Prelude
solve :: Int -> Int -> Int
solve 0 _ = 0
solve _ 0 = 0
solve a b
      | a >= b = (a `div` b) + solve b (a `mod` b)
      | otherwise = solve b a

printSolution :: IO ()
printSolution = do
              numsStr <- getLine
              let nums = map (read :: String -> Int) $ words numsStr
              print $ solve (nums!!0) (nums!!1)

printNSolutions :: Int -> IO ()
printNSolutions 1 = printSolution
printNSolutions n = do
                  printSolution
                  printNSolutions (n-1)

main = do
     nStr <- getLine
     printNSolutions $ (read nStr :: Int)

-- http://codeforces.ru/problemset/problem/267/A
import Data.List
import Control.Monad
-- helpers
getInt = \x -> read x :: Int
getPair str = (getInt $ lst !! 0, getInt $ lst !! 1) where lst = words str

solve :: (Int,Int) -> Int
solve (_,0) = 0
solve (0,_) = 0
solve (x,y) =
  acc' + (solve (mn,rm))
  where
    (mn, mx) = (min x y, max x y)
    (acc', rm) = mx `divMod` mn

main = do
  count <- fmap getInt getLine
  pairs <- replicateM count getLine
  let ps = map getPair pairs
      ss = map solve ps
  mapM_ putStrLn $ map show ss
{-
Заданы два числа. До тех пор, пока оба они больше нуля, с ними производят одну и ту же операцию: из большего числа вычитают меньшее. Если числа равны, то из одного вычитают другое. Например, из пары (4,17) за одну операцию получается пара (4,13), а из пары (5,5) пара (0,5).

Вам задано некоторое количество пар (ai, bi). Сколько операций будет выполнено для каждой из них?

Входные данные
В первой строке задано количество пар n (1  ≤  n  ≤  1000). Далее идут n строк, каждая содержит пару целых положительных чисел ai, bi (1  ≤  ai,  bi  ≤  109).

Выходные данные
Выведите искомое количество операций для каждой пары на отдельной строке.

Примеры тестов
входные данные
2
4 17
7 987654321
выходные данные
8
141093479
-}

f [a,b] | a == 0 = 0 | a > b = f [b, a] | 1 > 0 = div b a + f [mod b a, a]
main = interact $ unlines . map (show . f . map read . words) . tail . lines

f [0, _] = 0
f [a, b]
  | a > b     = f [b, a]
  | otherwise = b `div` a + f [(b `mod` a), a]

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

{-# LANGUAGE ScopedTypeVariables #-}

import Text.Printf
import Data.List
import Data.Functor
import Data.Function
import Control.Monad
import Data.Maybe
import Data.Foldable (foldr', foldr1)
import Prelude
import Control.Monad.State.Strict
import Data.Int
import qualified Data.ByteString.Char8 as B8
import qualified Data.Map.Strict as MapS
import qualified Data.Set as Set

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

calculateGcd a b
    | (a == 0) || (b == 0) = 0
    | otherwise = (calculateGcd b (a `mod` b)) + (a `div` b)

main :: IO ()
main = do
    n <- readB8Int <$> B8.getLine
    replicateM_ n $ do
        [a, b] <- (map readB8Int) <$> B8.words <$> B8.getLine
        printf "%d\n" $ calculateGcd a b

import Control.Monad
gcd' :: [Int] -> Int
gcd' [0, a] = 0
gcd' [a, b] = gcd' [(b`mod`a), a] + b `div` a
main = do
    n <- (fmap read getLine) :: IO Int
    list <- replicateM n $ (fmap (map read.words) getLine) :: IO [[Int]]
    let slist = [[(max a b), (min a b)] | [a, b] <- list]
    mapM print $ map gcd' slist

solve :: Int -> Int -> Int
solve 0 _ = 0
solve _ 0 = 0
solve n1 n2
	| n1 >= n2 = n1 `div` n2 + solve n2 (n1 `mod` n2)
	| otherwise = solve n2 n1

printSolution :: IO ()
printSolution = do
	numsStr <- getLine
	let [n1, n2] = map read $ words numsStr
	print $ solve n1 n2

printNSolutions :: Int -> IO ()
printNSolutions 1 = printSolution
printNSolutions n = do
	printSolution
	printNSolutions (n-1)

main = do
	nStr <- getLine
	printNSolutions $ read nStr

module Main where

solve :: Int -> Int -> Int
solve 0 _ = 0
solve _ 0 = 0
solve a b
      | a >= b = (a `div` b) + solve b (a `mod` b)
      | otherwise = solve b a

printSolution :: IO ()
printSolution = do
              numsStr <- getLine
              let nums = map (read :: String -> Int) $ words numsStr
              print $ solve (nums!!0) (nums!!1)

printNSolutions :: Int -> IO ()
printNSolutions 1 = printSolution
printNSolutions n = do
                  printSolution
                  printNSolutions (n-1)

main = do
     nStr <- getLine
     printNSolutions $ (read nStr :: Int)

main :: IO ()
main = do
	   n <-getLine
	   let num = read n
	   printSolve num

printSolve :: Int -> IO ()
printSolve 1 = solving
printSolve n = do
	           solving
	           printSolve (n-1)

solving :: IO ()
solving = do
	      numargs <- getLine
	      let [arg1, arg2] = map read $ words numargs
	      print $ solve arg1 arg2

solve :: Int -> Int -> Int
solve _ 0 = 0
solve 0 _ = 0
solve a b
      |a >= b = (a `div` b) + solve b (a `mod` b)
      |otherwise = solve b a

{-# LANGUAGE BangPatterns #-}
main=interact$unlines.map show.f.tail.map read.words
f(x:y:rest)=g 0 x y : f rest
f _ = []

g !ans !x !y
  | x==0 || y==0 = ans
  | x < y = let (!q,!r) = quotRem y x in g (ans+q) r x
  | x > y = let (!q,!r) = quotRem x y in g (ans+q) r y
  | otherwise = ans + 1

solve :: Int -> Int -> Int
solve a b
    | a == 0 || b == 0 = 0
    | a >= b = (a `div` b) + solve b (a `mod` b)
    | otherwise = solve b a

printSolution :: IO ()
printSolution = do
    numsStr <- getLine
    let nums = map (read :: String -> Int) $ words numsStr
    print $ solve (nums!!0) (nums!!1)

printNSolutions :: Int -> IO ()
printNSolutions 0 = return ()
printNSolutions n = do
    printSolution
    printNSolutions (n-1)

main = do
    nStr <- getLine
    printNSolutions (read nStr :: Int)

import Data.Char
import Data.List

ans [a,0] = 0
ans [a,b] = a`div`b + ans [b,(a`mod`b)]

main = do
    n<-getLine
    a<-getContents
    let input = map  (map (\x->read x::Int)) (map words $ lines a)
    putStrLn.unlines $ map show $ map ans input

solve :: Int -> Int -> Int
solve 0 _ = 0
solve _ 0 = 0
solve a b
      | a >= b = (a `div` b) + solve b (a `mod` b)
      | otherwise = solve b a

printSolution :: IO ()
printSolution =   do
                     numsStr <- getLine
                     let [ n1, n2 ] = map read $ words numsStr
                     print $ solve n1 n2

printNSolutions :: Int -> IO ()
printNSolutions 1 =  printSolution
printNSolutions n =  do
                     printSolution
                     printNSolutions ( n - 1 )

main = getLine >>= ( printNSolutions . read )

{-# LANGUAGE BangPatterns #-}
main=interact$unlines.map show.f.tail.map read.words
f(x:y:rest)=g 0 x y : f rest
f _ = []

g !ans !x !y
  | x==0 || y==0 = ans
  | x < y = let (!q,!r) = quotRem y x in g (ans+q) r x
  | x > y = let (!q,!r) = quotRem y x in g (ans+q) r y
  | otherwise = 1

{-# LANGUAGE BangPatterns #-}
main=interact$unlines.map show.f.tail.map read.words
f(x:y:rest)=g 0 x y : f rest
f _ = []

g !ans !x !y
  | x==0 || y==0 = ans
  | x < y = let (!q,!r) = quotRem y x in g (ans+q) r x
  | x > y = let (!q,!r) = quotRem y x in g (ans+q) r y
  | otherwise = ans + 1

{-# LANGUAGE BangPatterns #-}
main=interact$unlines.map show.f.tail.map read.words
f(x:y:rest)=g 0 x y : f rest
f _ = []

g !ans !x !y
  | x==0 || y==0 = ans
  | x < y = let (!q,!r) = quotRem y x in g (ans+q) r x
  | x > y = let (!q,!r) = quotRem y x in g (ans+q) r y
  | otherwise = 2


{-# LANGUAGE MultiWayIf, TypeApplications, 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

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

r p bs =
  let l = BS.length bs
   in fmap (BS.index bs) [l - 1,l - 2 .. 0]

main =
  cf $ do
    len <- readLn @Int
    line <- BS.getLine
    let p = not . BSI.isSpaceChar8
        n1 = (read @Int) $ reverse $ head $ words $ r p line
        n2 = fst $ fromJust $ BS.readInt $ BS.takeWhile p line
    BS.putStr $
      if n1 == len || n2 == len
        then BS.intercalate " " $ reverse $ BS.words line
        else "-1"
    putStrLn ""

{-# LANGUAGE MultiWayIf, TypeApplications #-}

import Control.Monad

main = do
  numCases <- readLn
  replicateM_ numCases $ do
    len <- readLn @Int
    nums_ <- getLine
    let nums = words $ nums_
    putStrLn $
      if read (head nums) == len || read (last nums) == len
        then unwords $ reverse nums
        else "-1"


module Main where

import Data.Char

--foo :: String -> Int
finds n m = length $ filter (== m) n

main = do
  n <- getLine
  s <- getLine
  let p = (finds s '1')
  let q = (finds s '0')
  print (if p >= q then p-q else q-p)

import Control.Applicative
import Data.List

main=do
	n<- read <$> getLine ::IO Int
	a<-   getLine
	let b1= length $ filter (=='1') a
	print $ abs ((n-b1)-b1)

ans [] = 0
ans (x:xs) = if x == '0' then ans xs + 1
                     else ans xs - 1

main = do
    numInputs <- getLine
    digs <- getLine
    print(abs(ans digs))

{-# LANGUAGE BangPatterns #-}

import Data.List (foldl')

parse :: String -> String
parse contents = s where [_, s] = lines contents

solve :: String -> Int
solve = length . foldl' step []
        where step []       !a = [a]
              step (s : ss) !a
                | s /= a    = ss
                | otherwise = a : s : ss

main :: IO ()
main = print . solve . parse =<< getContents

import Data.List (partition)

process :: [Char] -> Int
process s = abs ((length s1)-(length s0))
    where
        (s0,s1) = partition (=='0') s

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    s <- getLine
    print $ process s

main :: IO ()
main = interact $ show . solve . head .tail.lines

solve :: String -> Int
solve xs = abs $ (-) (length . filter (=='1') $ xs) (length . filter (=='0') $ xs)

main :: IO()
main = print . solve . head . tail . words =<< getContents

solve :: String -> Int
solve s = solve' s [] 0

solve' :: String -> [Char] -> Int -> Int
solve' []     _      num = num
solve' (c:cs) []     0   = solve' cs [c] 1
solve' (c:cs) (s:ss) num | c == s    = solve' cs (c:s:ss) (num+1)
                         | otherwise = solve' cs ss (num-1)

module Main where

toInt :: String -> Int
toInt s = read s :: Int

toIntList :: String -> [Int]
toIntList s = map toInt $ words s

readInt :: IO Int
readInt = fmap toInt getLine

readIntPair :: IO (Int, Int)
readIntPair = do
  (x:y:[]) <- fmap (map toInt . words) getLine
  return (x, y)

readIntList :: IO [Int]
readIntList = fmap (map toInt . words) getLine

readNStrings :: Int -> IO [String]
readNStrings n = sequence $ replicate n getLine

readNIntLists :: Int -> IO [[Int]]
readNIntLists n = fmap (map (\s -> toIntList s)) (readNStrings n)

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

process :: Char -> [Char] -> [Char]
process '0' ('1':xs) = xs
process '1' ('0':xs) = xs
process x xs = x:xs

main = do
  n <- getLine
  s <- getLine
  let r = foldr process [] s
  print $ length r

-- http://codeforces.com/problemset/problem/556A.hs

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

reduceString :: String -> String
reduceString str = reduceString' [] str
	where
		reduceString' acum [] = reverse acum
		reduceString' acum (x:[]) = reverse $ (x:acum)
		reduceString' [] (x:xs)
			| x /= head xs = reduceString' [] (tail xs)
			| otherwise = reduceString' [x] xs
		reduceString' acum (x:xs)
			| x /= head xs = reduceString' (tail acum) (head acum : tail xs)
			| otherwise = reduceString' (x:acum) xs

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

main = do

	_ <- getLine
	str <- getLine

	let
		reduced = reduceString str

	putStrLn $ show $ length reduced

main = do
  getLine
  s <- getLine
  let
    c1 = length $ filter (== '1') s
    c2 = length $ filter (== '0') s

  print $ abs $ c1-c2

main = getContents >>= putStrLn . show . solve . last . words

solve :: String -> Int
solve cs = n - 2 * min p q
    where n = length cs
          p = length $ filter (== '0') cs
          q = length $ filter (== '1') cs

module Main where

import Control.Applicative
import Control.Monad
import Data.Char           (toLower)
import Data.List           (intersperse)
import System.IO

solve :: String -> String
solve str = show $ abs $ count '0' str - count '1' str
    where count ch = length . filter (==ch)

main :: IO ()
main = do
    hSetBuffering stdin $ BlockBuffering Nothing
    hSetBuffering stdout $ BlockBuffering Nothing
    getLine
    str <- getLine
    putStrLn $ solve str

answer::[Char] -> Int
answer a = abs ((length (filter (=='0') a)) - (length (filter (=='1') a)))
main = do
  w0 <- getLine
  w1 <- getLine
  print $ answer w1

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = getLine >>= \a->solve =<< (map (fst.fromJust.C.readInt).C.words.C.intersperse ' '<$>C.getLine)
solve xs = print $ abs $ foldr (\a b-> if a>0 then 1+b else b-1) 0 xs

remove01 [] bs = length bs
remove01 ('1':'0':as) []  = remove01 as []
remove01 ('1':'0':as) (b:bs)  = remove01 (b:as) bs
remove01 ('0':'1':as) []  = remove01 as []
remove01 ('0':'1':as) (b:bs)  = remove01 (b:as) bs
remove01 (a:as) bs  = remove01 as (a:bs)

main = getLine >> getLine >>= print . (\x -> remove01 x [] )

-- Codeforces 556A

-- Hint: If there still exist at least one 0 and at least one 1 in the string
-- then there obviously exists either substring 01 or substring 10 (or both)
-- and we can remove it.
-- The order in which we remove substrings is unimportant: in any case we will
-- make min(#zeros, #ones) such operations.
-- Thus the answer is #ones + #zeros - 2min(#ones, #zeros) = |#ones - #zeros|.

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    getLine >>= print . abs . solve where
        solve xs = (length $ filter (== '1') xs) - (length $ filter (== '0') xs)

apply_operation :: [Char] -> [Char]
apply_operation [] = []
apply_operation (x:xs)
    | null rest = [x]
    | x == (head rest) = (x:rest)
    | otherwise = tail rest
    where rest = apply_operation xs

main :: IO()
main = do _ <- getLine
          bitstring <- getLine
          print (length $ apply_operation bitstring)

apply_operation :: [Char] -> [Char]
apply_operation bitstring = foldr loop "" bitstring
    where loop y "" = [y]
          loop y (x:xs)
              | x == y = y:(x:xs)
              | otherwise = xs

main :: IO()
main = do _ <- getLine
          bitstring <- getLine
          print (length $ apply_operation bitstring)

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

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

main = interact solve
solve input =
  let aswords = words input
      n:p:_ = aswords
  in show . solve' $ p

solve' :: String -> Int
solve' = length . reducedStr
  where
    reducedStr :: String -> String
    reducedStr "" = ""
    reducedStr "1" = "1"
    reducedStr "0" = "0"
    reducedStr str
      | reduced == "" = f:[]
      | f == f' = f:reduced
      | otherwise = rest'
      where (f:rest) = str
            reduced = reducedStr rest
            (f':rest') = reduced

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

--process::C.ByteString->C.ByteString

--process q       | C.null q = C.empty
--                | C.length q ==1 = q
--                | C.take 2 q==(C.pack "10") = process (C.drop 2 q)
--                | C.take 2 q ==(C.pack "01") = process (C.drop 2 q)
--                | otherwise = C.cons (C.head q ) ( process (C.tail q))

--myfix::(C.ByteString->C.ByteString)->C.ByteString->C.ByteString
--myfix f q | q==qq = q
--          | otherwise = myfix f (f q)
--  where qq = f q
process::Int->String->String->Int
process n st re | re==[] = n
                | st ==[] = process n [(head re)] (tail re)
                | head st /= head re = process (n-2) (tail st) (tail re)
                | otherwise = process n ((head re):st) (tail re)
main=do
    n<-read <$> getLine ::IO Int
    q<-  C.unpack <$> C.take n <$> C.getLine
    print $   process n []   q

import Control.Applicative ((*>), (<$>))
import Control.Arrow ((&&&))
import Data.Function (on)

main :: IO ()
main = print =<< solve <$> (getLine *> getLine)

solve :: String -> Int
solve = abs . uncurry ((-) `on` length) . (filter (=='1') &&& filter (=='0'))

import Data.List (partition)
main = getLine >> getLine >>= print . solve
solve s = abs (length a - length b) where (a,b) = partition (== '1') s

f :: String -> Int
f s = abs $ ones - zeros
    where ones = length $ filter (=='1') s
          zeros = length s - ones

main = getLine >> getLine >>= print . f

xsolve ""  = ""
xsolve [a] = [a]
xsolve (a:rest) =
    if null rest' then [a]
    else if a /= head rest' then tail rest'
    else a:rest'
    where rest' = xsolve rest

main = do
    _ <- getLine
    line <- getLine
    (print . length . xsolve) line

probA line = foldr loop "" line
    where
        loop a "" = [a]
        loop a (b:rest)
            | a /= b = rest
            | otherwise = a:(b:rest)

main = do
    _ <- getLine
    line <- getLine
    (print . length . probA) line

solve :: String -> Int
solve ns = abs ((length $ filter (=='0') ns) - (length $ filter (=='1') ns))

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

solve :: String -> Int
solve = solveHelper [] where
    solveHelper [] [] = 0
    solveHelper [] (y:ys) = solveHelper [y] ys
    solveHelper xs [] = length xs
    solveHelper (x:xs) (y:ys)
        | x == y = solveHelper (y:(x:xs)) ys
        | otherwise = solveHelper xs ys

main = do
    n <- getLine
    s <- getLine
    putStrLn $ show $ solve s

import Control.Applicative

count' _ [] = 0
count' n (x:xs)
    | n == x = 1 + count' n xs
    | otherwise = count' n xs

main = do
    n <- read <$> getLine
    n1 <- count' '1' <$> getLine
    let n0 = n - n1
    print $ n - 2 * (n0 `min` n1)

module Main where

count _ [] = 0
count c (a:as) =
    (if a == c then 1 else 0) + count c as

main = do
    _ <- getLine
    s <- getLine
    print $ abs (count '0' s - count '1' s)

main = getContents >>= putStrLn . show . solve . last . words

solve :: String -> Int
solve cs = n - min p q
    where n = length cs
          p = length $ filter (== '0') cs
          q = length $ filter (== '1') cs

minRemain :: [Char] -> Int
minRemain [] = 0
minRemain (x:[]) = 0
minRemain (x:xs)
    | x == snd = 2 + (minRemain $ tail xs)
    | otherwise = minRemain $ tail xs
    where snd = head xs

main :: IO()
main = do len <- getLine
          str <- getLine
          print $ minRemain str

import Control.Applicative
import Data.List

process [] = []
process [x] = [x]
process (a:b:cs)| a=='0' && b=='1' = process cs
                | a=='1' && b=='0' = process cs
                | otherwise = a: ( process (b:cs) )

main=do
    n<-getLine
    q<-   getLine
    print $ length $ process q

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

process::C.ByteString->C.ByteString

process q       | C.null q = C.empty
                | C.length q ==1 = q
                | C.take 2 q==(C.pack "10") = process (C.drop 2 q)
                | C.take 2 q ==(C.pack "01") = process (C.drop 2 q)
                | otherwise = C.cons (C.head q ) ( process (C.tail q))

myfix::(C.ByteString->C.ByteString)->C.ByteString->C.ByteString
myfix f q | q==qq = q
          | otherwise = myfix f (f q)
  where qq = f q

main=do
    n<-getLine
    q<-  C.getLine
    print $ C.length $ myfix process q

import Control.Applicative
import Data.List
import Data.List.Split
import qualified Data.ByteString.Char8 as C
process q | qql>1 = process (concat qq)
          | qqql>1 = process ( concat qqq)
          | otherwise = q

  where qq = splitOn "01" q
        qql = length qq
        qqq = splitOn "10" q
        qqql = length qqq

main=do
    n<-getLine
    q<- C.getLine
    print $ length $ process (C.unpack q)

import Control.Applicative
import Data.List
import Data.List.Split
import qualified Data.ByteString.Char8 as C
process q | qql>1 = process (concat qq)
          | qqql>1 = process ( concat qqq)
          | otherwise = q

  where qq = splitOn "01" q
        qql = length qq
        qqq = splitOn "10" q
        qqql = length qqq

myfix f q | q==qq = q
          | otherwise = myfix f (f q)
  where qq = f q

main=do
    n<-getLine
    q<- C.getLine
    print $ length $ process (C.unpack q)

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

process::C.ByteString->C.ByteString

process q       | C.null q = C.empty
                | C.length q ==1 = q
                | C.take 2 q==(C.pack "10") = process (C.drop 2 q)
                | C.take 2 q ==(C.pack "01") = process (C.drop 2 q)
                | otherwise = C.cons (C.head q ) ( process (C.tail q))

myfix::(C.ByteString->C.ByteString)->C.ByteString->C.ByteString
myfix f q | q==qq = q
          | otherwise = myfix f (f q)
  where qq = f q

main=do
    n<-getLine
    q<-  C.getContents
    print $ C.length $ myfix process q

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

process [] =[]
process [q] = [q]
process (a:b:c) | a=='1' && b=='0' = process c
                | a=='0' && b=='1' = process c
                | otherwise = a:(process (b:c))

myfix f q | q==qq = q
          | otherwise = myfix f (f q)
  where qq = f q

main=do
    n<-getLine
    q<-  C.getLine
    let q1 = C.unpack q
    print $ length $ myfix process  q1

import Data.List (group)
main = getLine >> getLine >>= print . solve . map length . group
solve [] = 0
solve [x] = x
solve s = solve $ reduce $ step s
step (a:b:c) = a-m : b-m : step c where m = min a b
step c = c
reduce (0:a) = reduce a
reduce (a:0:b:c) = a+b : reduce c
reduce (a:b) = a : reduce b
reduce [] = []

main :: IO ()
main = interact $ show . solve

solve :: String -> Int
solve (_:xs) = abs $ (-) (length . filter (=='1') $ xs) (length . filter (=='0') $ xs)

main :: IO ()
main = interact $ show . solve

solve :: String -> Int
solve xs = abs $ (-) (length . filter (=='1') $ xs) (length . filter (=='0') $ xs)


import Data.List
import Data.Function
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B

getIntArray :: B.ByteString -> [Int]
getIntArray = map fst . mapMaybe B.readInt . B.words

main = B.interact $ B.pack . show . getAns . getIntArray

getAns :: [Int] -> Int
getAns (n:xs) = maximum xs

main=interact$show.f.g.(0:).map read.tail.words
g (x:y:[]) = [x-y]
g (x:y:xs) = x-y:g(y:xs)

f (x:[])
  | x < 0 = negate x
  | otherwise = 0
f (x:xs)
  | x < 0 = negate x + f xs
  | otherwise = f (((head xs)+x):(tail xs))

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

solve :: [Integer] -> Integer
solve h = solve' h 0 0
    where
        solve' :: [Integer] -> Integer -> Integer -> Integer
        solve' []     _     _      = 0
        solve' (h:hs) lastH energy | energy + lastH - h < 0 = h - energy - lastH + (solve' hs h 0)
                                   | otherwise              = solve' hs h (energy + lastH - h)

import Data.List
import Data.Function
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B

getIntArray :: B.ByteString -> [Int]
getIntArray = map fst . mapMaybe B.readInt . B.words

main = B.interact $ B.pack . show . getAns . getIntArray

getAns :: [Int] -> Int
getAns (n:xs) = negate $ calMax xs 0 0

calMax :: [Int] -> Int -> Int -> Int
calMax [] _ _ = 0
calMax (x:xs) e p = let ne = e + p - x;
					  in min ne $ calMax xs ne x

main :: IO ()
main = getContents >>= print . maximum . map (read :: String -> Integer) . tail . words

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

solve :: [Integer] -> Integer
solve (_:hs) = maximum hs
solve _ = undefined

import Data.Maybe (fromJust)
import qualified Data.ByteString.Char8 as B

main :: IO ()
main = B.getContents >>= print . solve . map (fst . fromJust . B.readInt) . B.words

solve :: [Int] -> Int
solve (_:hs) = maximum hs
solve _ = undefined

{-# LANGUAGE TypeApplications #-}
main = interact $ show @Int . maximum . map read . tail . words

main = do
  getLine
  getLine >>= print. maximum. map (fromIntegral.read) . words

main = interact $ show . maximum . map (read::String -> Int) . drop 1 . words

solve :: [Integer] -> Integer -> Integer
solve [x] power = 0
solve (x:y:xs) power = if delta > power then ((delta - power) + solve (y:xs) 0) else solve (y:xs) (power - delta)
	where delta = y - x

main = do
	getLine
	input <- getLine
	putStr $ show $ max 0 (solve (0:(map read $ words input :: [Integer])) 0)

import Data.List
import Data.Function
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B

getIntArray :: B.ByteString -> [Int]
getIntArray = map fst . mapMaybe B.readInt . B.words

main = B.interact $ B.pack . show . maximum . tail . getIntArray

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

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

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

main = do
  getLine
  xs <- getInts

  let
    (_, s) = foldl (\(c, s) x -> let c' = c+x in if c' >= 0 then (c', s) else (0, s-c')) (0, 0) $ zipWith (-) (0:xs) $ xs

  print s

main = interact $ (show :: Int -> [Char]) . maximum . map read . tail . words

import Control.Applicative
main = do
		n <- getLine
		p <- (map read . words <$> getLine) :: IO [Int]
		print $ maximum p

-- Codeforces 463B

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    getLine >>= print . solve . map read . words

solve :: [Int] -> Int
solve = fst . foldl (
    \(m, (e, h)) b -> if (e < b-h)
        then (m+(b-h-e), (0, b))
        else (m, (e-(b-h), b)))
    (0, (0, 0))

import Control.Applicative
import Data.List

main::IO ()
main=do
    n<- read <$> getLine::IO Int
    a1<- maximum <$>  map read <$>   words   <$> getLine:: IO Int
    print a1

main=interact$show.f.(0:).map read.tail.words
f (x:y:[]) = y-x
f (x:y:xs)
  | x - y < 0 = y-x + f (y:xs)
  | otherwise = f(x:xs)

main=interact$show.negate.minimum.g.(0:).map read.tail.words
g (x:y:[]) = [x-y]
g (x:y:xs) = x-y:g(y:xs)


-- ID : 1697B (Promo)
-- URL: https://codeforces.com/problemset/problem/1697/B

import Control.Monad
import Data.List
import Data.Array

-- Fast IO
import Data.Int
import Data.Maybe
import qualified Data.ByteString.Char8 as BS8
import qualified Data.ByteString as BS
getInt64 = parseInt `fmap` BS8.getLine :: IO Int64
getInt64s = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int64]
parseInt = fromIntegral . fst . fromJust . BS8.readInt
-- Slow IO
getIntsSlow = (map read . words) `fmap` getLine :: IO [Int]

main = do
    [n,q] <- getIntsSlow
    ps0 <- getInt64s
    let ps = sortBy (\a b -> compare b a) ps0
    let subsumTable = listArray (0,n) (scanl (+) 0 ps) :: Array Int Int64
    --print subsumTable
    replicateM_ q $ do
        [x,y] <- getInt64s
        let answer = (subsumTable ! (fromIntegral x)) - (subsumTable ! (fromIntegral (x-y)))
        print answer

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

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

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

data TC = TC { n :: Int, q :: Int, ps :: [Int], qs :: [(Int, Int)]}
type Output = [Int]

input :: Scanner TC
input = do
  n <- int
  q <- int
  ps <- n >< int
  qs <- q >< pair int int
  return TC {..}

solve :: TC -> Output
solve TC {..} = map calc qs
  where
    pre = listArray (0, n) . scanl (+) 0 . reverse . sort $ ps
    calc (x, y) = pre ! x - pre ! (x - y)

output :: Output -> C.ByteString
output = map showB >>> C.unlines

-------------------------- Template ------------------------------------------
-- Debug
debug :: Show a => a -> a
#ifdef ONLINE_JUDGE
debug = id
#else
debug a = trace (show a) a
#endif

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


import Data.List

one :: (Int, [(Int, Int)])->Int->(Int, [(Int, Int)])
one (a, b) c = (m+1, (c, 1+(foldl max 0 $m:map snd p)):q) where (p, q) = break ((c,0)>) b; m = a-(length p)

gls :: [Int]->[Int]
gls = scanl (\a (_,(x:s))->max a $snd x) 0 . tail . scanl one (0,[])

slv :: [Int]->(Int, Int)
slv x =(m+1,o) where Just o = elemIndex m l; l = zipWith max (gls x) $reverse $ gls $ reverse x; m = foldl1 min l;

ot :: [Int]->Int->[Int]
ot x n = [a,(1+o+b)`mod`n] where (a,b)=(slv . take (n - 1) . tail. snd . break (1==) $x++x); Just o = elemIndex 1 x

main=do
 st1<-getLine
 st2<-getLine
 let n = (read st1)::Int
 let arr = map read $ words st2 :: [Int]
 putStrLn $intercalate " " $ map show (ot arr n)

import Data.List

one (a, b) c = (m+1, (c, 1+(foldl max 0 $m:map snd p)):q) where (p, q) = break ((c,0)>) b; m = a-(length p)

gls = scanl (\a (_,(x:s))->max a $snd x) 0 . tail . scanl one (0,[])

slv x =(m+1,o) where Just o = elemIndex m l; l = zipWith max (gls x) $reverse $ gls $ reverse x; m = foldl1 min l;

ot x n = [a,(1+o+b)`mod`n] where (a,b)=(slv . take (n - 1) . tail. snd . break (1==) $x++x); Just o = elemIndex 1 x

main=do
 st1<-getLine
 st2<-getLine
 let n = (read st1)::Int
 let arr = map read $ words st2 :: [Int]
 putStrLn $intercalate " " $ map show (ot arr n)


import Data.Ratio

showR r = show (numerator r) ++ "/" ++ show (denominator r)

solve [ [n, m], p:_, q:_ ]	| n < m			= "0/1"
				| n > m && p * q > 0	= "Infinity"
				| n > m && p * q < 0	= "-Infinity"
				| n == m		= showR (p % q)

main = interact $ solve . map (map read . words) . take 3 . lines

solve :: Int -> Int -> Int -> Int -> String
solve n m a b
  | n < m  =  "0/1"
  | a * b < 0  =  '-' : solve n m a' b'
  | n > m  =  "Infinity"
  | otherwise  =  concat [show $ div a' gcdAB, "/", show $ div b' gcdAB]
  where
    a'  =  abs a
    b'  =  abs b
    gcdAB  =  gcd a' b'

reads :: Read a => IO [a]
reads  =  getLine >>= return . map read . words

main :: IO ()
main  =  do
    [n, m]  <-  Main.reads
    as  <-  Main.reads
    bs  <-  Main.reads
    putStrLn $ solve n m (head as) (head bs)

import Control.Applicative

main = do
  [n,m] <- map read.words <$> getLine
  (a:_) <- map read.words <$> getLine
  (b:_) <- map read.words <$> getLine
  putStrLn $ solve n m a b

solve :: Int -> Int -> Int -> Int ->String
solve n m a b
  | n>m = s ++ "Infinity"
  | n<m = "0/1"
  | otherwise = s ++ show x ++ "/" ++ show y
   where
     s = if a*b<0 then "-" else ""
     x = abs $ div a g
     y = abs $ div b g
     g = gcd a b

import Data.Ratio

solve [ [n, m], p:_, q:_ ]	| n < m			= "0/1"
				| n > m && p * q > 0	= "Infinity"
				| n > m && p * q < 0	= "-Infinity"
				| n == m		= show (numerator $ p % q) ++ "/" ++ show (denominator $ p % q)

main = interact $ solve . map (map read . words) . lines

import Data.Ratio

solve [ [n, m], p:_, q:_ ]	| n < m			= "0/1"
				| n > m 		= (if p * q < 0 then "-" else "") ++ "Infinity"
				| n == m		= show (numerator $ p % q) ++ "/" ++ show (denominator $ p % q)

main = interact $ solve . map (map read . words) . lines

import Data.Ratio

main =
	do	grades <- getLine
		coeficientsP <- getLine
		coeficientsQ <- getLine
		putStrLn (result grades coeficientsP coeficientsQ)

result::String -> String -> String -> String

result grades coefsP coefsQ =
	if gradeP > gradeQ
	then infinity coefP coefQ
	else if gradeQ > gradeP
	then "0/1"
	else limit coefP coefQ
		where	[gradeP, gradeQ]	= map toInt (words grades)
			coefP			= toInt (head (words coefsP))
			coefQ			= toInt (head (words coefsQ))

infinity coefA coefB =
	(if coefA*coefB > 0
	then ""
	else "-")++"Infinity"

limit::Int -> Int -> String
limit p q =
	(show (numerator lim))
	++ "/" ++
	(show (denominator lim))
		where lim = p % q

toInt::String -> Int
toInt s = read s :: Int

import Data.List

getNumerator :: Int -> Int -> Int
getNumerator a b
	| b > 0 = div a (gcd a b)
	| otherwise =  div (0 - a) (gcd a b)

getDenominator :: Int -> Int -> Int
getDenominator a b
	| b > 0 = div b (gcd a b)
	| otherwise = div (0 - b) (gcd a b)

main :: IO()
main = do
	str1 <- getLine
	str2 <- getLine
	str3 <- getLine
	let num = words str1
	let a0  = read ((words str2) !! 0)
	let b0  = read ((words str3) !! 0)
	let n = read (num !! 0)
	let m = read (num !! 1)
	if ((m - n) > 0)
		then putStrLn "0/1"
		else if (n > m)
			then if (a0 * b0 > 0)
				then putStrLn "Infinity"
				else putStrLn "-Infinity"
			else putStrLn (show (getNumerator a0 b0) ++ "/" ++ show (getDenominator a0 b0))

-- -*- compile-command: "ghc --make -O limit.hs" -*-

import System.IO
import Data.List
import Data.Char
import qualified Data.ByteString.Lazy as B

limit :: Int -> Int -> Int -> Int -> String
limit n m a b
  | m > n = "0/1"
  | n > m && a*b > 0 = "Infinity"
  | n > m = "-Infinity"
   | otherwise = (show $ c `div` ggt) ++ "/" ++ (show $ d `div` ggt)
       where ggt = gcd a b
             (c,d) = if a*b > 0
                     then (abs a, abs b)
                     else (negate $ abs a, abs b)

readInts :: String -> [Int]
readInts = (map read) . words

main = do
     n:m:[] <- readInts `fmap` getLine
     a0:_ <- readInts `fmap` getLine
     b0:_ <- readInts `fmap` getLine
     --print a0
     --print b0
     putStrLn $ limit n m a0 b0

import Data.List

getNumerator :: Int -> Int -> Int
getNumerator a b
	| b > 0 = div a (gcd a b)
	| otherwise =  div (0 - a) (gcd a b)

getDenominator :: Int -> Int -> Int
getDenominator a b
	| b > 0 = div b (gcd a b)
	| otherwise = div (0 - b) (gcd a b)

main :: IO()
main = do
	str1 <- getLine
	str2 <- getLine
	str3 <- getLine
	let num = words str1
	let a0  = read ((words str2) !! 0)
	let b0  = read ((words str3) !! 0)
	let n = num !! 0
	let m = num !! 1
	if (m > n)
		then putStrLn "0/1"
		else if (n > m)
			then if (a0 * b0 > 0)
				then putStrLn "Infinity"
				else putStrLn "-Infinity"
			else putStrLn (show (getNumerator a0 b0) ++ "/" ++ show (getDenominator a0 b0))

-- -*- compile-command: "ghc --make -O limit.hs" -*-

import System.IO
import Data.List
import Data.Char
import qualified Data.ByteString.Lazy as B

limit :: Int -> Int -> Int -> Int -> String
limit n m a b
  | m > n = "0/1"
  | n > m && a*b > 0 = "Infinty"
  | n > m = "-Infinty"
   | otherwise = (show $ c `div` ggt) ++ "/" ++ (show $ d `div` ggt)
       where ggt = gcd a b
             (c,d) = if a*b > 0
                     then (abs a, abs b)
                     else (negate $ abs a, abs b)

readInts :: String -> [Int]
readInts = (map read) . words

main = do
     n:m:[] <- readInts `fmap` getLine
     a0:_ <- readInts `fmap` getLine
     b0:_ <- readInts `fmap` getLine
     --print a0
     --print b0
     putStrLn $ limit n m a0 b0

import Data.Ratio

showR r = show (numerator r) ++ "/" ++ show (denominator r)

solve [ [n, m], p:_, q:_ ]	| n < m			= "0/1"
				| n > m && p > 0	= "Infinity"
				| n > m && p < 0	= "-Infinity"
				| n == m		= showR (p % q)

main = interact $ solve . map (map read . words) . take 3 . lines

import Data.Ratio

main =
	do	grades <- getLine
		coeficientsP <- getLine
		coeficientsQ <- getLine
		putStrLn (result grades coeficientsP coeficientsQ)

result::String -> String -> String -> String

result grades coefsP coefsQ =
	if gradeP > gradeQ
	then infinity coefP
	else if gradeQ > gradeP
	then "0/1"
	else limit coefP coefQ
		where	[gradeP, gradeQ]	= map toInt (words grades)
			coefP			= toInt (head (words coefsP))
			coefQ			= toInt (head (words coefsQ))

infinity coef =
	(if coef > 0
	then ""
	else "-")++"Infinity"

limit::Int -> Int -> String
limit p q =
	(show (numerator lim))
	++ "/" ++
	(show (denominator lim))
		where lim = p % q

toInt::String -> Int
toInt s = read s :: Int


import Control.Monad
import Data.List
import qualified Data.Map as M

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

output :: Show a => [a] -> IO ()
output = putStrLn <$> unwords <$> map show

main = do
  [n,p,k] <- input
  a <- input
  print
    $ sum
    $ map (\xs -> let n = length xs in n*(n-1)`div`2)
    $ group
    $ sort [(x^4-k*x) `mod` p | x <- a]

import Control.Monad
import qualified Data.Map.Strict as M

--
-- UTILITIES
--
import qualified Data.ByteString.Char8 as C
import           Data.Maybe (fromJust)

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

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

getInteger :: IO Integer
getInteger = read <$> getLine

getIntegers :: IO [Integer]
getIntegers = fmap (fst . fromJust . C.readInteger) . C.words <$> C.getLine

--
-- MAIN
--

main :: IO ()
main = do
  [n, p, k] <- getIntegers
  nums <- getIntegers
  let modnums = (\a -> (a ^ 4 - k * a) `mod` p) <$> nums
      modmap  = foldl (\m k -> if k `M.member` m then M.adjust succ k m else M.insert k 1 m) M.empty modnums
      modlist = (\(_, v) -> (v * v - v) `div` 2) <$> M.toList modmap
  print $ sum modlist


import Data.List (splitAt)
main = do
    [n,a,b] <- fmap ((map read) . words) getLine :: IO[Int]
    if n>a*b
        then print (-1)
        else mapM_ printLs $ solve n a b

printLs :: [Int] -> IO()
printLs xs = mapM_ (\x -> putStr (show x ++ " ")) xs >> putStrLn ""

solve :: Int -> Int ->Int ->[[Int]]
solve n a b =
    let l = [1..n] ++ (repeat 0)
    in go l a b 0

go :: [Int] -> Int -> Int -> Int ->[[Int]]
go l a b c
 |c==a = []
 |otherwise =
    let (x,y) = splitAt b l
    in if even c then x:go y a b (c+1) else (reverse x):go y a b (c+1)

main :: IO ()
main = do
  (n:a:b:_) <- fmap (map read . words) getLine
  if n > a * b
  then print (-1)
  else flip mapM_ [0 .. a-1] $ \i -> do
    let r = (if even b && odd i then reverse else id)
          [if j < n then j + 1 else 0 | j <- take b [i * b ..]]
    putStrLn $ unwords $ map show r

import Data.List

rowToString [] = ""
rowToString (x : xs) = (show x) ++ " " ++ (rowToString xs)
tableToString [] = ""
tableToString (r : rs) = (rowToString r) ++ ("\n") ++( tableToString rs)

up b = div (b + 1) 2
down b = div b 2
build a n m b | a == 0 = []
              | otherwise = ((map (max 0) . concat . transpose $ ([take (up b) [n, n - 2..], take (down b) [m, m - 2..]])): build (a - 1) (m - 2 * down(b)) (n - 2 * up(b)) b)
main = do
    [n, a, b] <- fmap (map  read . words) getLine
    putStr .tableToString $ if (n > a * b) then [[(-1)]] else (build a n (n - 1) b)

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

splitBy::Int->[a]->[[a]]
splitBy _ [] = []
splitBy n xs = let (pref, rest) = splitAt n xs in pref: splitBy n rest

solution::Int->Int->Int->[[Int]]
solution n a b
  | n > a * b = [[-1]]
  | otherwise = let
    nums    = splitBy b $ take (a*b)  $ [1..n] ++ repeat 0
    rev _ []          = []
    rev False (x: xs) = x: rev True xs
    rev True (x:xs)   = reverse x : rev False xs
    in case mod b 2 of
      1 -> nums
      _ -> rev False nums

main :: IO ()
main = do
  [n,a,b] <- map read . words <$> getLine
  forM_ (solution n a b) $ putStrLn . intercalate " ". map show

main = interact $ unlines . map (unwords . map show) . go . map read . words . filter ('\n'/=)
go [n,a,b] | n>a*b = [[-1]]
           | True = (map (\(i,k) -> dr i [k-b+1..k]) . take ndb $ zip [1..] [b,b+b..]) ++ map zs [ndb+1..a]
           where dr i | b`mod`2==0 && i`mod`2==0 = reverse
                      | True = id
                 zs i = dr i $ l ++ take (b-length l) [0,0..]
                      where l = [b*(i-1)+1..n]
                 ndb = n`div`b

main = do
  (n:a:b:_) <- fmap (map read . words) getLine
  if n > a * b
  then print (-1)
  else flip mapM_ [0 .. a-1] $ \i -> do
    let r = (if odd b && odd i then reverse else id)
          [if j < n then j + 1 else 0 | j <- take b [i * b ..]]
    putStrLn $ unwords $ map show r


import Data.List
import Control.Monad
main :: IO ()
main = do
  n <- readLn
  replicateM_ n routine
routine :: IO ()
routine = do
  n <- readLn
  as <- (map read. words) <$> getLine
  print $ solve n as

solve :: Int -> [Int] -> Int
solve n as = (as'!!n)-(as'!!(n-1))
  where
    as' = sort as

import Data.Ord
import Data.Int
import qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>), take)
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Prelude hiding (showList)
import Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if DSeq.null s then
                aux s
            else
                return $ toList s
        else
            aux $ s DSeq.|> x
    in aux DSeq.Empty

type EIO a = ExceptT String IO a

get :: Read a => EIO a
get = ExceptT $ liftM readEither getToken
gets :: EIO String
gets = ExceptT $ liftM Right getToken
puts :: String -> EIO ()
puts = lift . putStr
putsln :: String -> EIO ()
putsln = lift . putStrLn
put :: Show a => a -> EIO ()
put = putsln . show
putln :: Show a => a -> EIO ()
putln = putsln . show
showList :: Show a => [a] -> String
showList [] = []
showList (x : l) = shows x $ showChar ' ' $ showList l

main :: IO ()
main = do
    o <- runExceptT main_
    case o of
        Right () -> return ()
        Left s -> putStrLn s

main_ :: EIO ()
main_ = do
    t <- get
    replicateM_ t f1

f1 :: EIO ()
f1 = do
    n <- get
    a <- replicateM (2 * n) get
    putln $ f2 a n

f2 :: [Int64] -> Int -> Int64
f2 l n =    let sl = sort l
            in
            ((sl !! (n)) - (sl !! (n - 1)))

import Control.Monad
import Data.List

solve :: (Int, [Int]) -> Int
solve (n,xs) = abs $ (xs !! q) - (xs !! r)
  where
    q = 2 * n `div` 2
    r = q - 1

main = do
  t <- readLn :: IO Int
  xss <- replicateM t $ do
    n <- readLn :: IO Int
    xs <- sort . map read . words <$> getLine :: IO [Int]
    return (n, xs)
  mapM_ (print . solve) xss

import Data.List as L

solve :: [Integer] -> Integer
solve as = (head secondHalf) - (last firstHalf)
  where ordered = L.sort as
        mid = div (length as) 2
        firstHalf = take mid ordered
        secondHalf = drop mid ordered

groupByTwo :: [String] -> [(String, String)]
groupByTwo [] = []
groupByTwo (n:as:other) = [(n, as)] ++ groupByTwo other

parse :: (String, String) -> String
parse (_, as) = show $ solve as'
  where as' = map (\x -> read x :: Integer) $ words as

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

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

main = getLine >>= test.read
test 0 = return ()
test n = getLine >> getLine >>= print.solve.sort.map read.words >> test (n - 1)

solve as = abs $ as !! i - as !! pred i where
  i = div (length as) 2

import Control.Monad
import Data.List

solve :: (Int, [Int]) -> Int
solve (n,xs) = abs $ ma - mb
  where
    ma = (reverse as) !! (n `div` 2)
    mb = (reverse bs) !! (n `div` 2)
    (as,bs) = foldl' step ([],[]) $ zip [1..2*n] xs
    step (as,bs) (i,e)
      | odd i = (e:as,bs)
      | otherwise = (as,e:bs)

main = do
  t <- readLn :: IO Int
  xss <- replicateM t $ do
    n <- readLn :: IO Int
    xs <- sort . map read . words <$> getLine :: IO [Int]
    return (n,xs)
  mapM_ (print . solve) xss

import Control.Monad
import Data.List

solve :: (Int, [Int]) -> Int
solve (n,xs) = abs $ ma - mb
  where
    ma = (sort as) !! (n `div` 2)
    mb = (sort bs) !! (n `div` 2)
    (as,bs) = collect xs ([],[])
    collect xs (as,bs)
      | null xs = (as,bs)
      | otherwise = collect xs' ((h:as), (l:bs))
      where
        h = head xs
        l = last xs
        xs' = reverse $ init $ tail xs

main = do
  t <- readLn :: IO Int
  xss <- replicateM t $ do
    n <- readLn :: IO Int
    xs <- sort . map read . words <$> getLine :: IO [Int]
    return (n,xs)
  mapM_ (print . solve) xss

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

solve :: (Int, [Int]) -> Int
solve (n,xs) = abs $ (xs !! q) - (xs !! r)
  where
    q = 2 * n `div` 2
    r = q - 1

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


import Data.List
import qualified Data.Maybe as M
import qualified Data.Set as S

candidate :: String -> String -> String

candidate [] [] = []
candidate (x:xs) (y:ys) = cur:candidate xs ys
    where
        cur = if (x == y) then x else (head $ "SET" \\ [x, y])

getAllMatches cards = [(a, b, c) |
    (a:bs) <- tails cards,
    b <- bs,
    let c = candidate a b,
    c < a,
    S.member c cards']
    where cards' = S.fromAscList cards

solve :: [String] -> Int
solve cards =
    length . getAllMatches . sort $ cards

main = do
    _ <- getLine
    strings <- words <$> getContents
    print $ solve strings

import Data.Map.Strict (fromAscList, findWithDefault, keys)
import Data.List

main = do
	getLine
	strings <- group . sort . words <$> getContents
	let counts = fromAscList [(head ss, length ss) | ss <- strings]
	    elems = keys counts
	print $ sum [findWithDefault 0 (set a b) counts |
		i <- [0..length elems - 1],
		let (a:bs) = drop i elems,
		b <- bs] `div` 3

set [] _ = []
set (a:as) (b:bs)
	| a == b = a : set as bs
	| otherwise = (head $ "SET" \\ [a, b]) : set as bs

import Data.Set as S
import Data.List as L

missing :: Char -> Char -> Char
missing 'S' 'E' = 'T'
missing 'E' 'S' = 'T'
missing 'E' 'T' = 'S'
missing 'T' 'E' = 'S'
missing 'S' 'T' = 'E'
missing 'T' 'S' = 'E'

desiredCard :: String -> String -> String
desiredCard "" "" = ""
desiredCard (a:as) (b:bs)
  | a == b = [a] ++ next
  | otherwise = [missing a b] ++ next
  where next = desiredCard as bs

possibilitiesCount :: [String] -> Int
possibilitiesCount strings = length
                             $ L.filter (\[a, b] -> S.member (desiredCard a b) allStrings)
                             [[a, b] | a <- strings, b <- strings, a /= b && a < b]
  where allStrings = S.fromList strings

solve :: String -> String
solve input = show $ (div (possibilitiesCount lines') 3)
  where lines' = tail $ lines input

main :: IO ()
main = do
  contents <- getContents
  putStrLn (solve contents)