{-# LANGUAGE ScopedTypeVariables #-}

import Control.Monad
import Data.Ratio
import Data.Function
import Data.Coerce
import Data.Array

class TypeMod a where
    modulo :: ModInt a

data MyMod = MyMod
instance TypeMod MyMod where
    modulo = Mod 998244353

newtype ModInt a = Mod Integer

instance Show (ModInt a) where
    show (Mod n) = show n

instance TypeMod a => Num (ModInt a) where

    Mod l + Mod r = Mod (mod (l + r) (coerce (modulo::ModInt a)))

    Mod l - Mod r = Mod (mod (l - r) (coerce (modulo::ModInt a)))

    Mod l * Mod r = Mod (mod (l * r) (coerce (modulo::ModInt a)))

    abs = id
    signum = const 1
    fromInteger n = Mod (mod n ((coerce (modulo::ModInt a))))

instance TypeMod a => Fractional (ModInt a) where
    recip = (^(((coerce(modulo::ModInt a)::Integer) - 2)))
    fromRational r = (fromInteger . numerator) r * (recip . fromInteger . denominator) r

fac n = take (n+1) (iterate (\(y,x) -> (y+1,x*fromInteger (y+1))) ((0,1)::(Integer,ModInt MyMod)))

toShow (x,y,z) = show x ++ " " ++ show y ++ " " ++ show z

solve _ 2 = (1,0,1)
solve arr n = let (x,y,z) = solve arr (n-2) in (y+(arr!(n-1)/(arr!(div n 2) * (arr!(div n 2-1)))),x+(arr!(n-2)/(arr!(div n 2) * (arr!(div n 2-2)))) ,z)

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let n = read  input ::Int
        let arr = array (0,n) (map (\(x,y) -> (fromInteger x,y)) $ fac n)
        putStrLn .toShow .solve arr $ n
    return ()

import Data.Map (Map(..))
import qualified Data.Map as M
import Control.Monad (replicateM_)

p = 998244353
main = read <$> getLine >>=
       flip replicateM_ (scase (genGames 60 p))

scase g = read <$> getLine >>=
          \n -> case (g M.! n) of
                  (a, b, c) -> putStrLn (show a ++ " " ++ show b ++ " " ++ show c)

-- n is even > 4
genGames :: Int -> Int -> Map Int (Int, Int, Int)
genGames n p = let m = M.insert 2 (1, 0, 1) M.empty
               in foldl (f p) m [4, 6 .. n]

f :: Int -> Map Int (Int, Int, Int) -> Int -> Map Int (Int, Int, Int)
f p m n = let (a, b, c) = m M.! (n-2)
              n2 = div n 2
          in
            M.insert n ((b + comb (n-1) n2) `mod` p, (a + comb (n-2) n2) `mod` p, c) m

-- n C m
comb :: Int -> Int -> Int
comb n m = c60 M.! (n, m)

c60 :: Map (Int, Int) Int
c60 = let m = M.insert (0, 0) 1 M.empty
          f m (n, k) | k == 0 || k == n = M.insert (n, k) 1 m
                     | otherwise = M.insert (n, k)
                                   (m M.! (n-1, k-1) + m M.! (n-1, k)) m
      in
        foldl f m [(i, j) | i <- [1..60], j <- [0..i]]

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

{-# language Safe                      #-}
{-# language ImportQualifiedPost       #-}
{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L
import Data.Map.Lazy         qualified as Map

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

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [n] <- ri
        return n
    mapM_ (putStrLn.showAns.solve) tcs

showAns (a,b,c) = unwords . map show $ [a,b,c]

solve nn = f nn
  where
    c = ncomb

    f 2 = (1,0,1)
    f n = (c (n-1) (h-1)             .+. b (n-2),
           c (n-2) (h-2) .+. a (n-2)            ,
           c (n  ) (h  ) .-. a (n  ) .-. b (n  ))
      where
        h = n `div` 2

    a n = x  where  (x,_,_) = f n
    b n = x  where  (_,x,_) = f n

ncomb n k = cmap ! (n,k)  where  (!) = (Map.!)
cmap = Map.fromList [((n,k), cc n k) | n <- nvals,
                                       k <- nvals]
  where
    cc n k | (k == 0)  = 1 :: Int
           | (k == n)  = 1
           | otherwise  = ncomb (n-1) (k-1) .+. ncomb (n-1) k
nvals = [0..60] :: [Int]

modVal = 998244353

x .+. y = (x          + y) `mod` modVal
x .-. y = (x + modVal - y) `mod` modVal

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

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

type TC = Int

type Output = [Int]

input :: Scanner TC
input = int

solve :: TC -> Output
solve n = calc n ++ [1]

output :: Int -> Output -> C.ByteString
output _ = map showB >>> C.unwords

calc :: Int -> [Int]
calc 2 = [1, 0]
calc n = let h = n `div` 2 in zipWith (+%) [(n - 1) `choose` h, (n - 2) `choose` h] (reverse $ calc (n - 2))

choose' :: [[Int]]
choose' =
  [ [ if n < r
        then 0
        else
          if r == 0 || r == n
            then 1
            else (n - 1) `choose` r +% (n - 1) `choose` (r - 1)
      | r <- [0 .. 60]
    ]
    | n <- [0 .. 60]
  ]

choose n r = choose' !! n !! r

modulo = 998244353

a +% b = (a + b) `mod` modulo
infixl 4 +%

-------------------------- Template ------------------------------------------
-- Debug
debug :: Show a => a -> a

#ifdef ONLINE_JUDGE
debug = id
#else
debug a = trace (show a) a
#endif

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

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Control.Monad.Trans.State
import Data.Array.Base (UArray (UArray))
import Data.Array.Unboxed
import Data.Bits
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import qualified Data.ByteString.Lazy.Char8 as P
import Data.List
import Data.Maybe
import System.IO

mainFun :: SP Builder
mainFun = do
  casnum <- getInt
  ans <- forM [1 .. casnum] $ \_ -> do
    n <- getInt
    let m = div n 2
    let (w, l) = win !! m
    pure [w, l, 1]
  pure $ mconcat $ map putInts ans
  where
    win =
      map (\(a, b, c) -> (b, c)) $
        take (maxM + 1) $
          iterate
            ( \(i, w, l) ->
                (i + 1, l +! combine (2 * i + 1) i, w +! combine (2 * i) (i + 1))
            )
            (0, 0, 0)

maxN = 60

maxM = div maxN 2

facts :: UArray Int Int
facts = listArray (0, maxN) $ scanl' (*!) 1 [1 .. maxN]

ifacts :: UArray Int Int
ifacts = listArray (0, maxN) [inv (facts ! i) | i <- [0 .. maxN]]

combine :: Int -> Int -> Int
combine n m
  | n < m = 0
  | otherwise = (facts ! n) *! (ifacts ! m) *! (ifacts ! (n - m))

modulo :: Int
modulo = 998244353

infixl 6 +!

(+!) :: Int -> Int -> Int
x +! y = x + y -! modulo

infixl 6 -!

(-!) :: Int -> Int -> Int
x -! y =
  let raw = x - y
   in raw + (modulo .&. shiftR raw 63)

infixl 8 *!

(*!) :: Int -> Int -> Int
x *! y = mod (x * y) modulo
--   let raw = mod (x * y) modulo
--    in raw + (modulo .&. shiftR raw 63)

pow :: Int -> Int -> Int
pow =
  let -- I used to use stimes for this, but it seems that's 15x slower
      -- than just the hand-rolled loop, so no more is it used.
      go acc !x 0 = acc
      go !acc !x k =
        if even k
          then go acc (x *! x) (div k 2)
          else go (acc *! x) (x *! x) (div k 2)
   in go 1

inv :: Int -> Int
inv n = pow n (modulo - 2)

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 BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Control.Monad.Trans.State
import Data.Array.Base (UArray (UArray))
import Data.Array.Unboxed
import Data.Bits
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import qualified Data.ByteString.Lazy.Char8 as P
import Data.List
import Data.Maybe
import System.IO

mainFun :: SP Builder
mainFun = do
  casnum <- getInt
  ans <- forM [1 .. casnum] $ \_ -> do
    n <- getInt
    let m = div n 2
    let (w, l) = win !! m
    pure [w, l, 1]
  pure $ mconcat $ map putInts ans
  where
    win =
      map (\(a, b, c) -> (b, c)) $
        take (maxM + 1) $
          iterate
            ( \(i, w, l) ->
                (i + 1, l +! combine (2 * i + 1) i, w +! combine (2 * i) (i + 1))
            )
            (0, 0, 0)

maxN = 60

maxM = div maxN 2

facts :: UArray Int Int
facts = listArray (0, maxN) $ scanl' (*) 1 [1 .. maxN]

ifacts :: UArray Int Int
ifacts = listArray (0, maxN) [inv (facts ! i) | i <- [0 .. maxN]]

combine :: Int -> Int -> Int
combine n m
  | n < m = 0
  | otherwise = (facts ! n) *! (ifacts ! m) *! (ifacts ! (n - m))

modulo :: Int
modulo = 998244353

infixl 6 +!

(+!) :: Int -> Int -> Int
x +! y = x + y -! modulo

infixl 6 -!

(-!) :: Int -> Int -> Int
x -! y =
  let raw = x - y
   in raw + (modulo .&. shiftR raw 63)

infixl 8 *!

(*!) :: Int -> Int -> Int
x *! y =mod (x * y) modulo
--   let raw = mod (x * y) modulo
--    in raw + (modulo .&. shiftR raw 63)

pow :: Int -> Int -> Int
pow =
  let -- I used to use stimes for this, but it seems that's 15x slower
      -- than just the hand-rolled loop, so no more is it used.
      go acc !x 0 = acc
      go !acc !x k =
        if even k
          then go acc (x *! x) (div k 2)
          else go (acc *! x) (x *! x) (div k 2)
   in go 1

inv :: Int -> Int
inv n = pow n (modulo - 2)

type SP = State P.ByteString

type S = StateT P.ByteString

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

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

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

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

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


import Data.List
import Control.Monad

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

solve :: Int -> [Int] -> Int -> String
solve 0 xs w = show w
solve x xs w
    | head xs == 0 = solve (x - 1) (tail xs) (w + 1)
    | head xs == 1 && last xs == 2 = solve (x - 2) (init (tail xs)) (w + 1)
    | x >= 3 = solve (x - 3) (drop 3 xs) (w + 1)
    | otherwise = solve 0 xs w

--subproblem :: IO ()
--subproblem = do
--  n <- getLine
--  a <- getLine
--  print $ solve (toInt n) (sort (map (`mod` 3) (map toInt (words a)))) 0

fff :: String -> String
fff x = unlines (process (tail (lines x)))

process :: [String] -> [String]
process [] = []
process input = do
    let x = toInt (input !! 0)
    let xs = sort (map (`mod` 3) (map toInt (words (input !! 1))))
    (solve x xs 0 ++ "\n") : process (drop 2 input)

--printAll :: [String] -> IO()
--printAll [] = print []
--printAll x:xs = do

main :: IO()
main = interact fff

import Data.List
import Control.Monad

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

solve :: Int -> [Int] -> Int -> Int
solve 0 xs w = w
solve x xs w
    | head xs == 0 = solve (x - 1) (tail xs) (w + 1)
    | head xs == 1 && last xs == 2 = solve (x - 2) (init (tail xs)) (w + 1)
    | x >= 3 = solve (x - 3) (drop 3 xs) (w + 1)
    | otherwise = solve 0 xs w

subproblem :: IO ()
subproblem = do
  n <- getLine
  a <- getLine
  print $ solve (toInt n) (sort (map (`mod` 3) (map toInt (words a)))) 0

main = do
    n <- getLine
    replicateM (toInt n) subproblem

calc :: [Int] -> Int
calc xs = let a = xs!!0
              b = xs!!1
              c = xs!!2
          in a + min b c + (div (max b c - min b c) 3)

count :: Int -> [Int] -> [Int]
count x cl
    | mod x 3 == 0 = [a + 1, b, c]
    | mod x 3 == 2 = [a, b + 1, c]
    | mod x 3 == 1 = [a, b, c + 1]
    | otherwise = cl
    where a = cl!!0
          b = cl!!1
          c = cl!!2

solve' :: [Int] -> [Int] -> Int -> Int -> [Int] -> [Int]
solve' (x:xs) cl n curr res
    | n == (curr - 1) = solve' xs [0,0,0] x 1 (res ++ [(calc cl)])
    | curr > 0 = solve' xs (count x cl) n (curr + 1) res
    | otherwise = solve' xs [0,0,0] x 1 res

solve' _ cl n curr res
    | cl == [0,0,0] = res
    | otherwise = (tail res) ++ [(calc cl)]

solve :: [Int] -> [Int]
solve xs = solve' xs [0,0,0] (-1) 0 []

main = interact $ unlines . map show . solve . map (read::String->Int) . tail . words

import Control.Monad

solve :: Int -> Int -> Int -> [Integer] -> Int
solve grp0 grp1 grp2 [] = grp0 + pairs + rest
  where pairs = min grp1 grp2
        rest = (grp1 - pairs) `div` 3 + (grp2 - pairs) `div` 3
solve grp0 grp1 grp2 (x:xs)
  | x `mod` 3 == 0 = solve (grp0 + 1) grp1 grp2 xs
  | x `mod` 3 == 1 = solve grp0 (grp1 + 1) grp2 xs
  | x `mod` 3 == 2 = solve grp0 grp1 (grp2 + 1) xs

process :: Int -> [[Integer]] -> IO [[Integer]]
process 0 result = return $ reverse result
process counter result = do
  [_, queries] <- replicateM 2 $ map read . words <$> getLine
  process next (queries:result)
    where next = counter - 1

main :: IO ()
main = do
  n <- readLn
  result <- process n []
  mapM_ (print . solve 0 0 0) $ result

calc :: [Int] -> Int
calc xs = let a = xs!!0
              b = xs!!1
              c = xs!!2
          in a + min b c + (div (max b c - min b c) 3)

count :: Int -> [Int] -> [Int]
count x cl
    | mod x 3 == 0 = [a + 1, b, c]
    | mod x 2 == 0 = [a, b + 1, c]
    | mod x 1 == 0 = [a, b, c + 1]
    | otherwise = cl
    where a = cl!!0
          b = cl!!1
          c = cl!!2

solve' :: [Int] -> [Int] -> Int -> Int -> [Int] -> [Int]
solve' (x:xs) cl n curr res
    | n == (curr - 1) = solve' xs [0,0,0] x 1 (res ++ [(calc cl)])
    | curr > 0 = solve' xs (count x cl) n (curr + 1) res
    | otherwise = solve' xs [0,0,0] x 1 res

solve' _ cl n curr res
    | cl == [0,0,0] = res
    | otherwise = (tail res) ++ [(calc cl)]

solve :: [Int] -> [Int]
solve xs = solve' xs [0,0,0] (-1) 0 []

main = interact $ unlines . map show . solve . map (read::String->Int) . tail . words

calc :: [Int] -> Int
calc xs = let a = xs!!0
              b = xs!!1
              c = xs!!2
          in a + max b c - min b c

count :: Int -> [Int] -> [Int]
count x cl
    | mod x 3 == 0 = [a + 1, b, c]
    | mod x 2 == 0 = [a, b + 1, c]
    | mod x 1 == 0 = [a, b, c + 1]
    | otherwise = cl
    where a = cl!!0
          b = cl!!1
          c = cl!!2

solve' :: [Int] -> [Int] -> Int -> Int -> [Int] -> [Int]
solve' (x:xs) cl n curr res
    | n == (curr - 1) = solve' xs [0,0,0] x 1 (res ++ [(calc cl)])
    | curr > 0 = solve' xs (count x cl) n (curr + 1) res
    | otherwise = solve' xs [0,0,0] x 1 res

solve' _ cl n curr res
    | cl == [0,0,0] = res
    | otherwise = (tail res) ++ [(calc cl)]

solve :: [Int] -> [Int]
solve xs = solve' xs [0,0,0] (-1) 0 []

main = interact $ unlines . map show . solve . map (read::String->Int) . tail . words


{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Data.Maybe
import Prelude as P

import Data.Word (Word8)
import Data.Int (Int64)
import qualified Data.Bits as Bits
import qualified Data.Char as Char
import qualified Data.Ratio as Rat

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

import qualified Data.ByteString as Bs
import qualified System.IO as Io
--import Data.IntSet

issuperior :: [Int] -> [Int] -> Bool
issuperior xs ys = length (filter (==True) $ zipWith (<) xs ys) > div total 2
  where total = length xs

superior :: [Int] -> [Int] -> [Int]
superior xs ys = if issuperior xs ys then xs else ys

winner :: [[Int]] -> [Int]
winner [xs] = xs
winner xxs = winner $ [a] ++ b
  where (a,b) = foldl (\(prev, acc) xs -> if null prev then (xs, acc) else ([], (superior xs prev : acc))) ([], []) xxs

solve :: IO ()
solve = do
  n <- readLn :: IO Int
  a <- readintrows n
  let best = winner a
      cnt = length $ filter (issuperior best) a
      bestidx = if cnt < n-1 then -1 else (fromMaybe 0 $ findIndex (==best) a) + 1
    in print bestidx

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

----------------------------------------------------------------------------------------
readrows :: (Integral b) => b -> IO [String]
readrows 0 = return []
readrows n = do
  row <- getLine
  l <- readrows $ n-1
  return (row : l)

readintrows :: (Integral a, Integral b) => b -> IO [[a]]
readintrows 0 = return []
readintrows n = do
  row <- readInts
  l <- readintrows $ n-1
  return (row : l)

parseInt :: (Integral a) => Bs.ByteString -> a
parseInt xs = snd $ Bs.foldr (\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48)))) (1, 0) xs

readInts :: (Integral a) => IO [a]
readInts =  map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine
  where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs

import Control.Monad (replicateM)
import Data.List ( elemIndex )
import Data.Maybe ( fromJust )
import Data.Function (on)

main :: IO [()]
main = do
  t <- readLn :: IO Int
  replicateM t $ do
    n <- readLn :: IO Int
    z <- replicateM n $ do
      map read . words <$> getLine
    print $ solve z

solve :: (Ord a, Num a) => [[a]] -> Int
solve list = if best m then i else -1
  where
    (i, m) = foldl1 (\a b -> if (better `on` snd) a b then a else b) $ zip [1..] list
    better a b = length (filter id $ zipWith (<=) a b) >= 3
    best a = all (better a) list

import Control.Monad (replicateM)
import Data.List ( elemIndex )
import Data.Maybe ( fromJust )
import Data.Function (on)

main :: IO [()]
main = do
  t <- readLn :: IO Int
  replicateM t $ do
    n <- readLn :: IO Int
    z <- replicateM n $ do
      map read . words <$> getLine
    print $ solve z

solve :: (Ord a, Num a) => [[a]] -> Int
solve list = if best m then i else -1
  where
    (i, m) = foldl1 (\a b -> if (better `on` snd) a b then a else b) $ zip [1..] list
    better a b = length (filter id $ zipWith (<) a b) >= 3
    best a = length (filter id $ map (better a) list) == length list - 1

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

import Data.Array.Unboxed

better :: Array Int (UArray Int Int) -> Int -> Int -> Int
better arr x y = let
  gt = (!! 2) $ sort $ zipWith (<) (elems $ arr ! x) (elems $ arr ! y)
  in  if  gt  then  x  else  y

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n] <- readInts
    r <- listArray (1, n) <$> replicateM n (listArray (1, 5) <$> readInts)
    let
      opt = foldl' (better r) n $ [1 .. n] ++ [1 .. n]
      isOK = and [better r opt i == opt | i <- [1 .. n]]
    putInts [if  isOK  then  opt  else  0-1]

type SIO = StateT P.ByteString IO

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

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

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

import Control.Monad
import Data.Function

solve :: IO ()
solve = do
    n <- readLn :: IO Int
    r <- replicateM n readMany :: IO [[Int]]
    let sup a b = length (filter id $ zipWith (<) a b) >= 3
        allSup a = length (filter id $ map (sup a) r) == n - 1
        (i, m) = foldr1 (\a b -> if (sup `on` snd) a b then a else b) $ zip [1..] r
    print $ if allSup m then i else -1

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

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

{-# LANGUAGE Strict #-}
{-# LANGUAGE LambdaCase #-}
import Control.Applicative (liftA2)
import Control.Monad (replicateM)
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromJust, fromMaybe)

main :: IO ()
main = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))

testCase :: Scanner String
testCase = do
  n <- int
  xs <- n >< (5 >< int)
  return . show . fromMaybe (-1) . solve $ xs `zip` [1..]

solve :: [([Int], Int)] -> Maybe Int
solve xs
  | all (win cs . fst) xs = Just i
  | otherwise = Nothing
  where
    (cs, i) = foldl1 better xs
    better ps qs = if win (fst ps) (fst qs) then ps else qs
    win ls rs = ls == rs || count True (zipWith (<) ls rs) >= 3

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

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

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

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

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

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

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

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

(><) = times

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

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

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Data.Maybe
import Prelude as P

import Data.Word (Word8)
import Data.Int (Int64)
import qualified Data.Bits as Bits
import qualified Data.Char as Char
import qualified Data.Ratio as Rat

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

import qualified Data.ByteString as Bs
import qualified System.IO as Io
--import Data.IntSet

issuperior :: [Int] -> [Int] -> Bool
issuperior xs ys = length (filter (==True) $ zipWith (<) xs ys) > div total 2
  where total = length xs

superior :: [Int] -> [Int] -> [Int]
superior xs ys = if issuperior xs ys then xs else ys

winner [xs] = xs
winner xxs = winner $ snd $ foldl (\(prev, acc) xs -> if null prev then (xs, acc) else ([], (superior xs prev : acc))) ([], []) xxs

solve :: IO ()
solve = do
  n <- readLn :: IO Int
  a <- readintrows n
  let best = winner a
      cnt = length $ filter (issuperior best) a
      bestidx = if cnt < n-1 then -1 else (fromMaybe 0 $ findIndex (==best) a) + 1
    in print bestidx

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

----------------------------------------------------------------------------------------
readrows :: (Integral b) => b -> IO [String]
readrows 0 = return []
readrows n = do
  row <- getLine
  l <- readrows $ n-1
  return (row : l)

readintrows :: (Integral a, Integral b) => b -> IO [[a]]
readintrows 0 = return []
readintrows n = do
  row <- readInts
  l <- readintrows $ n-1
  return (row : l)

parseInt :: (Integral a) => Bs.ByteString -> a
parseInt xs = snd $ Bs.foldr (\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48)))) (1, 0) xs

readInts :: (Integral a) => IO [a]
readInts =  map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine
  where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs


import Control.Monad
import Data.List

solve :: [Int] -> Bool
solve li = let
  sli = reverse $ sort li
  uli = map head $ group sli
  in  li /= uli

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    _nStr <- getLine
    a <- map read . words <$> getLine
    putStrLn $ if  solve a
      then "YES"
      else "NO"

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NumDecimals #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}

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

import Data.Char
import Data.List
import Data.Maybe

import qualified Data.ByteString.Char8 as B

import Data.Array.ST.Safe
import Data.STRef

-- import Debug.Trace
import Text.Printf

readInt = readLn :: IO Int
readInteger = readLn :: IO Integer
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

modifyArray a i f = writeArray a i =<< f <$> readArray a i

printList [a] = print a
printList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as

main = readInt >>= flip replicateM solve >>= mapM_ ( putStrLn . which "YES" "NO" )

solve = do
	n <- readInt
	as <- readInts
	let
		sorted = sort as
	return $ ( length $ group $ sorted ) /= n || sorted /= reverse as

import Control.Monad
import Control.Monad.ST
import Data.Array
import qualified Data.Array.ST.Safe as S
import qualified Data.Array.Unboxed as U
import Data.Foldable
import Data.List

same :: [Int] -> Bool
same [] = False
same [x] = False
same (a : b : xs) = a == b || same (b : xs)

sorted :: [Int] -> Bool
sorted [] = True
sorted [x] = True
sorted (a : b : xs) = a >= b && sorted (b : xs)

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    _ <- getLine
    v <- map read . words <$> getLine
    if (not (same (sort v)) && sorted v)
      then putStrLn "NO"
      else putStrLn "YES"

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NumDecimals #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}

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

import Data.Char
import Data.List
import Data.Maybe

import qualified Data.ByteString.Char8 as B

import Data.Array.ST.Safe
import Data.STRef

import Text.Printf

readInt = readLn :: IO Int
readInteger = readLn :: IO Integer
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

modifyArray a i f = writeArray a i =<< f <$> readArray a i

printList [a] = print a
printList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as

main = readInt >>= flip replicateM solve >>= mapM_ ( putStrLn . which "YES" "NO" )

solve = do
	n <- readInt
	as <- readInts
	let
		sorted = sort as
	return $ ( length $ group $ sorted ) == n && sorted == reverse as

import Control.Monad
import Control.Monad.ST
import Data.Array
import qualified Data.Array.ST.Safe as S
import qualified Data.Array.Unboxed as U
import Data.Foldable
import Data.List

same :: [Int] -> Bool
same [] = True
same [x] = True
same (a : b : xs) = a == b && same (b : xs)

sorted :: [Int] -> Bool
sorted [] = True
sorted [x] = True
sorted (a : b : xs) = a <= b && sorted (b : xs)

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    _ <- getLine
    v <- map read . words <$> getLine
    if (not (same v) && sorted (reverse v))
      then putStrLn "NO"
      else putStrLn "YES"


{-# LANGUAGE BangPatterns #-}
module Main where

import Control.Monad
import Control.Monad.ST
import Data.Array.ST
import Data.Array.Unboxed
import Data.List (foldl')

readInts :: IO [Int]
readInts = liftM (map read . words) getLine

modSum :: Int -> Int -> Int -> Int
modSum m a b = (a + b) `rem` m

solve :: Int -> Int -> Int -> [Int] -> Int
solve numLines numErrors modulo errors =
    runST $ do
      let numCoders = length errors
          verrors   = listArray (0, numCoders - 1) errors :: UArray Int Int
          msum      = modSum modulo
          bounds    = ((0, 0), (numLines, numErrors))
      table <- newArray bounds 0 :: ST s (STUArray s (Int, Int) Int)

      writeArray table (0, 0) 1
      forM_ [0 .. numCoders - 1] $ \c ->
          do forM_ (range bounds) $ \ix@(l, r) ->
                 do a <- readArray table ix
                    b <- if l >= 1 && verrors ! c <= r
                         then readArray table (l - 1, r - verrors ! c)
                         else return 0
                    writeArray table ix (a `msum` b)
      vs <- forM [0 .. numErrors] $ \e -> readArray table (numLines, e)
      return $ foldl' msum 0 vs

main :: IO ()
main =
    do [numCoders, numLines, numErrors, modulo] <- readInts
       errors                                   <- readInts
       when (numCoders /= length errors) $ fail "Wrong input format"
       print $ solve numLines numErrors modulo errors

{-# LANGUAGE BangPatterns #-}
module Main where

import Control.Monad
import Control.Monad.ST
import Data.Array.ST
import Data.Array.Unboxed
import Data.List (foldl')

modSum :: Int -> Int -> Int -> Int
modSum m a b = (a + b) `rem` m

solve :: Int -> Int -> UArray Int Int -> Int -> Int
solve numLines numErrors errors modulo =
    runST $ do
      let coders      = bounds errors
          msum        = modSum modulo
          tableBounds = ((0, 0), (numLines, numErrors))
      table <- newArray tableBounds 0 :: ST s (STUArray s (Int, Int) Int)
      writeArray table (0, 0) 1
      forM_ (range coders) $ \c ->
          do forM_ (range tableBounds) $ \ix@(l, e) ->
                 do let ce = errors ! c
                    a <- readArray table ix
                    b <- if l >= 1 && ce <= e
                         then readArray table (l - 1, e - ce)
                         else return 0
                    writeArray table ix (a `msum` b)
      foldM (\r v -> liftM (msum r) (readArray table (numLines, v))) 0 [0 .. numErrors]

readInts :: IO [Int]
readInts = liftM (map read . words) getLine

main :: IO ()
main =
    do [numCoders, numLines, numErrors, modulo] <- readInts
       errors <- liftM (listArray (0, numCoders - 1)) readInts
       print $ solve numLines numErrors errors modulo

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Exception hiding (mask)
import Control.Monad hiding (foldM, foldM_)
import Control.Monad.ST
import Data.Array.Base hiding (readArray, writeArray)
import Data.Array.ST (runSTUArray, runSTArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.IntMap as IM
import qualified Data.Set as S
import qualified Data.IntSet as IS
import Data.STRef
import GHC.Arr (Array, STArray, Ix(..))
import Debug.Trace

main :: IO ()
main = do
  [n,m,b,v] <- map read.words <$> getLine
  xs <- map readInt.B.words <$> B.getLine
  print $ solve n m b v xs

solve :: Int -> Int -> Int -> Int -> [Int] -> Int
solve n m b v xs = runST $ do

  let x +% y = (x + y) `rem` v

  dp <- newArray ((0, 0), (m, b)) 0 :: ST s (STUArray s (Int, Int) Int)

  writeArray dp (0, 0) 1

  forM_ xs $ \x -> do
    rep (m + 1) $ \i -> do
      rep (b + 1) $ \j -> do
        when (i + 1 <= m && j + x <= b) $ do
          (+%) <$> readArray dp (i, j) >>= modifyArray dp (i + 1, j + x)

  foldM 0 [0..b] $ \ !acc i -> do
    (acc+%) <$> readArray dp (m, i)

------------------------------------------------------------------------------
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs=case B.readInt bs of{Just(n,_)->n;_->error$"readInt error : bs = "++show bs;}
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep n f=foldr((>>).f)(return())[0..n-1]
rev n f=foldr((>>).f.negate)(return())[1-n..0]
for :: Monad m => Int -> Int -> (Int -> m ()) -> m ()
for a b f=foldr((>>).f)(return())[a..b]
{-# INLINE rep #-}
{-# INLINE rev #-}
{-# INLINE for #-}
foldM :: (Monad m) => a -> [b] -> (a -> b -> m a) -> m a
foldM a xs f=foldr((>=>).flip f)return xs$a
{-# INLINE foldM #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}
(!) :: (IArray a e, Ix i) => a i e -> i -> e
(!) a i=unsafeAt a$unsafeIndex(bounds a)i
{-# INLINE (!) #-}
readArray :: (MArray a e m, Ix i) => a i e -> i -> m e
readArray a i=do lr<-getBounds a;unsafeRead a$unsafeIndex lr i
{-# INLINE readArray #-}
writeArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ()
writeArray a i e=do lr<-getBounds a;unsafeWrite a(unsafeIndex lr i)e
{-# INLINE writeArray #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=do lr<-getBounds a;unsafeModify a(unsafeIndex lr i)f
{-# INLINE modifyArray #-}

{-# LANGUAGE BangPatterns #-}
module Main where

import Control.Monad
import Control.Monad.ST
import Data.Array.ST
import Data.Array.Unboxed
import Data.List (foldl')

modSum :: Int -> Int -> Int -> Int
modSum m a b = (a + b) `rem` m

solve :: Int -> Int -> UArray Int Int -> Int -> Int
solve numLines numErrors errors modulo =
    runST $ do
      let coders      = bounds errors
          msum        = modSum modulo
          tableBounds = ((0, 0), (numLines, numErrors))
      table <- newArray tableBounds 0 :: ST s (STUArray s (Int, Int) Int)
      writeArray table (0, 0) 1
      forM_ (range coders) $ \c ->
          do forM_ (range tableBounds) $ \ix@(l, e) ->
                 do let ce = errors ! c
                    a <- readArray table ix
                    b <- if l >= 1 && ce <= e
                         then readArray table (l - 1, e - ce)
                         else return 0
                    writeArray table ix (a `msum` b)
      foldM (\r v -> liftM (r+) (readArray table (numLines, v))) 0 [0 .. numErrors]

readInts :: IO [Int]
readInts = liftM (map read . words) getLine

main :: IO ()
main =
    do [numCoders, numLines, numErrors, modulo] <- readInts
       errors <- liftM (listArray (0, numCoders - 1)) readInts
       print $ solve numLines numErrors errors modulo


import Control.Monad
import Data.List

_in l r x = l <= x && x <= r
getA = fmap (map read . words) getLine
std [a,b,c,d] = map fromIntegral [min a c, min b d, max a c, max b d]
gao l = and $ zipWith3 (\i j [a,b,c,d] -> _in a c i && _in b d j) (f x z) (f y z) (head l:l) where
	(x,y,z) = unzip3 $ map (\[a,b,c,d] -> ((a+c)/2, (b+d)/2, (c-a)^3)) l
	f p m = zipWith (/) (scanr1 (+) $ zipWith (*) p m) (scanr1 (+) m)
main = do
	[n] <- getA
	a <- replicateM n getA
	putStrLn $ show $ maximum $ map length $ takeWhile gao $ inits $ map std a

main = interact f
f input = output where
  n0:bricks0 = lines input
  n = read n0::Int
  bricks = map (map (read::String->Float)) $ map words bricks0
  output = show ans
  center [[x1,y1,x2,y2]] = ((x1+x2)/2,(y1+y2)/2,abs((x2-x1)^3))
  center (x:xs) = (g x1 x2,g y1 y2,w1+w2) where
    (x1,y1,w1) = center [x]
    (x2,y2,w2) = center xs
    g x y = (x*w1+y*w2)/(w1+w2)
  stable [_] = True
  stable ([x1,y1,x2,y2]:xs) = stable xs && (x-x1)*(x-x2)<=0 && (y-y1)*(y-y2)<=0 where
    (x,y,_) = center xs
  ans = length $ takeWhile id [stable $ take i bricks|i<-[1..n]]

cdg (a,b,w) (x,y,z,t) = (a + (x + z) * nw, b + (y + t) * nw, w + nw) where nw = (z-x)*(z-x)*(z-x)

isOK [] _ = True
isOK ((h0x,h0y,h1x,h1y):hs) (x,y,w)
  | x < h0x * 2 * w = False
  | x > h1x * 2 * w = False
  | y < h0y * 2 * w = False
  | y > h1y * 2 * w = False
  | otherwise = isOK hs (cdg (x,y,w) (h0x,h0y,h1x,h1y))

solve v n = [t | t <- [1..n], isOK ( reverse (take (t - 1) v) ) (cdg (0,0,0) (v !! (t - 1)))]

intrprt [] n = n
intrprt (x:xs) n
  | x == n = intrprt xs (n + 1)
  | otherwise = n

prc (x1,y1,x2,y2) = ((min x1 x2), (min y1 y2), (max x1 x2), (max y1 y2))

readVector 0 = return []
readVector n = do
  [x,y,z,t] <- fmap ( (map (\x -> read x::Integer)) . words ) getLine
  rest <- (readVector (n - 1))
  return ((prc (x,y,z,t)):rest)

main = do
  n <- readLn::IO Int
  v <- (readVector n)
  print $ (intrprt (solve v n) 1) - 1

import Control.Monad
import Data.List

_in l r x = l <= x && x <= r
getA = fmap (map read . words) getLine
std [a,b,c,d] = map fromIntegral [min a c, min b d, max a c, max b d]
gao l = and $ zipWith3 (\i j [a,b,c,d] -> _in a c i && _in b d j) (f x z) (f y z) (head l:l) where
	(x,y,z) = unzip3 $ map (\[a,b,c,d] -> ((a+c)/2, (b+d)/2, (c-a)^3)) l
	f p m = zipWith (/) (scanr1 (+) $ zipWith (*) p m) (scanr1 (+) m)
main = do
	[n] <- getA
	a <- replicateM n getA
	putStrLn $ show $ maximum $ map length $ filter gao $ inits $ map std a

import Data.Char (ord)

cdg (a,b,w) (x,y,z,t) = (a + (x + z) * nw, b + (y + t) * nw, w + nw) where nw = (z-x)*(z-x)

isOK [] _ = True
isOK ((h0x,h0y,h1x,h1y):hs) (x,y,w)
  | x < h0x * 2 * w = False
  | x > h1x * 2 * w = False
  | y < h0y * 2 * w = False
  | y > h1y * 2 * w = False
  | otherwise = isOK hs (cdg (x,y,w) (h0x,h0y,h1x,h1y))

solve v n = maximum [t | t <- [1..n], isOK ( reverse (take (t - 1) v) ) (cdg (0,0,0) (v !! (t - 1)))]

prc (x1,y1,x2,y2) = ((min x1 x2), (min y1 y2), (max x1 x2), (max y1 y2))

readVector 0 = return []
readVector n = do
  [x,y,z,t] <- fmap ( (map (\x -> read x::Int)) . words ) getLine
  rest <- (readVector (n - 1))
  return ((prc (x,y,z,t)):rest)

main = do
  n <- readLn::IO Int
  v <- (readVector n)
  print $ solve v n

cdg (a,b,w) (x,y,z,t) = (a + (x + z) * nw, b + (y + t) * nw, w + nw) where nw = (z-x)*(z-x)*(z-x)

isOK [] _ = True
isOK ((h0x,h0y,h1x,h1y):hs) (x,y,w)
  | x < h0x * 2 * w = False
  | x > h1x * 2 * w = False
  | y < h0y * 2 * w = False
  | y > h1y * 2 * w = False
  | otherwise = isOK hs (cdg (x,y,w) (h0x,h0y,h1x,h1y))

solve v n = maximum [t | t <- [1..n], isOK ( reverse (take (t - 1) v) ) (cdg (0,0,0) (v !! (t - 1)))]

prc (x1,y1,x2,y2) = ((min x1 x2), (min y1 y2), (max x1 x2), (max y1 y2))

readVector 0 = return []
readVector n = do
  [x,y,z,t] <- fmap ( (map (\x -> read x::Integer)) . words ) getLine
  rest <- (readVector (n - 1))
  return ((prc (x,y,z,t)):rest)

main = do
  n <- readLn::IO Int
  v <- (readVector n)
  print $ solve v n

import Data.Char (ord)

cdg (a,b,w) (x,y,z,t) = (a + (x + z) * nw, b + (y + t) * nw, w + nw) where nw = (z-x)*(z-x)*(z-x)

isOK [] _ = True
isOK ((h0x,h0y,h1x,h1y):hs) (x,y,w)
  | x < h0x * 2 * w = False
  | x > h1x * 2 * w = False
  | y < h0y * 2 * w = False
  | y > h1y * 2 * w = False
  | otherwise = isOK hs (cdg (x,y,w) (h0x,h0y,h1x,h1y))

solve v n = maximum [t | t <- [1..n], isOK ( reverse (take (t - 1) v) ) (cdg (0,0,0) (v !! (t - 1)))]

prc (x1,y1,x2,y2) = ((min x1 x2), (min y1 y2), (max x1 x2), (max y1 y2))

readVector 0 = return []
readVector n = do
  [x,y,z,t] <- fmap ( (map (\x -> read x::Int)) . words ) getLine
  rest <- (readVector (n - 1))
  return ((prc (x,y,z,t)):rest)

main = do
  n <- readLn::IO Int
  v <- (readVector n)
  print $ solve v n

import Data.Char (ord)

cdg (a,b) (x,y,z,t) = (a + x + z, b + y + t)

isOK [] _ _ = True
isOK ((h0x,h0y,h1x,h1y):hs) (x,y) n
  | x < h0x * 2 * n = False
  | x > h1x * 2 * n = False
  | y < h0y * 2 * n = False
  | y > h1y * 2 * n = False
  | otherwise = isOK hs (cdg (x,y) (h0x,h0y,h1x,h1y)) (n + 1)

solve v n = maximum [t | t <- [1..n], isOK ( reverse (take (t - 1) v) ) (cdg (0,0) (v !! (t - 1))) 1]

readVector 0 = return []
readVector n = do
  [x,y,z,t] <- fmap ( (map (\x -> read x::Int)) . words ) getLine
  rest <- (readVector (n - 1))
  return ((x,y,z,t):rest)

main = do
  n <- readLn::IO Int
  v <- (readVector n)
  print $ solve v n

cdg::(Integer,Integer,Integer)->(Integer,Integer,Integer,Integer)->(Integer,Integer,Integer)
cdg (a,b,w) (x,y,z,t) = (a + (x + z) * nw, b + (y + t) * nw, w + nw) where nw = (z-x)*(z-x)*(z-x)

isOK::[(Integer,Integer,Integer,Integer)]->(Integer,Integer,Integer)->Bool
isOK [] _ = True
isOK ((h0x,h0y,h1x,h1y):hs) (x,y,w)
  | x < h0x * 2 * w = False
  | x > h1x * 2 * w = False
  | y < h0y * 2 * w = False
  | y > h1y * 2 * w = False
  | otherwise = isOK hs (cdg (x,y,w) (h0x,h0y,h1x,h1y))

solve::[(Integer,Integer,Integer,Integer)]->Int->Int
solve v n = maximum [t | t <- [1..n], isOK ( reverse (take (t - 1) v) ) (cdg (0,0,0) (v !! (t - 1)))]

prc::(Integer,Integer,Integer,Integer)->(Integer,Integer,Integer,Integer)
prc (x1,y1,x2,y2) = ((min x1 x2), (min y1 y2), (max x1 x2), (max y1 y2))

readVector::Int->IO [(Integer,Integer,Integer,Integer)]
readVector 0 = return []
readVector n = do
  [x,y,z,t] <- fmap ( (map (\x -> read x::Integer)) . words ) getLine
  rest <- (readVector (n - 1))
  return ((prc (x,y,z,t)):rest)

main = do
  n <- readLn::IO Int
  v <- (readVector n)
  print $ solve v n

import Data.Char (ord)

cdg (a,b) (x,y,z,t) = (a + x + z, b + y + t)

isOK [] _ _ = True
isOK ((h0x,h0y,h1x,h1y):hs) (x,y) n
  | x < h0x * 2 * n = False
  | x > h1x * 2 * n = False
  | y < h0y * 2 * n = False
  | y > h1y * 2 * n = False
  | otherwise = isOK hs (cdg (x,y) (h0x,h0y,h1x,h1y)) (n + 1)

solve v n = maximum [t | t <- [1..n], isOK ( reverse (take (t - 1) v) ) (cdg (0,0) (v !! (t - 1))) 1]

prc (x1,y1,x2,y2) = ((min x1 x2), (min y1 y2), (max x1 x2), (max y1 y2))

readVector 0 = return []
readVector n = do
  [x,y,z,t] <- fmap ( (map (\x -> read x::Int)) . words ) getLine
  rest <- (readVector (n - 1))
  return ((prc (x,y,z,t)):rest)

main = do
  n <- readLn::IO Int
  v <- (readVector n)
  print $ solve v n


-- pragmas.hs {{{
-- vim: foldmethod=marker
{-# LANGUAGE AllowAmbiguousTypes        #-}
{-# LANGUAGE BinaryLiterals             #-}
{-# LANGUAGE ConstraintKinds            #-}
{-# LANGUAGE DataKinds                  #-}
{-# LANGUAGE DeriveFoldable             #-}
{-# LANGUAGE DeriveFunctor              #-}
{-# LANGUAGE DeriveGeneric              #-}
{-# LANGUAGE DeriveTraversable          #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE FlexibleInstances          #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase                 #-}
{-# LANGUAGE MagicHash                  #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE MultiWayIf                 #-}
{-# LANGUAGE RankNTypes                 #-}
{-# LANGUAGE RecordWildCards            #-}
{-# LANGUAGE ScopedTypeVariables        #-}
{-# LANGUAGE StandaloneDeriving         #-}
{-# LANGUAGE TupleSections              #-}
{-# LANGUAGE TypeApplications           #-}
{-# LANGUAGE TypeFamilies               #-}
{-# LANGUAGE TypeInType                 #-}
{-# LANGUAGE TypeOperators              #-}
{-# LANGUAGE UnboxedTuples              #-}
{-# LANGUAGE UndecidableInstances       #-}
-- pragmas.hs }}}
module Main where

import           Control.Monad         (replicateM_)
import           Data.Array            (Array, (!))
import           Data.Bool             (bool)
import qualified Data.ByteString.Char8 as C
import           Data.Ix               (Ix)
import           Data.List             (unfoldr)

data Player = Alice | Bob deriving Show

solve :: [Int] -> Player
solve xs = bool Bob Alice (head xs /= minimum xs)

docase :: IO ()
docase = do
  _ <- getInt
  xs <- getInts
  print $ solve xs

main :: IO ()
main = getInt >>= flip replicateM_ docase

readInt :: C.ByteString -> Int
readInt s = let Just (i,_) = C.readInt s in i :: Int

readInt2 :: C.ByteString -> (Int, Int)
readInt2 u = (a, b)
  where
  Just (a,v) = C.readInt u
  Just (b,_) = C.readInt (C.tail v)

readInts :: C.ByteString -> [Int]
readInts = unfoldr go where
    go s = do
        (n,s1) <- C.readInt s
        let s2 = C.dropWhile (==' ') s1
        pure (n,s2)

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

getInt2 :: IO (Int, Int)
getInt2 = readInt2 <$> C.getLine

getInts :: IO [Int]
getInts = readInts <$> C.getLine

{-# 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 { as :: [Int] }

type Output = Bool

input :: Scanner TC
input = do
  as <- numberOf int
  return TC {..}

solve :: TC -> Output
solve TC {..} = head as > minimum as

output :: Int -> Output -> C.ByteString
output ix = bool "Bob" "Alice" >>> C.pack

----- </Solution> -------------------------------------------------------------

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

----- Template ----------------------------------------------------------------

-- Debug
debug :: Show a => a -> a

#ifdef ONLINE_JUDGE
debug = id
#else
debug a = trace (show a) a
#endif

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


import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

powMod :: Int64 -> Int64 -> Int64
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

getAllPows :: Int64 -> Int64 -> Int64 -> Int64 -> [Int64]
getAllPows a n p cur
    | p == n = [cur]
    | otherwise = cur : (getAllPows a n (p + 1) (2 `multMod` cur))

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

powMod' :: Int64 -> Int64
powMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr

sub :: Int64 -> Int64 -> Int64
sub a b = (a + modPr - b) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64
solve x p n ps pl = ((x `multMod` (ps `sub` 1)) + modPr - (x `multMod` (pl `sub` 1))) `mod` modPr
    -- | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr
    -- | otherwise = 123

solve' :: [Int64] -> Int64 -> Int64 -> [Int64] -> [Int64] -> Int64
solve' [] _ _ _ _ = 0
solve' (x:xs) p n (ps:pss) (pl:pls) =  ((solve' xs (p + 1) n pss pls) + (solve x p n ps pl)) `mod` modPr

getInt64s :: IO [Int64]
getInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    -- xs <- sort . map (read :: String -> Int64) . words <$> getLine
    xs <- sort <$> getInt64s
    let ps = getAllPows 2 (n - 1) 0 1
    -- putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]
    putStrLn . show $ solve' xs 0 n ps $ reverse ps

module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Data.Int
import Data.Array.Unboxed

readInt = maybe undefined fst . B.readInt
readInts = (readInt <$>) . B.words

pairs [] = []
pairs (x:xs) = [(x, x') | x' <- xs] ++ pairs xs

chiến :: Int -> [Int64] -> Int64
chiến n = foldl' (\s (i, x) -> s +% (x *% (twoPows!i) - x *% (twoPows!(n - i - 1)))) 0 . zip [0..] . sort
  where
    m = 1000000007
    twoPows = listArray (0, n) $ iterate (*% 2) 1 :: UArray Int Int64
    a +% b = (a + b) `mod` m
    a *% b = (a * b) `mod` m

main = do
  n <- readInt <$> B.getLine
  xs <- map fromIntegral . readInts <$> B.getLine
  print $ chiến n xs

{-
x1 <= x2 <= ... <= xn
12
13
14
23
24
34
123 -> 13
124 -> 14
134 -> 14
234 -> 24
1234 -> 14

14 -> 3 -> 4
13 -> 2 -> 2
12 -> 1 -> 1
24 ->

xi * (2^i) - xi * 2^(n-i-1)
-}

{-# LANGUAGE BangPatterns #-}

import Data.Maybe
import Data.Int
import Data.Bool
import Data.List
import Control.Monad

modulant :: Int64
modulant = 1000000007

twos :: [Int64]
twos = work 1
    where
        work c = c : work (let x = 2*c in if x > modulant then x - modulant else x)

-- >>> all (>= 0) $ take 100000 ((* 1000000007) <$> twos)
-- True
--
main :: IO ()
main = do
    getLine
    sorted <- liftM (\l -> (sort :: [Int64] -> [Int64]) $ read <$> (words l)) getLine
    let a = foldl' (\acc s -> (acc + s) `mod` modulant) 0 $ (uncurry (*)) <$> zip twos sorted
        b = foldl' (\acc s -> (acc + s) `mod` modulant) 0 $ (uncurry (*)) <$> (zip twos $ reverse sorted)
    print $ (a - b) `mod` modulant

import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

getAllPows :: Int64 -> Int64 -> Int64 -> Int64 -> [Int64]
getAllPows a n p cur
    | p == n = [cur - 1]
    | otherwise = (cur `sub` 1) : (getAllPows a n (p + 1) (2 `multMod` cur))

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

sub :: Int64 -> Int64 -> Int64
sub a b = (a + modPr - b) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64
solve x p n ps pl = ((x `multMod` ps) + modPr - (x `multMod` pl)) `mod` modPr

solve' :: [Int64] -> Int64 -> Int64 -> [Int64] -> [Int64] -> Int64
solve' [] _ _ _ _ = 0
solve' (x:xs) p n (ps:pss) (pl:pls) =  ((solve' xs (p + 1) n pss pls) + (solve x p n ps pl)) `mod` modPr

getInt64s :: IO [Int64]
getInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    xs <- sort <$> getInt64s
    let ps = getAllPows 2 (n - 1) 0 1
    putStrLn . show $ solve' xs 0 n ps $ reverse ps

import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

powMod :: Int64 -> Int64 -> Int64
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

powMod' :: Int64 -> Int64
powMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64
solve x p n ps pl = ((x `multMod` (ps - 1)) + modPr - (x `multMod` (pl - 1))) `mod` modPr
    -- | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr
    -- | otherwise = 123

solve' :: [Int64] -> Int64 -> Int64 -> Int64 -> Int64 -> Int64
solve' [] _ _ _ _ = 0
solve' (x : xs) p n ps pl =  ((solve' xs (p + 1) n (ps `multMod` 2) (pl `div` 2)) + (solve x p n ps pl)) `mod` modPr

getInt64s :: IO [Int64]
getInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    -- xs <- sort . map (read :: String -> Int64) . words <$> getLine
    xs <- sort <$> getInt64s
    let ps = 1
        pl = powMod 2 $ n - 1
    -- putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]
    putStrLn . show $ solve' xs 0 n ps pl

import Data.List
import Control.Applicative

modPr = 1000000009 :: Integer

powMod :: Integer -> Integer -> Integer
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

powMod' :: Integer -> Integer -> Integer
powMod' a b = (powMod a b) - 1

solve :: Integer -> Integer -> Integer -> Integer
solve x 0 n = (- (x * (powMod' 2 $ n - 1)))
solve x p n
    | p == (n - 1) = (x * (powMod' 2 $ n - 1))
    | otherwise = (- (x * (powMod' 2 $ p))) + (x * (powMod' 2 $ n - p - 1))

main :: IO ()
main = do
    n <- (read :: String -> Integer) <$> getLine
    xs <- sort . map (read :: String -> Integer) . words <$> getLine
    -- putStrLn . show $ zip xs [0..(n - 1)]
    putStrLn . show $ foldl' (\ acc (x, p) -> acc + (solve x p n)) 0 $ zip xs [0..(n - 1)]

import Data.List
import Control.Applicative

modPr = 1000000009 :: Integer

powMod :: Integer -> Integer -> Integer
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

powMod' :: Integer -> Integer
powMod' x = (powMod 2 x) - 1

multMod :: Integer -> Integer -> Integer
multMod a b = (a * b) `mod` modPr

solve :: Integer -> Integer -> Integer -> Integer
solve x 0 n = (modPr - (x `multMod` (powMod' $ n - 1))) `mod` modPr
solve x p n
    | p == (n - 1) = (x `multMod` (powMod' $ n - 1))
    | otherwise =  ((x `multMod` (powMod' $ n - p - 1)) + modPr - (x `multMod` (powMod' p))) `mod` modPr

main :: IO ()
main = do
    n <- (read :: String -> Integer) <$> getLine
    xs <- sort . map (read :: String -> Integer) . words <$> getLine
    -- putStrLn . show $ zip xs [0..(n - 1)]
    putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]

import Data.List
import Control.Applicative

modPr = 1000000009 :: Integer

powMod :: Integer -> Integer -> Integer
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

multMod :: Integer -> Integer -> Integer
multMod a b = (a * b) `mod` modPr

powMod' :: Integer -> Integer
powMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr

solve :: Integer -> Integer -> Integer -> Integer
solve x p n = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr

{-
solve :: Integer -> Integer -> Integer -> Integer
solve x p n
    | p == 0 = (modPr - (x `multMod` (powMod' $ n - 1))) `mod` modPr
    | p == (n - 1) = (x `multMod` (powMod' $ n - 1)) `mod` modPr
    | otherwise = ((x `multMod` (powMod' $ n - p - 1)) + modPr - (x `multMod` (powMod' p))) `mod` modPr
    where multMod a b = (a * b) `mod` modPr
          powMod' x = (powMod 2 x) - 1
-}

main :: IO ()
main = do
    n <- (read :: String -> Integer) <$> getLine
    xs <- sort . map (read :: String -> Integer) . words <$> getLine
    -- putStrLn . show $ zip xs [0..(n - 1)]
    putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]

import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

powMod :: Int64 -> Int64 -> Int64
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

powMod' :: Int64 -> Int64
powMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64
solve x p n
    | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr
    | otherwise = 123

getInt64s :: IO [Int64]
getInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    -- xs <- sort . map (read :: String -> Int64) . words <$> getLine
    xs <- sort <$> getInt64s
    putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]

import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

powMod :: Int64 -> Int64 -> Int64
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

powMod' :: Int64 -> Int64
powMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64
solve x p n
    | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr
    | otherwise = 123

solve' :: [Int64] -> Int64 -> Int64 -> Int64
solve' [] _ _ = 0
solve' (x : xs) p n =  ((solve' xs (p + 1) n) + (solve x p n)) `mod` modPr

getInt64s :: IO [Int64]
getInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    -- xs <- sort . map (read :: String -> Int64) . words <$> getLine
    xs <- sort <$> getInt64s
    -- putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]
    putStrLn . show $ solve' xs 0 n

import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

powMod :: Int64 -> Int64 -> Int64
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

powMod' :: Int64 -> Int64
powMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr

sub :: Int64 -> Int64 -> Int64
sub a b = (a + modPr - b) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64
solve x p n ps pl = ((x `multMod` (ps `sub` 1)) + modPr - (x `multMod` (pl `sub` 1))) `mod` modPr
    -- | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr
    -- | otherwise = 123

solve' :: [Int64] -> Int64 -> Int64 -> Int64 -> Int64 -> Int64
solve' [] _ _ _ _ = 0
solve' (x : xs) p n ps pl =  ((solve' xs (p + 1) n (ps `multMod` 2) (pl `div` 2)) + (solve x p n ps pl)) `mod` modPr

getInt64s :: IO [Int64]
getInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    -- xs <- sort . map (read :: String -> Int64) . words <$> getLine
    xs <- sort <$> getInt64s
    let ps = 1
        pl = powMod 2 $ n - 1
    -- putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]
    putStrLn . show $ solve' xs 0 n ps pl

import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

getAllPows :: Int64 -> Int64 -> Int64 -> Int64 -> [Int64]
getAllPows a n p cur
    | p == n = [cur]
    | otherwise = (cur `sub` 1) : (getAllPows a n (p + 1) (2 `multMod` cur))

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

sub :: Int64 -> Int64 -> Int64
sub a b = (a + modPr - b) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64
solve x p n ps pl = ((x `multMod` ps) + modPr - (x `multMod` pl)) `mod` modPr

solve' :: [Int64] -> Int64 -> Int64 -> [Int64] -> [Int64] -> Int64
solve' [] _ _ _ _ = 0
solve' (x:xs) p n (ps:pss) (pl:pls) =  ((solve' xs (p + 1) n pss pls) + (solve x p n ps pl)) `mod` modPr

getInt64s :: IO [Int64]
getInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    xs <- sort <$> getInt64s
    let ps = getAllPows 2 (n - 1) 0 1
    putStrLn . show $ solve' xs 0 n ps $ reverse ps

import Data.List
import Control.Applicative

modPr = 1000000009 :: Integer

powMod :: Integer -> Integer -> Integer
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

multMod :: Integer -> Integer -> Integer
multMod a b = (a * b) `mod` modPr

powMod' :: Integer -> Integer
powMod' x = (powMod 2 x) - 1

solve :: Integer -> Integer -> Integer -> Integer
solve x p n = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr

{-
solve :: Integer -> Integer -> Integer -> Integer
solve x p n
    | p == 0 = (modPr - (x `multMod` (powMod' $ n - 1))) `mod` modPr
    | p == (n - 1) = (x `multMod` (powMod' $ n - 1)) `mod` modPr
    | otherwise = ((x `multMod` (powMod' $ n - p - 1)) + modPr - (x `multMod` (powMod' p))) `mod` modPr
    where multMod a b = (a * b) `mod` modPr
          powMod' x = (powMod 2 x) - 1
-}

main :: IO ()
main = do
    n <- (read :: String -> Integer) <$> getLine
    xs <- sort . map (read :: String -> Integer) . words <$> getLine
    -- putStrLn . show $ zip xs [0..(n - 1)]
    putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]

import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

powMod :: Int64 -> Int64 -> Int64
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

powMod' :: Int64 -> Int64
powMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64
solve x p n
    | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr
    | otherwise = 123

getInt64s :: IO [Int64]
getInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    xs <- sort . map (read :: String -> Int64) . words <$> getLine
    -- xs <- sort <$> getInt64s
    putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]

{-# LANGUAGE BangPatterns #-}

import Data.Maybe
import Data.Int
import Data.Bool
import Data.List
import Control.Monad

modulant :: Int64
modulant = 1000000007

twos :: [Int64]
twos = work 1
    where
        work c = c : work (let x = 2*c in if x > modulant then x - modulant else x)

main :: IO ()
main = do
    getLine
    sorted <- liftM (\l -> (sort :: [Int64] -> [Int64]) $ read <$> (words l)) getLine
    let a = foldl' (\acc s -> (acc + s) `mod` modulant) 0 $ (uncurry (*)) <$> zip twos sorted
        b = foldl' (\acc s -> (acc + s) `mod` modulant) 0 $ (uncurry (*)) <$> (zip twos $ reverse sorted)
    print $ a - b

import Data.Maybe
import Data.Int
import Data.Bool
import Data.List
import Control.Monad

calc :: [Int64] -> Int64
calc = work 0 1
    where
        work acc _ [] = acc
        work acc cnt (x:xs) = work ((acc + x * cnt) `mod` 1000000007) (let c = 2 * cnt in if c > 1000000007 then c - 1000000007 else c) xs

main :: IO ()
main = do
    getLine
    sorted <- liftM (\l -> sort $ read <$> (words l)) getLine
    let a = calc sorted
        b = calc . reverse $ sorted
    print $ a - b

{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Data.Int
import Data.Bits

readInt = maybe undefined fst . B.readInt
readInts = (readInt <$>) . B.words

pairs [] = []
pairs (x:xs) = [(x, x') | x' <- xs] ++ pairs xs

chiến :: [Int64] -> Int64
chiến = foldl' (+%) 0 . map (\((i, x), (i', x')) -> (1 `shiftL`  (i' - i - 1)) *% (x' - x)) . pairs . zip [1..] . sort
  where
    m = 1000000007
    a +% b = (a + b) `mod` m
    a *% b = (a * b) `mod` m

main = do
  B.getLine
  xs <- map fromIntegral . readInts <$> B.getLine
  print $ chiến xs

{-
x1 <= x2 <= ... <= xn
12
13
14
23
24
34
123 -> 13
124 -> 14
134 -> 14
234 -> 24
1234 -> 14

14 -> 3 -> 4
13 -> 2 -> 2
12 -> 1 -> 1
24 ->

xi * (2^i) - xi * 2^(n-i-1)
-}

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

readInt = maybe undefined fst . B.readInt
readInts = (readInt <$>) . B.words

pairs [] = []
pairs (x:xs) = [(x, x') | x' <- xs] ++ pairs xs

chiến n = foldl' (+%) 0 . map (\((i, x), (i', x')) -> (i' - i) *% (x' - x)) . pairs . zip [1..] . sort
  where
    m = 1000000007
    a +% b = (a + b) `mod` m
    a *% b = f a b 0
      where
        f x y acc
          | y == 1 = acc +% x
          | r == 0 = f x2 q acc
          | otherwise = f x2 q (acc +% x)
          where
            (q, r) = y `quotRem` 2
            x2 = x +% x

main = chiến <$> (readInt <$> B.getLine) <*> (readInts <$> B.getLine) >>= print

{-
x1 <= x2 <= ... <= xn
x2-x1: 1
x3-x1: 2
x4-x1: 3
-}


import Data.List

count xs = [(head x, length x) | x <- group(sort xs)]

winner:: [(Int,Int)] -> (Int,Int)
winner [x] = x
winner (x:xs)
    | snd x > snd maxVote = x
    | snd x == snd maxVote && fst x < fst maxVote = x
    | otherwise = maxVote
    where maxVote = winner xs

stage1::[[Int]] -> [Int]
stage1 [] = []
stage1 (v:vs) = fst(winner(zip [1..length v] v)) : stage1 vs

replicateM n x = sequence (replicate n x)

readLine = do
    line <- getLine
    return [read n :: Int| n <- words line]

main = do
    numberStr <- getLine
    let [_,m] = [read n::Int | n <- words numberStr]
    votes <- replicateM m readLine
    print (fst(winner(count(stage1(votes)))))

import Data.List

main =  do
  s <- getLine
  let
    n:m:[] = words s
  s <- sequence (replicate (read m :: Int) getLine)
  let
    d = map words s
    dd = map (\xs -> map (\x -> read x :: Int) xs) d
    cities = sort $ map cityWin dd
    grouped = map (\xs -> (head xs, length xs) ) (group cities)
    r = foldl (\(bc, bcnt) (city, cnt) -> if cnt > bcnt then (city, cnt) else (bc, bcnt)) (head grouped) grouped

  print (fst r)

cityWin::[Int]->Int
cityWin xs = snd $ foldl (\(bx, bp) (x,p) -> if x > bx then (x,p) else (bx, bp)) (head xs, 1)  $ zip xs [1..]

import Data.List as L
import Control.Applicative
import Data.Ord (comparing)

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

maxVote xs = fst $ head $ filter (\x-> snd x == m) (zip [1..] xs)
  where m = maximum xs

maxCity xs = fst $ head $ groupCount xs

groupCount x = zip (map head groupedOnes) (map length groupedOnes)
  where groupedOnes = groupDes x

groupDes x = L.reverse . L.sortBy (comparing length) . L.group . L.reverse . L.sort $ x

main = do
  votes <- map (map toInt . words) . tail . lines <$> getContents
  let ans = maxCity $ map maxVote votes
  print ans

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

rInt = map (\x -> read x::Int) . words

main :: IO()
main = do
    [n,m] <- fmap rInt getLine
    arr <- forM [1..m] $ \i ->do
        l <- fmap rInt getLine
        return l
    let a = elems $ solve (map rSolve arr)
    let (_, ans) = foldl' (\(a,b) (b1,b2)->if b1>a then (b1,b2) else (a,b)) (0,1) $ zip a [1..]
    print ans

rSolve :: [Int] -> Int
rSolve l = v
 where (_,v) = foldl' f (-1,0) $ zip l [1..]
       f (a,b) (c,d) = if c>a then (c,d) else (a,b)

solve :: [Int] -> UArray Int Int
solve l = runSTUArray $ do
    a <- newArray (1,100) 0
    forM_ l $ \i -> do
        x <- readArray a i
        writeArray a i (x+1)
    return a

import Data.Function
import Data.List

main = do
  getLine
  a <- fmap (map (map read . words) . lines) getContents :: IO [[Int]]

  print $ - (head $ maximumBy (compare `on` (\x -> (length x, x))) $ group $  sort $ map (\a -> snd $ maximum $ zipWith (\a b -> (a, -b)) a [1..]) a)

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

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

main = do
    [n, m] <- readInts
    cities <- map (`zip` map negate [1..]) <$> replicateM m readInts
    print . negate . snd . maximum . map (length &&& head) . group . sort . map (snd . maximum) $ cities

import Data.Array
answer::Int -> [[Int]] -> Int
answer m a = elec m (city a)
elec::Int -> [Int] -> Int
elec m a = getMaxIndex (elems (accumArray (+) 0 (1,m) (zip a (repeat 1))))
city::[[Int]] ->[Int]
city a = map getMaxIndex a
getMaxIndex::[Int] -> Int
getMaxIndex a = getMaxIndex0 (-1) 1 0 a
getMaxIndex0::Int -> Int -> Int -> [Int] ->Int
getMaxIndex0 n m r [] = r
getMaxIndex0 n m r a | n >= h = getMaxIndex0 n (m+1) r (tail a)
                     | otherwise = getMaxIndex0 h (m+1) m (tail a)
                          where h = head a
--main = print $ answer 3 [[1,2,3],[2,3,1],[1,2,1]]
-- main = print $ answer 3 [[10,10,3],
--                          [5,1,6],
--                          [2,2,2],
--                          [1,5,7]]
readInput::Int -> IO [[Int]]
readInput 0 = return []
readInput n = do
               w <- getLine
               let a = [read n::Int|n <- (words w)]
               next <- readInput (n-1)
               return ([a] ++ next)
main = do
        w <- getLine
        let ww = words w
        let m = read (ww !! 0)::Int
        let n = read (ww !! 1)::Int
        a <- readInput n
        print $ answer m a

import Data.List
import Data.Tree
import Data.Int
import Data.Word
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
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=   readsolveprint

readsolveprint::IO()
readsolveprint = getLine >>= \ns -> let [_,n]  = (map (read).words) ns in (solve =<< forM [1..n] ( \i -> map (read).words <$>getLine))
solve::[[Word64]]->IO()
solve xs = print $ f $ map (\a-> (length a, head a)) $ group $ sort  $ map (\as-> f as) $ map (\as-> zipWith (\a b -> (b,a)) [1..] as) xs
  where
  f ds = (snd . head .sortBy (\ (a1,a2) (b1,b2) -> a2 `compare` b2). head . groupBy (\ (a1,a2) (b1,b2) -> a1 == b1) . sortBy (\ (a1,a2) (b1,b2) -> b1 `compare` a1)) ds

-- Codeforces 570A

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

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

solve :: [[Int]] -> Int
solve = snd . head . sortBy (\x y -> if (fst x) == (fst y) then compare (snd x) (snd y) else compare (fst y) (fst x)) . map (\x -> (length x, head x)) . group . sort . map (\x -> (+ 1) $ fromJust $ elemIndex (maximum x) x)

import Control.Applicative
import Control.Monad
import Data.Array
-----

--be carefull with the type inference

-----

---------
-- get space separated something

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

---------

---------
-- output [a] in space separated form

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

---------

--------
-- read an integer N, get N lines, make a list consist of them

getListLn :: Read a => IO [a]
getListLn = do n <- readLn
               s <- replicateM n getLine
	       return (map read s)
--------

main = do [n, m] <- getListSp
          votes <- replicateM m getListSp
	  print $ solve votes

solve :: [[Int]] -> Int
solve = maxInd . cntList . (map maxInd)

maxInd :: [Int] -> Int
maxInd xs = rval $ head $ filter ((== maxVal) . lval) $ zip xs [1..]
             where maxVal = foldl1 max xs
	           lval (x, y) = x
		   rval (x, y) = y

cntList :: [Int] -> [Int]
cntList xs = elems $ accumArray (+) 0 (1, maxVal) (zip xs (repeat 1))
              where maxVal = foldl1 max xs

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

process x =   fromJust $ findIndex (==m) x
  where m = maximum x

process1 n x  = process $ elems xx
  where xx = accumArray (+) 0 (0,n-1) $ zip x (repeat 1)

main::IO ()
main=do
   [n,m]<- map read <$> words <$> getLine ::IO [Int]
   x<-(+1) <$> process1 n <$> map process <$> map (map (fromIntegral.fst.fromJust.C.readInteger))<$> map C.words <$> C.lines <$> C.getContents ::IO Int
   print x

import Control.Arrow ((&&&))
import Data.List (elemIndex, group, sort)
import Data.Maybe (fromJust)

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

solve :: [[Int]] -> Int
solve = succ . negate . snd . maximum . map (length &&& negate . head) . group . sort . map maximumIndex

maximumIndex :: Ord a => [a] -> Int
maximumIndex xs = fromJust $ elemIndex (maximum xs) xs

import Data.Function
import Data.List
import Data.Monoid
import Control.Arrow
import Control.Monad
readInts = fmap (map read . words) getLine
winner = fst . maximumBy ((compare `on` snd) `mappend` (flip compare `on` fst))
main = do
  [n,m] <- readInts
  cs <- replicateM m (fmap (zip [1..]) readInts)
  let ws = map winner cs
  print $ winner $ map (head &&& length) $ group $ sort ws

import Data.List
import Data.Maybe
import Data.Function

winner :: [Int] -> Int
winner xs = (+1) . fromJust . elemIndex m $ xs
    where m = maximum xs

solve :: [[Int]] -> Int
solve = head . maximumBy (compare `on` length) . group . reverse . sort . map winner

main = do
    [n,m] <- getList
    xs <- mapM (\_ -> getList) [1..m]
    print $ solve xs

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

import System.IO
import qualified Data.List as L

read_ints :: String -> [Int]
read_ints x = map read (words x) :: [Int]

best :: [[Int]] -> Int
best x = fst $ foldl (\(ans,co) gr -> if length gr > co then (head gr,length gr) else (ans,co) ) (0,0) x

compute :: [Int] -> Int
compute x = best ( L.group $ L.sort x )

solve :: [Int] -> Int
solve x = fst $ foldl (\(ans,co) (x,y) -> if x > co then (y,x) else (ans,co) ) (0,negate 1) ( zip x [1..] )

main = do
	ln <- getLine
	let [n,m] = read_ints ln
	ln <- getContents
	let mat = map read_ints (lines ln)

	let winers = foldl (\ans ln -> solve ln : ans ) [] mat
	-- print winers
	let ans = compute winers
	putStr $ show ans

import Data.Ord (comparing)
import Data.List (maximumBy)
import Data.Monoid
import qualified Data.Map as M

main = interact solve >> putChar '\n'

solve :: String -> String
solve rawInput = winner
    where input = (map . map) read $ map words $ lines rawInput :: [[Int]]
          inData = tail input
          indexed = map (zip [1..]) inData
          winners = map fst $ map (maximumBy $ compareOrder) indexed
          occurList = toOccurList winners
          winner = show $ fst $ maximumBy compareOrder occurList

compareOrder = mappend (comparing snd) (flip $ comparing fst)

toOccurList :: [Int] -> [(Int, Int)]
toOccurList = M.toList . foldr (\x map -> M.insertWith (+) x 1 map) M.empty

import Control.Applicative
import Data.List

mymax s =  snd $ head $ filter (\z-> fst z ==m) $ zip s [1..]
	where m = maximum s

main=do
	[n,m]<-map read.words <$> getLine:: IO [Int]
	s<- map (map read). map words . lines <$> getContents ::IO [[Int]]
	let s1 = group $ sort $ map (mymax) s
	let s2 = maximum (map length s1)
	print $ minimum $ map head $ filter (\z-> length z ==s2) s1

import Control.Arrow ((&&&))
import Data.List (group, sort)

type Input = [[Int]]

parse :: String -> Input
parse = map parseLine . tail . lines
        where parseLine = map read . words

select :: [(Int, Int)] -> Int
select = negate . snd . maximum

solve :: Input -> Int
solve = stage2 . stage1
        where stage1 = map (select. flip zip [-1, -2..]) :: [[Int]] -> [Int]
              stage2 = select . map (length &&& negate . head) . group . sort

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

import Data.List

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

sol (n:_:xs) = snd . minimum . map (\x -> (- length x, head x)) . group . sort . map det $ spl (map negate xs)
    where det ls = snd . minimum $ zip ls [1..]
          spl [] = []
          spl l = take n l : spl (drop n l)

import Data.List
import Control.Monad

main :: IO ()
main = do
        _:m:_ <- getList
        votes <- getLists m
        print $ solve votes

getLists :: (Read a) => Int -> IO [[a]]
getLists nRows = replicateM nRows getList

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

solve :: [[Int]] -> Int
solve = mostCommon . map cityWinner

cityWinner :: [Int] -> Int
cityWinner  = negate . snd . maximum . (`zip` [-1,-2..])

mostCommon :: [Int] -> Int
mostCommon = negate . snd . maximum . fmap (\xs -> (length xs, - head xs)) . group . sort

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

rInt = map (\x -> read x::Int) . words

main :: IO()
main = do
    [n,m] <- fmap rInt getLine
    arr <- forM [1..m] $ \i ->do
        l <- fmap rInt getLine
        return l
    let a = elems $ solve (map rSolve arr)
    print a
    let (_, ans) = foldl' (\(a,b) (b1,b2)->if b1>a then (b1,b2) else (a,b)) (0,1) $ zip a [1..]
    print ans

rSolve :: [Int] -> Int
rSolve l = v
 where (_,v) = foldl' f (0,0) $ zip l [1..]
       f (a,b) (c,d) = if c>a then (c,d) else (a,b)

solve :: [Int] -> UArray Int Int
solve l = runSTUArray $ do
    a <- newArray (1,100) 0
    forM_ l $ \i -> do
        x <- readArray a i
        writeArray a i (x+1)
    return a

import Data.List
import Data.Tree
import Data.Int
import Data.Word
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
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=   readsolveprint
readsolveprint::IO()
readsolveprint = getLine >>= \ns -> let [_,n]  = (map (read).words) ns in (solve =<< forM [1..n] ( \i -> map (read).words <$>getLine))
solve::[[Word64]]->IO()
solve xs = print $ f $ map (\a-> (length a, head a)) $ group $ map (\as-> f as) $ map (\as-> zipWith (\a b -> (b,a)) [1..] as) xs
  where
  f ds = (snd . head .sortBy (\ (a1,a2) (b1,b2) -> a2 `compare` b2). head . groupBy (\ (a1,a2) (b1,b2) -> a1 == b1) . sortBy (\ (a1,a2) (b1,b2) -> b1 `compare` a1)) ds

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
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=   readsolveprint
readsolveprint::IO()
readsolveprint = C.getLine >>= \ns -> let [_,n]  = (map (fst.fromJust.C.readInteger).C.words) ns in (solve =<< forM [1..n] ( \i -> map (fst.fromJust.C.readInteger).C.words <$>C.getLine))
solve xs = print $ snd $ head $ head $ groupBy (\ (a1,a2) (b1,b2) -> a1 == b1) $ sortBy (\ (a1,a2) (b1,b2) -> b1 `compare` a1) $ map (\a-> (length a, head a)) $ group $ map (\as-> snd $ head $  head $ groupBy (\ (a1,a2) (b1,b2) -> a1 == b1) $ sortBy (\ (a1,a2) (b1,b2) -> b1 `compare` a1) as) $ map (\as-> zipWith (\a b -> (b,a)) [1..] as) xs

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
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=   readsolveprint
readsolveprint::IO()
readsolveprint = C.getLine >>= \ns -> let [_,n]  = (map (fst.fromJust.C.readInteger).C.words) ns in (solve =<< forM [1..n] ( \i -> map (fst.fromJust.C.readInteger).C.words <$>C.getLine))
solve xs = print $ f $ map (\a-> (length a, head a)) $ group $ map (\as-> f as) $ map (\as-> zipWith (\a b -> (b,a)) [1..] as) xs
  where
  f ds = (snd . head .sortBy (\ (a1,a2) (b1,b2) -> a2 `compare` b2). head . groupBy (\ (a1,a2) (b1,b2) -> a1 == b1) . sortBy (\ (a1,a2) (b1,b2) -> b1 `compare` a1)) ds

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
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=   readsolveprint
readsolveprint::IO()
readsolveprint = C.getLine >>= \ns -> let [_,n]  = (map (fst.fromJust.C.readInteger).C.words) ns in (solve =<< forM [1..n] ( \i -> map (fst.fromJust.C.readInteger).C.words <$>C.getLine))
solve xs = print $ fst $ maximumBy (\(a,b) (a1,b1) -> (b `compare` b1) `compare` (a `compare` a1))$ map (\a->(head a, length a)) $ groupBy (==) $ sortBy (\ a b ->b `compare` a ) $ map (\hs -> last $ maximumBy (\(a:b:c:[]) (a1:b1:c1:[]) -> (a `compare` a1) `compare` (c `compare` c1)) hs) $ zipWith (\as bs-> zipWith (\a b -> b:as:a:[]) [1..] bs) [1..]  xs

import Control.Applicative
import Control.Monad
import Data.Array
-----

--be carefull with the type inference

-----

---------
-- get space separated something

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

---------

---------
-- output [a] in space separated form

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

---------

--------
-- read an integer N, get N lines, make a list consist of them

getListLn :: Read a => IO [a]
getListLn = do n <- readLn
               s <- replicateM n getLine
	       return (map read s)
--------

main = do [n, m] <- getListSp
          votes <- replicateM m getListSp
	  print $ solve votes

solve :: [[Int]] -> Int
solve = maxInd . cntList . (map maxInd)

maxInd :: [Int] -> Int
maxInd xs = lval $ head $ filter ((== maxVal) . lval) $ zip xs [1..]
             where maxVal = foldl1 max xs
	           lval (x, y) = x

cntList :: [Int] -> [Int]
cntList xs = elems $ accumArray (+) 0 (1, maxVal) (zip (repeat 1) xs)
              where maxVal = foldl1 max xs

import Control.Applicative
import Control.Monad
import Data.Array
-----

--be carefull with the type inference

-----

---------
-- get space separated something

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

---------

---------
-- output [a] in space separated form

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

---------

--------
-- read an integer N, get N lines, make a list consist of them

getListLn :: Read a => IO [a]
getListLn = do n <- readLn
               s <- replicateM n getLine
	       return (map read s)
--------

main = do [n, m] <- getListSp
          votes <- replicateM m getListSp
	  print $ solve votes

solve :: [[Int]] -> Int
solve = maxInd . cntList . (map maxInd)

maxInd :: [Int] -> Int
maxInd xs = lval $ head $ filter ((== maxVal) . lval) $ zip xs [1..]
             where maxVal = foldl1 max xs
	           lval (x, y) = x

cntList :: [Int] -> [Int]
cntList xs = elems $ accumArray (+) 0 (1, maxVal) (zip xs (repeat 1))
              where maxVal = foldl1 max xs

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

process x = (+1) $ fromJust $ findIndex (==m) x
  where m = maximum x

main::IO ()
main=do
   getLine
   x<-(+1) <$> process <$> map process <$> map (map (fromIntegral.fst.fromJust.C.readInteger))<$> map C.words <$> C.lines <$> C.getContents ::IO Int
   print x

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

process x =   fromJust $ findIndex (==m) x
  where m = maximum x

main::IO ()
main=do
   getLine
   x<-(+1) <$> process <$> map process <$> map (map (fromIntegral.fst.fromJust.C.readInteger))<$> map C.words <$> C.lines <$> C.getContents ::IO Int
   print x

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

process x = (+1) $ fromJust $ findIndex (==m) x
  where m = maximum x

main::IO ()
main=do
   getLine
   x<-process <$> map process <$> map (map (fromIntegral.fst.fromJust.C.readInteger))<$> map C.words <$> C.lines <$> C.getContents ::IO Int
   print x

import System.IO
import qualified Data.List as L

read_ints :: String -> [Int]
read_ints x = map read (words x) :: [Int]

best :: [[Int]] -> Int
best x = fst $ foldl (\(ans,co) gr -> if length gr > co then (head gr,length gr) else (ans,co) ) (0,0) x

compute :: [Int] -> Int
compute x = best ( L.group $ L.sort x )

solve :: [Int] -> Int
solve x = fst $ foldl (\(ans,co) (x,y) -> if x > co then (y,x) else (ans,co) ) (0,0) ( zip x [1..] )

main = do
	ln <- getLine
	let [n,m] = read_ints ln
	ln <- getContents
	let mat = map read_ints (lines ln)

	let winers = foldl (\ans ln -> solve ln : ans ) [] mat
	-- print winers
	let ans = max (compute winers) 1
	putStr $ show ans

import System.IO
import qualified Data.List as L

read_ints :: String -> [Int]
read_ints x = map read (words x) :: [Int]

best :: [[Int]] -> Int
best x = fst $ foldl (\(ans,co) gr -> if length gr > co then (head gr,length gr) else (ans,co) ) (0,0) x

compute :: [Int] -> Int
compute x = best ( L.group $ L.sort x )

solve :: [Int] -> Int
solve x = fst $ foldl (\(ans,co) (x,y) -> if x > co then (y,x) else (ans,co) ) (0,0) ( zip x [1..] )

main = do
	ln <- getLine
	let [n,m] = read_ints ln
	ln <- getContents
	let mat = map read_ints (lines ln)

	let winers = foldl (\ans ln -> solve ln : ans ) [] mat
	-- print winers
	let ans = compute winers
	putStr $ show ans

import Data.List

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

sol (n:m:xs) = snd . minimum . map (\x -> (- length x, head x)) . group . map det $ spl (map negate xs)
    where det ls = snd . minimum $ zip ls [1..]
          spl [] = []
          spl l = take n l : spl (drop n l)


import Data.Char
import Control.Monad

similar :: String -> String -> Bool
similar s1 s2
    | length s1 /= length s2 = False
    | otherwise = similarInner s1 s2

similarInner :: String -> String -> Bool
similarInner s1 s2 = all id $ zipWith similarChar s1 s2

similarChar :: Char -> Char -> Bool
similarChar c1 c2
    | c1 == c2 = True
    | otherwise = any id $ map (($c1) . ($c2)) [similarCase, similarO, similar1]

similarCase :: Char -> Char -> Bool
similarCase c1 c2 = isLower c1 /= isLower c2 && toLower c1 == toLower c2

similarO :: Char -> Char -> Bool
similarO 'O' '0' = True
similarO '0' 'O' = True
similarO 'o' '0' = True
similarO '0' 'o' = True
similarO _   _   = False

similar1 :: Char -> Char -> Bool
similar1 c1 c2 = c1 /= c2 && c1 `elem` ls && c2 `elem` ls
    where ls = "1lLiI"

main = do
    login <- getLine
    n <- readLn
    res <- liftM (any $ similar login) $ replicateM n getLine
    putStrLn $ case res of
                   True -> "No"
                   False -> "Yes"

{-# LANGUAGE ScopedTypeVariables #-}

module Main where

import           Control.Applicative
import           Control.Monad.Cont
import           Data.Char

chZero :: Char -> Char
chZero '0' = 'O'
chZero a   = a

chI :: Char -> Char
chI '1' = 'l'
chI 'I' = 'l'
chI 'i' = 'l'
chI a   = a

minimize :: String -> String
minimize = map (toLower . chI . chZero)

main :: IO ()
main = do
  login <- minimize <$> getLine
  n :: Int <- read <$> getLine
  flip runContT putStrLn $ callCC $ \notOk -> do
    forM_ [1..n] $ \_ -> do
      l2 <- minimize <$> liftIO getLine
      if l2 == login then notOk "No" else return ()
    return "Yes"

import Data.List
import Data.Char

main :: IO ()
main = do
  s <- getLine
  ns <- getLine
  let n = read ns :: Integer
  strings <- mapM (\_ -> getLine) [1..n]
  let solution = solveProblem s strings
  putStrLn solution

solveProblem :: String -> [String] -> String
solveProblem    s         strings   = let s' = fmap (repl . toLower) s
                                          strings' = fmap (fmap (repl . toLower)) strings
                                      in case (length (nub (s':strings')) == length (s':strings')) of
                                           True -> "Yes"
                                           False -> "No"

repl :: Char -> Char
repl 'o' = '0'
repl '1' = 'i'
repl 'l' = 'i'
repl c = c

{-# LANGUAGE ScopedTypeVariables #-}

module Main where

import           Control.Applicative
import           Control.Monad.Cont
import           Data.Char

chZero :: Char -> Char
chZero '0' = 'O'
chZero a   = a

chI :: Char -> Char
chI '1' = 'l'
chI 'I' = 'l'
chI 'i' = 'l'
chI a   = a

minimize :: String -> String
minimize = map (toLower . chI . chZero)

main :: IO ()
main = do
  login <- minimize <$> getLine
  print login
  n :: Int <- read <$> getLine
  flip runContT putStrLn $ callCC $ \notOk -> do
    forM_ [1..n] $ \_ -> do
      l2 <- minimize <$> liftIO getLine
      liftIO $ print login
      if l2 == login then notOk "No" else return ()
    return "Yes"

import Data.List
import Data.Char

main :: IO ()
main = do
  s <- getLine
  ns <- getLine
  let n = read ns :: Integer
  strings <- mapM (\_ -> getLine) [1..n]
  let solution = solveProblem s strings
  putStrLn (show solution)

solveProblem :: String -> [String] -> String
solveProblem    s         strings   = let s' = fmap (repl . toLower) s
                                          strings' = fmap (fmap (repl . toLower)) strings
                                      in case (length (nub (s':strings')) == length (s':strings')) of
                                           True -> "YES"
                                           False -> "NO"

repl :: Char -> Char
repl 'o' = '0'
repl '1' = 'i'
repl 'l' = 'i'
repl c = c