{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}

import safe Control.Arrow ((>>>))
import qualified Data.Text as T
import qualified Data.Text.IO as TI
import Data.List
import Data.Function
import Data.Maybe

main :: IO ()
main = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where
  tcio :: [T.Text] -> [String]
  tcio [] = []
  tcio (nm : rest) = ((:[]).istoline . solve . linestoiss) (nm:( take 1 rest)) ++ tcio (drop 1 rest)
  linetoi t = f 0 t where f n t = if (T.null) t then n else f (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;
  linetois = (map linetoi).(T.words); linestoiss = map linetois
  itoline = show; istoline = unwords . (map itoline); isstolines = map istoline

solve :: [[Integer]] -> [Integer]
solve [[n,x],as] = [(sum as + x - 1) `div` x, sum $ map (`div` x) $ map (+ (x-1)) as]

import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.List
import Data.Maybe
import Control.Monad (replicateM)
import Data.Int

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

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

do_test :: IO ()
do_test = do

  [n, x] <- readIntegers
  ns <- readIntegers
  let
    mini = div ((sum ns) + x - 1) x
    maxi = sum $ map ((`div` x) . (+(x-1))) ns
  putStrLn $ (show mini) ++ " " ++ (show maxi)

main :: IO [()]
main = do
  t <- readInt
  replicateM t do_test

import Control.Monad (replicateM)
import Data.Int

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

do_test :: IO ()
do_test = do

  [n, x] <- readInts
  ns <- readInts
  let
    mini = div ((sum ns) + x - 1) x
    maxi = sum $ map ((`div` x) . (+(x-1))) ns
  putStrLn $ (show mini) ++ " " ++ (show maxi)

main :: IO [()]
main = do
  t <- readLn :: IO Int
  replicateM t do_test

import Control.Arrow
import Control.Monad
import Data.Char
import Data.List (foldl)
import Data.Set (Set, fromList, member, insert)
import System.IO
import Text.Read
-- import Debug.Trace

handleCase :: Integer -> IO ()
handleCase c = do
  -- print c
  [n, x] <- fmap (map read . words) getLine :: IO [Integer]
  a <- fmap (map read . words) getLine :: IO [Integer]
  putStrLn  $ (\ (a, b) -> unwords [show a, show b]) $ solve n x a
  return ()

main :: IO ()
main = do
  t <- readLn :: IO Integer
  forM_ [1 .. t] handleCase

-- type State = (Set Integer, Integer, Integer)
--
-- c :: Integer -> State -> Integer -> State
-- c x (m, cnt, total) i
--   | i == 0 = ( m, cnt, total)
--   | newCnt `member` m = (fromList [0], 0, total + 1)
--   | otherwise = (insert newCnt m, newCnt, total)
--   where
--     newCnt = (cnt + i) `mod` x

solve :: Integer -> Integer -> [Integer] -> (Integer, Integer)
solve n x a =
  let roundUp i = (i + x - 1) `quot` x
      mx = sum $ map roundUp a
      mn = roundUp $ sum a
   in (mn, mx)

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

solve = do
	[ _, x ] <- readIntegers
	as <- readIntegers
	let
		mi = rdiv ( sum as ) x
		ma = sum $ map ( flip rdiv x ) as
	printf "%lld %lld\n" mi ma

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

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

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

readInts :: IO [Integer]
readInts = readArray

solve :: Integer -> [Integer] -> (Integer, Integer)
solve x a = (roundUp $ sum a, sum $ map roundUp a)
  where roundUp y = (y + x - 1) `div` x

solveCase :: IO String
solveCase = do
  (n:x:[]) <- readInts
  (a, b) <- fmap (solve x) readInts
  pure $ printf "%d %d" a b

main :: IO ()
main = readLn >>= flip replicateM_ (solveCase >>= putStrLn)

import Control.Monad
import Data.Int

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

runSeveral :: IO () -> IO ()
runSeveral act = do
  t <- read <$> getLine
  replicateM_ t act

ceilDiv :: Integral t => t -> t -> t
ceilDiv x y = div (x + y - 1) y

main :: IO ()
main = runSeveral $ do
  [_n, x] <- readInts
  -- reading so many Int64s with [Char]s may be too slow
  -- but the ByteString version of this is so much uglier
  a <- readInts
  let
    le = ceilDiv (sum a) x
    ri = sum [ceilDiv ai x | ai <- a]
  putStrLn . unwords $ map show [le, ri]

{-# LANGUAGE DeriveFunctor       #-}
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Arrow              ((>>>))
import           Control.Monad              (MonadPlus (mplus), foldM_, forM_,
                                             join, replicateM_)
import qualified Control.Monad.ST.Strict    as ST
import qualified Control.Monad.State.Strict as S
import qualified Data.Array                 as A
import qualified Data.Array.MArray.Safe     as MA
import qualified Data.Array.ST.Safe         as STA
import           Data.Bits
import qualified Data.ByteString.Char8      as B8
import           Data.Char
import           Data.Functor               ((<&>))
import           Data.IORef                 (modifyIORef, newIORef, readIORef)
import           Data.Int
import qualified Data.IntMap                as IM
import           Data.List                  (elemIndices, find, findIndices,
                                             intersect, isPrefixOf, nub, sort,
                                             sortOn)
import qualified Data.Map                   as M
import           Data.Maybe                 (fromJust, fromMaybe, isJust)
import qualified Data.Set                   as S
import           Data.Traversable           (forM)
import           GHC.IO.Handle              (hDuplicateTo)
import           System.IO                  (IOMode (ReadMode, WriteMode),
                                             openFile, stdin, stdout)
import           Text.Printf                (printf)

-- import Debug.Trace (trace)
-- debug = flip trace

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

readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)

solve :: Int -> Int64 -> [Int64] -> (Int64, Int64)
solve n x as = (minAnswer, maxAnswer)
    where
        minAnswer = (sum as + x - 1) `div` x
        maxAnswer = sum [(a + x - 1) `div` x | a <- as]

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [n, x] <- B8.getLine <&> map readIntB8 . B8.words
        as <- B8.getLine <&> map (\e -> (fromInteger (readIntegerB8 e)) :: Int64) . B8.words
        let (minAnswer, maxAnswer) = solve n ((fromIntegral x) :: Int64) as
        printf "%lld %lld\n" minAnswer maxAnswer

import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.List
import Data.Maybe
import Control.Monad (replicateM)
import Data.Int

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

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

do_test :: IO ()
do_test = do

  [n, x] <- readInts
  ns <- readInts
  let
    mini = div ((sum ns) + x - 1) x
    maxi = sum $ map ((`div` x) . (+(x-1))) ns
  putStrLn $ (show mini) ++ " " ++ (show maxi)

main :: IO [()]
main = do
  t <- readLn :: IO Int
  replicateM t do_test

import Control.Monad (replicateM)

solve_min :: [Int] -> Int -> Int
solve_min ns x = ceiling ((fromIntegral (sum ns)) / (fromIntegral x))

solve_max :: [Int] -> Int -> Int
solve_max ns x = sum (map (ceiling . (/ (fromIntegral x)) . fromIntegral) ns)

solve :: [Int] -> Int -> (Int, Int)
solve ns x = (solve_min ns x, solve_max ns x)

do_test :: IO ()
do_test = do
  line <- getLine
  let [n, x] = (map read . words) line :: [Int] in
    do
    ns <- map read . words <$> getLine :: IO [Int]
    let (mini, maxi) = solve ns x in
      do
        putStrLn $ (show mini) ++ " " ++ (show maxi)

main :: IO [()]
main = do
  t <- readLn :: IO Int
  replicateM t do_test

import Control.Monad (replicateM)

solve_min :: [Int] -> Int -> Int
solve_min ns x = ceiling ((fromIntegral (sum ns)) / (fromIntegral x))

solve_max :: [Int] -> Int -> Int
solve_max ns x = sum (map (ceiling . (/ (fromIntegral x)) . fromIntegral) ns)

solve :: [Int] -> Int -> (Int, Int)
solve ns x = (solve_min ns x, solve_max ns x)

do_test :: IO ()
do_test = do
  line <- getLine
  let [n, x] = (map read . words) line :: [Int] in
    do
    ns <- map read . words <$> getLine :: IO [Int]
    let (mini, maxi) = solve ns x in
      do
        putStrLn $ (show mini) ++ " " ++ (show maxi)

main :: IO [()]
main = do
  t <- readLn :: IO Int
  print t
  replicateM t do_test

import Control.Arrow
import Control.Monad
import Data.Char
import Data.List (foldl)
import Data.Set (Set, fromList, member, insert)
import System.IO
import Text.Read
-- import Debug.Trace

handleCase :: Int -> IO ()
handleCase c = do
  -- print c
  [n, x] <- fmap (map read . words) getLine :: IO [Int]
  a <- fmap (map read . words) getLine :: IO [Int]
  putStrLn  $ (\ (a, b) -> unwords [show a, show b]) $ solve n x a
  return ()

main :: IO ()
main = do
  t <- readLn :: IO Int
  forM_ [1 .. t] handleCase

-- type State = (Set Int, Int, Int)
--
-- c :: Int -> State -> Int -> State
-- c x (m, cnt, total) i
--   | i == 0 = ( m, cnt, total)
--   | newCnt `member` m = (fromList [0], 0, total + 1)
--   | otherwise = (insert newCnt m, newCnt, total)
--   where
--     newCnt = (cnt + i) `mod` x

solve :: Int -> Int -> [Int] -> (Int, Int)
solve n x a =
  let roundUp i = (i + x - 1) `quot` x
      mx = sum $ map roundUp a
      mn = roundUp $ sum a
   in (mn, mx)

import Control.Arrow
import Control.Monad
import Data.Char
import Data.List (foldl)
import Data.Set (Set, fromList, member, insert)
import System.IO
import Text.Read
-- import Debug.Trace

handleCase :: Int -> IO ()
handleCase c = do
  -- print c
  [n, x] <- fmap (map read . words) getLine :: IO [Int]
  a <- fmap (map read . words) getLine :: IO [Int]
  putStrLn  $ (\ (a, b) -> unwords [show a, show b]) $ solve n x a
  return ()

main :: IO ()
main = do
  t <- readLn :: IO Int
  forM_ [1 .. t] handleCase

type State = (Set Int, Int, Int)

c :: Int -> State -> Int -> State
c x (m, cnt, total) i
  | i == 0 = ( m, cnt, total)
  | newCnt `member` m = (fromList [0], 0, total + 1)
  | otherwise = (insert newCnt m, newCnt, total)
  where
    newCnt = (cnt + i) `mod` x

solve :: Int -> Int -> [Int] -> (Int, Int)
solve n x a =
  let base = sum $ map (`quot` x) a
      mods = map (`mod` x) a
      (_, _, total) = foldl (c x) (fromList [0], 0, 0) mods
   in (base, base + total)


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

main = do
	n<-read <$> getLine ::IO Int
	let a =  take 1 $ [[n,y,denominator z] |y<-[n+1..(n+n)],let z=(1%n)- ( 1%y), numerator z==1,denominator z /=y]
	if length a ==1 then putStrLn (intercalate " " ( map show (head a))) else print (-1)

{-# LANGUAGE TypeApplications #-}

main :: IO ()
main = do
  n <- read @ Int <$> getLine
  if n == 1
     then putStrLn "-1"
     else putStrLn . unwords . fmap show $ [n, n + 1, n * (n + 1)]

module Main where
  import Data.List
  import Control.Monad
  import Data.Array
  import qualified Data.Set as S

  toArray :: [a] -> Array Int a
  toArray xs =
    let ls = length xs - 1
        in array (0, ls) $ zip [0..ls] xs

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

  readMultilineInput :: Int -> (String -> IO a) -> IO [a]
  readMultilineInput n transformer = replicateM n (getLine >>= transformer)

  elemSet :: (Ord a) => a -> S.Set a -> Bool
  elemSet elem sets =
    let found = elem `S.lookupIndex` sets
        in toBool found
        where
          toBool :: Maybe Int -> Bool
          toBool (Just _) = True
          toBool Nothing = False

  main :: IO()
  main = do
    n <- getLine >>= return . readInt
    let m = n * (n + 1)
    case n of
      1 -> putStrLn "-1"
      _ -> putStrLn $ (show m)  ++ " " ++ (show n) ++ " " ++ (show (n + 1))

module Main where

import Control.Applicative
import Control.Monad
import Prelude
import Text.Printf

main = do
    n <- read <$> getLine :: IO Int
    if n == 1 then print $ -1
    else printf "%d %d %d\n" n (n + 1) (n*(n+1))

{-# LANGUAGE TypeApplications #-}

main :: IO ()
main = do
  n <- read @ Int <$> getLine
  putStrLn . unwords . fmap show $ [n, n + 1, n * (n + 1)]

module Main where
  import Data.List
  import Control.Monad
  import Data.Array
  import qualified Data.Set as S

  toArray :: [a] -> Array Int a
  toArray xs =
    let ls = length xs - 1
        in array (0, ls) $ zip [0..ls] xs

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

  readMultilineInput :: Int -> (String -> IO a) -> IO [a]
  readMultilineInput n transformer = replicateM n (getLine >>= transformer)

  elemSet :: (Ord a) => a -> S.Set a -> Bool
  elemSet elem sets =
    let found = elem `S.lookupIndex` sets
        in toBool found
        where
          toBool :: Maybe Int -> Bool
          toBool (Just _) = True
          toBool Nothing = False

  main :: IO()
  main = do
    n <- getLine >>= return . readInt
    putStrLn $ "1 " ++ (show n) ++ " " ++ (show (n + 1))

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

main = do
	n<-read <$> getLine ::IO Int
	let a =  take 1 $ [[n,y,denominator z] |y<-[n+1..(n+n)],let z=(1%n)- ( 1%y), numerator z==1]
	if length a ==1 then putStrLn (intercalate " " ( map show (head a))) else print (-1)

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

main = do
	n<-read <$> getLine ::IO Int
	print $ head $ [[x,y,denominator z] |x<-[2..10^9],y<-[x+1..10^9],let z=(2%n)- ((1%x) +( 1%y)), numerator z==1]


import Control.Arrow

main = interact $
         words >>> drop 1
         >>> map (
               read
               >>> solve
               >>> maybe "-1\n" (unlines . map (unwords . map show)))
         >>> concat

solve :: Int -> Maybe [[Int]]
solve 1 = Just [[1]]
solve 2 = Nothing
solve n = Just [[val $ i*n + j | j <- [0..n-1]] | i <- [0..n-1]]
    where
        val x = 1 + (if even x then (n^2 `div` 2) else 0) + x `div` 2

import Control.Monad

main = do
    t <- read <$> getLine
    replicateM_ t $
        getLine >>= putStr . unlines . map (unwords . map show) . solve . read

solve :: Int -> [[Int]]
solve 2 = [[-1]]
solve n = chunks n $ [2,4 .. n * n] ++ [1,3 .. n * n]

chunks :: Int -> [Int] -> [[Int]]
chunks _ [] = []
chunks n l =
    let (xs, ys) = splitAt n l
     in xs : chunks n ys

{-# LANGUAGE ParallelListComp #-}
import Control.Arrow
import Data.List

main = interact $
         words >>> drop 1
         >>> map (
               read
               >>> solve
               >>> maybe "-1\n" (unlines . map (unwords . map show)))
         >>> concat

solve :: Int -> Maybe [[Int]]
solve 1 = Just [[1]]
solve 2 = Nothing
solve 3 = Just [[1,6,2], [7,3,8], [4,9,5]]
solve n = let (Just grid) = solve (n - 1) in
            Just $ [(n - 1) * n + 1 .. n^2] : [((n - 1)^2 + x) : row | row <- grid | x <- [1..n-1]]


import Data.List

parseInt :: String -> Int
parseInt number = (read number) :: Int

readInt :: IO Int
readInt = do
    number <- getLine
    pure $ parseInt number

readIntArr :: IO [Int]
readIntArr = do
    numbers <- getLine
    pure $ map parseInt $ words numbers

calc :: (Int, Int, [Int]) -> Int
calc (_, _, []) = 0
calc (i, n, (0 : xs)) = (i + 1) * (n - i) + calc (i + 1, n, xs)
calc (i, n, (_ : xs)) = calc (i + 1, n, xs)

solve :: IO ()
solve = do
    n   <- readInt
    arr <- readIntArr
    print $ (n * (n + 1) * (n + 2)) `div` 6 + (calc (0, n, arr))

readLoop :: Int -> IO ()
readLoop i =
    if (i == 0)
        then pure ()
        else do
            solve
            readLoop (i - 1)

main :: IO ()
main = do
    n <- readInt
    readLoop n

main = interact $ unlines . map p . chunk 2 . drop 1 . lines

chunk n [] = []
chunk n xs = take n xs : chunk n (drop n xs)

f n t x = let i1 = fst t
              i2 = n - i1 + 1
              s = snd t
          in case x of 0 -> (i1 + 1, s + i1 * i2 * 2)
                       _ -> (i1 + 1, s + i1 * i2)

calc n = foldl (f n) (1,0)

p xs = let ((n:_):s:_) = fmap (fmap read . words) xs :: [[Int]]
        in show $ snd $ calc n s

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

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

mainFun :: SP Builder
mainFun = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    n <- getInt
    a <- replicateM n getInt
    let
      ans = foldl' (+) 0 $ do
        suff <- tails a
        seg <- inits suff
        v <- seg
        pure $ if  v == 0  then  2  else  1
    pure $ putInts [ans]

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


main = do
  interact (unlines .run. map f . lines)

f :: String -> [Int]
f inp = (map g (words inp)) where g x = read x :: Int

run :: [[Int]]->[[Char]]
run (x:y:z:xs)= ((solve (head y) z): (run ([(head x) - 1]: xs)))
run [[0]] = []

solve :: Int -> [Int] -> [Char]
solve y z |z == [1..y] = "0"
  |head z == 1 = "1"
  |last z == y = "1"
  |((head z == y) && (last z == 1)) = "3"
  | otherwise = "2"

import qualified Data.ByteString.Lazy.Char8 as BS
import Control.Monad
import Data.List
import Data.Maybe
import System.IO
import System.IO.Unsafe

deb s e = unsafePerformIO $ do
    hPutStrLn stderr s
    return e

parseInt = fst . fromJust . BS.readInt
parseInteger = fst . fromJust . BS.readInteger

solve :: [Int] -> Int
solve xs
    | Data.List.sort xs == xs =
        0
    | minimum xs == head xs || maximum xs == last xs =
        1
    | minimum xs == last xs && maximum xs == head xs =
        3
    | otherwise =
        2

main = do
    ls <- tail . BS.lines <$> BS.getContents
    let ls' = snd <$> filter (odd . fst) (zip [0..] ls)
    forM_ ls' (print . solve . map parseInt . BS.words)

module Main where
import Data.Functor ((<&>))
import Control.Monad (forM, replicateM, replicateM_)
import Data.Foldable (traverse_)
import GHC.Float.RealFracMethods (ceilingDoubleInt, floorDoubleInt)
import Data.List (group, sort)
import Data.Ratio ((%))
import Prelude hiding (floor)
import Control.Monad (forM_)

readInts :: IO [Int]
readInts = getLine <&> words <&> fmap read

readString :: IO String
readString = getLine

toDoubles :: (Functor f, Integral a) => f a -> f Double
toDoubles xs = (\x -> fromIntegral x :: Double) <$> xs

toDouble :: (Integral a) => a -> Double
toDouble = fromIntegral

ceil :: Double -> Int
ceil = ceilingDoubleInt

floor :: Double -> Int
floor = floorDoubleInt

main :: IO ()
main = do
  t:_ <- readInts
  replicateM_ t $ do
    n:_ <- readInts
    as <- readInts
    let
      maxi = maximum as
      mini = minimum as
      ans xs
        | sort xs == xs = 0
        | maxi == last xs || mini == head xs = 1
        | mini == last xs && maxi == head xs = 3
        | otherwise = 2
    print $ ans as

import Control.Monad

main = do
    t <- read <$> getLine
    replicateM_ t $ do
        n <- read <$> getLine :: IO Int
        a <- map read . words <$> getLine :: IO [Int]
        print $
            if a == [1 .. n]
                then 0
                else if head a == 1 || last a == n
                         then 1
                         else if head a /= n || last a /= 1
                                  then 2
                                  else 3

module Main where
import Data.Functor ((<&>))
import Control.Monad (forM, replicateM, replicateM_)
import Data.Foldable (traverse_)
import GHC.Float.RealFracMethods (ceilingDoubleInt, floorDoubleInt)
import Data.List (group, sort)
import Data.Ratio ((%))
import Prelude hiding (floor)
import Control.Monad (forM_)

readInts :: IO [Int]
readInts = getLine <&> words <&> fmap read

readString :: IO String
readString = getLine

toDoubles :: (Functor f, Integral a) => f a -> f Double
toDoubles xs = (\x -> fromIntegral x :: Double) <$> xs

toDouble :: (Integral a) => a -> Double
toDouble = fromIntegral

ceil :: Double -> Int
ceil = ceilingDoubleInt

floor :: Double -> Int
floor = floorDoubleInt

main :: IO ()
main = do
  t:_ <- readInts
  replicateM_ t $ do
    n:_ <- readInts
    as <- readInts
    let
      maxi = maximum as
      mini = minimum as
      unsorted xs
          | sort xs == xs = 0
          | otherwise = 1
      ans xs
        | sort xs == xs = 0
        | maxi == last xs || mini == head xs = 1
        | mini == last xs || maxi == head xs = 3
        | otherwise = 2
    print $ ans as

import qualified Data.ByteString.Lazy.Char8 as BS
import Control.Monad
import Data.List
import Data.Maybe
import System.IO
import System.IO.Unsafe

deb s e = unsafePerformIO $ do
    hPutStrLn stderr s
    return e

parseInt = fst . fromJust . BS.readInt
parseInteger = fst . fromJust . BS.readInteger

solve :: [Int] -> Int
solve xs
    | Data.List.sort xs == xs =
        0
    | minimum xs == head xs || maximum xs == last xs =
        1
    | minimum xs == last xs || maximum xs == head xs =
        3
    | otherwise =
        2

main = do
    ls <- tail . BS.lines <$> BS.getContents
    let ls' = snd <$> filter (odd . fst) (zip [0..] ls)
    forM_ ls' (print . solve . map parseInt . BS.words)


{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

maxRect p1 p2 l = abs (a1 - a2)
    where
    l'  = map f $ filter ((/=p1) <&&> (/=p2)) $ l
    f p = signedArea3 p1 p2 p
    a1  = maximum l'
    a2  = minimum l'

signedArea l = (sum $ zipWith (\(a,b) (c,d) -> a*d - b*c) l (tail (cycle l)))

signedArea3 (x1,y1) (x2,y2) (x3,y3) = a*d - b*c
    where
    (a,b) = (x2-x1,y2-y1)
    (c,d) = (x3-x1,y3-y1)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

--maxRect p1 p2 = abs . uncurry (-)  maxMin . map (signedArea3 p1 p2) . filter ((/=p1) <&&> (/=p2))

maxRect p1 p2 l = go minBound maxBound  l
    where
    go !a !b [] = a - b
    go !a !b (p:ps)
        | p == p1 || p == p2 = go a b ps
        | otherwise =
            let x = signedArea3 p1 p2 p in
                go (max a x) (min b x) ps

signedArea3 (x1,y1) (x2,y2) (x3,y3) =
    (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)

--maxMin = foldl' (\(a,b) x -> (max a x,min b x)) (minBound,maxBound)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

maxRect p1 p2 l = go minBound maxBound  l
    where
    go !a !b (p:ps)
        | p == p1 || p == p2 = go a b ps
        | otherwise =
            let x = signedArea3 p1 p2 p in
                go (max a x) (min b x) ps
    go !a !b [] = a - b

signedArea3 (x1,y1) (x2,y2) (x3,y3) =
    (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

maxRect p1 p2 l = abs (a1 - a2)
    where
    l'  = map (signedArea3 p1 p2) $ filter ((/=p1) <&&> (/=p2)) $ l
    a1  = maximum l'
    a2  = minimum l'

signedArea3 (x1,y1) (x2,y2) (x3,y3) = (x2-x1)*(y3-y1) - (y2-y1)*(x3-x1)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

maxRect p1 p2 l = go minBound maxBound  l
    where
    go a b [] = a - b
    go a b (p:ps)
        | p == p1 || p == p2 = go a b ps
        | otherwise =
            let x = signedArea3 p1 p2 p in
                go (max a x) (min b x) ps

signedArea3 (x1,y1) (x2,y2) (x3,y3) =
    (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

maxRect p1 p2 l = go minBound maxBound  l
    where
    go !a !b (p:ps)
        | p == p1 || p == p2 = go a b ps
        | otherwise =
            let x = signedArea3 p1 p2 p in
                go (max a x) (min b x) ps
    go !a !b [] = a - b

{-# INLINE signedArea3 #-}
signedArea3 (x1,y1) (x2,y2) (x3,y3) =
    (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

maxRect p1 p2 l = abs (a1 - a2)
    where
    l'  = map f l
    f p = signedArea3 p1 p2 p
    a1  = maximum l'
    a2  = minimum l'

signedArea l = (sum $ zipWith (\(a,b) (c,d) -> a*d - b*c) l (tail (cycle l)))

signedArea3 (x1,y1) (x2,y2) (x3,y3) = a*d - b*c
    where
    (a,b) = (x2-x1,y2-y1)
    (c,d) = (x3-x1,y3-y1)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

type Point = (Double,Double)

main = do
    n <- readLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- readsLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = maximum [ maxRect p1 p2 l | p1 <- l, p2 <- l, p1 /= p2 ]

maxRect p1@(x1,y1) p2@(x2,y2) l = a1 - a2
    where
    l'  = map f l
    f p = signedArea [p1,p2,p]
    a1  = maximum l'
    a2  = minimum l'

signedArea l = 0.5 * (sum $ zipWith (\(a,b) (c,d) -> a*d - b*c) l (tail l))

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

--maxRect p1 p2 = abs . uncurry (-)  maxMin . map (signedArea3 p1 p2) . filter ((/=p1) <&&> (/=p2))

maxRect p1 p2 l = go minBound maxBound  l
    where
    go !a !b [] = a - b
    go !a !b (p:ps)
        | p == p1 || p == p2 = go a b ps
        | otherwise =
            let x = signedArea3 p1 p2 p in
                go (max a x) (min a x) ps

signedArea3 (x1,y1) (x2,y2) (x3,y3) =
    (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)

--maxMin = foldl' (\(a,b) x -> (max a x,min b x)) (minBound,maxBound)


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

data TC = TC { n :: Int, m :: Int }

type Output = (Int, Int)

input :: Scanner TC
input = do
  n <- int
  m <- int
  return TC {..}

solve :: TC -> Output
solve TC {..}
  | n >= 2 && m >= 2 = (2, 2)
  | otherwise = (1, 1)

output :: Int -> Output -> C.ByteString
output _ (x, y) = C.pack $ show x <> " " <> show y

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

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

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

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

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

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

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

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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

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

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

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

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

(><) = times

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

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

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

{-# LANGUAGE ScopedTypeVariables #-}

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

mainFun :: SP Builder
mainFun = do
  casnum <- getInt
  ress <- forM [1 .. casnum] $ \_ -> do
    n <- getInt
    m <- getInt
    let res
          | n == 1 || m == 1 = [1, 1] -- isolate on [1,1]
          | n >= 4 || m >= 4 = [1, 1] -- no isolate
          | otherwise = [2, 2]
    pure res
  pure $ foldl1 (<>) $ map putInts ress

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

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

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,m] <- ri
        return (n,m)
    mapM_ (putStrLn.showT.solve) tcs

showT (a,b) = show a ++ " " ++ show b

solve (n,m) = f (n,m) :: (Int,Int)
  where
    f | n <= m     =        solveN
      | otherwise  = swap . solveN . swap

solveN (n,m) | n >  m            = error "Wrong usage"
             | n >= 2 && m >= 4  = (2,2)
             | n == 1            = (1,1)
             | n == 2            = (2,2)
             | n == 3            = (2,2)
             | otherwise         = error "Logic error (impossible)"

{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections  #-}
{-# LANGUAGE Strict #-}
{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}
#ifndef DEBUG
{-# LANGUAGE Safe #-}
#endif

import qualified Data.ByteString.Char8 as B8
import qualified Data.String as S

import Control.Arrow ((>>>))
import Data.Functor ((<&>))
import Data.Maybe
import qualified Data.Traversable as T

import qualified Control.Applicative as A
import qualified Control.Monad as M
import qualified Control.Monad.State as MS
import qualified Control.Monad.Trans as MT
import qualified Control.Monad.Trans.Maybe as M

import qualified Data.List as L
import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import qualified Data.IntSet as IS
import qualified Data.IntMap as IM
import qualified Data.Set as S
import Data.List (sortBy, sortOn)

import Data.Char
import Data.Int

import System.IO (stdin, stdout, hFlush)
import Text.Printf

#ifdef DEBUG
import Debug.Trace (trace, traceM, traceShowM)
debug = flip trace

tracing t x = trace (t ++ " = " ++ show x) x
debugging x t = tracing t x

tracingM t x = traceM $ t ++ " = " ++ show x

#else

debug x _ = x
trace _ x = x
tracing _ x = x
debugging x _ = x

traceM _ = pure ()
tracingM _ _ = pure ()
#endif

{- reading -}
readIntB8 :: B8.ByteString -> Int
readIntB8 = B8.readInt >>> (fst . fromJust)

readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))

readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)

readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

solve 1 m = [1, m]
solve n 1 = [n, 1]
solve n m = [2, 2]

main :: IO()
main = do
	t <- B8.getLine <&> readIntB8
	M.replicateM_ t $ do
		[n, m] <- B8.getLine <&> readIntB8s
		let answer = solve n m
		M.forM_ answer $ \x -> printf "%d " x
		putStrLn ""

import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase = map read . words <$> getLine >>=
        \[n, m] -> case isolated n m of
                     Just (x, y) -> putStrLn (show x ++ " " ++ show y)
                     Nothing -> putStrLn "1 1"
isolated :: Int -> Int -> Maybe (Int, Int)
isolated n m = if (div n 2) >= 2 && (div m 2) >= 2
               then Nothing
               else Just (mod n 2 + div n 2, mod m 2 + div m 2)

import Control.Monad

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

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

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let [n,m] = map read . words $ input ::[Int]
        putStrLn.toShow$ solve n m
    return ()

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UnboxedTuples #-}

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Control.Monad.Trans.State
import Data.Array.ST.Safe
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 Data.Semigroup
import GHC.Exts
import System.IO

mainFun :: SP Builder
mainFun = do
  casnum <- getInt
  ress <- forM [1 .. casnum] $ \_ -> do
    n <- getInt
    m <- getInt
    let res
          | n == 2 && (m == 2 || m == 3) = [1, 2]
          | n == 3 && m == 2 = [2, 1]
          | otherwise = [1, 1]
    pure res
  pure $ foldl1 (<>) $ map putInts ress
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

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

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,m] <- ri
        return (n,m)
    mapM_ (putStrLn.showT.solve) tcs

showT (a,b) = show a ++ " " ++ show b

solve (n,m) = f (n,m) :: (Int,Int)
  where
    f | n <= m     =        solveN
      | otherwise  = swap . solveN . swap

solveN (n,m) | n >= 2 && m >= 4  = (2,4)  -- any
             | n == 1            = (1,1)
             | n == 2            = (1,1)
             | n == 3            = (2,2)
             | otherwise         = error "Logic error (impossible)"


{-# LANGUAGE FlexibleContexts #-}
import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.IO
import Data.Array.Unboxed
import Data.Bits
import Data.Bool
import Data.Char
import Data.Int
import Data.List
import Data.Maybe
import Data.Ord
import Data.Ratio
import qualified Data.Set as Set
import qualified Data.Sequence as Seq
import System.IO
import System.IO.Unsafe

(><) a b = a Seq.>< b

deb s e = unsafePerformIO $ do
    hPutStrLn stderr s
    return e

parseInt = fst . fromJust . BS.readInt
parseInteger = fst . fromJust . BS.readInteger

main = do
    tn <- parseInt <$> BS.getLine
    replicateM_ tn $ do
        n <- parseInt <$> BS.getLine
        xs <- sort . map parseInt . BS.words <$> BS.getLine
        let
            (_,i) = minimum (map (\(x,y,i) -> (y-x,i)) $ zip3 xs (drop 1 xs) [0..])
            (a,x0:x1:b) = splitAt i xs
            r = x0:b ++ a ++ [x1]
        putStrLn . unwords $ map show r

import Control.Monad
import Data.List
readInts = fmap (map read.words) getLine :: IO [Int]
printArr = putStrLn . unwords . map show

printResult = do
    n <- readLn :: IO Int
    h <- readInts
    let sh = sort h
    if n <= 2 then printArr sh
    else
        let zh = zip (zipWith (-) (tail sh) sh) [0..]
            (_,i) = minimum zh
            (f,l) = splitAt (i+1) sh
        in printArr $ l ++ f

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

import Control.Monad
import Data.List
readInts = fmap (map read.words) getLine :: IO [Int]

toStr [] = ""
toStr (x:xs) = show x ++ " " ++ toStr xs

printResult = do
    n <- readLn :: IO Int
    h <- readInts
    let sh = sort h
    if n <= 2 then putStrLn $ toStr sh
    else
        let zh = zip (zipWith (-) (tail sh) sh) [0..]
            (_,i) = minimum zh
            (f,l) = splitAt (i+1) sh
        in putStrLn $ toStr $ l ++ f

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

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

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

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

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    as <- sort <$> getInts
    let diff = minimum $ zipWith (flip (-)) as $ tail as
        func (x1 : x2 : xs)
          | x2 - x1 == diff = x2 : xs
          | otherwise = func (x2 : xs)
        results
          | n == 2 = as
          | otherwise = take n $ func $ as ++ as
    return $ mconcat (map (\x -> intDec x `mappend` charUtf8 ' ') results) `mappend` charUtf8 '\n'
  hPutBuilder stdout output

import Control.Monad
import Data.List
readInts = fmap (map read.words) getLine :: IO [Int]

toStr [] = ""
toStr (x:xs) = show x ++ " " ++ toStr xs

printResult = do
    n <- readLn :: IO Int
    h <- readInts
    let sh = sort h
        zh = zip (zipWith (-) (tail sh) sh) [0..]
        (_,i) = if n > 1 then minimum zh else (0,0)
        (a,b) = splitAt (i+1) sh
    putStrLn $ toStr $ b ++ a

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


{-# LANGUAGE BangPatterns #-}

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

readInteger s = let Just (n,_) = B.readInteger s in n

main = do
  [_,d] <- map read.words <$> getLine
  [a,b] <- map read.words <$> getLine
  let toCosts [] = []
      toCosts (x:y:xys) = (a*x+b*y):toCosts xys
  costs <- zip[1..].toCosts.map readInteger.B.words <$> B.getContents
  let solve ans !total [] = do
        print $ length ans
        putStrLn $ unwords $ map show $  ans
      solve ans !total ((i,c):rest)
        | total+c<=d = solve (i:ans) (total+c) rest
        | otherwise = do
            print $ length ans
            putStrLn $ unwords $ map show $ ans
  solve [] 0 $ sortBy(comparing snd)costs

import Data.List

data Client = Client { size :: Integer,
					ident :: Integer
					}
					deriving(Eq,Ord)
instance Show Client where
	show (Client _s i) = show i

process ls hs  = flip go 1
	where
		go [] _ = []
		go (l:h:cs) n = Client (l*ls+h*hs) n : go cs (succ n)

serve mem = flip go 0
	where
		go [] _ = []
		go (c@(Client s _):xs) n
			| n+s<=mem = c:go xs (n+s)
			| otherwise = []

main = do
	s <- fmap words getContents
	let (_:mem:ls:hs:cs) = map read s
	let servedclients =serve mem $ sort $ process ls hs cs
	print $ length servedclients
	putStrLn $ unwords $ map show servedclients

import Char (isDigit, ord)
import Control.Monad (liftM)
import Data.List (sortBy)

--import CPUTime
--import IO (hPutStrLn, stderr)

{-
import HUnit

testInput :: Test
testInput  =  TestList "TestInput"
  [
    Test "1" $ assertEq (2, [2,3]) $ solve 3 10 2 3 [(1,4), (2,1), (1,0)],
    Test "2" $ assertEq (1, [2]) $ solve 3 6 6 6 [(1,1), (1,0), (1,0)]
  ]

testBigNumbers :: Test
testBigNumbers  =  Test "TestBigNumbers" $
    assertEq (1, [3]) $ solve 3 (10^9) (10^5) (10^5) [(10000, 10000), (10000, 0), (0,1)]

test :: IO ()
test  =  runs
  [
    testInput,
    testBigNumbers
  ]
-}

solve :: Int -> Int -> Int -> Int -> [(Int, Int)] -> (Int, [Int])
solve n d a b xs  =  solve' d (0, []) sorted
  where
    sorted  =  sortBy (\n1 n2 -> compare (snd n1) (snd n2)) $
        zipWith (\n (x, y) -> (n, a * x + b * y)) [1..] xs
    solve' _ acc []  =  acc
    solve' freeMemory (c, acc) ((n, memory) : xs)
      | freeMemory' >= 0  =  solve' freeMemory' (c + 1, n : acc) xs
      | otherwise  =  (c, acc)
      where
        freeMemory'  =  freeMemory - memory

readPair :: String -> (Int, Int)
readPair s  =  reads' 0 s
  where
    reads' a (' ':s)  =  reads'' a 0 (dropWhile (== ' ') s)
    reads' a (c:s)
      | isDigit c  =  reads' (10*a + ord c - ord '0') s
      | otherwise  =  error $ concat ["readPair: unknown symbol ", show c]
    reads'' a b []  =  (a, b)
    reads'' a b (c:s)
      | isDigit c  =  reads'' a (10*b + ord c - ord '0') s
      | otherwise  =  error $ concat ["readPair: unknown symbol ", show c]

printAns :: (Int, [Int]) -> IO ()
printAns (n, xs)  =  print n  >> printAns' xs
  where
    printAns' []  =  return ()
    printAns' [x]  =  print x
    printAns' (x:xs)  =  putStr (concat [show x, " "]) >> printAns' xs

main :: IO ()
main  =  do
--    timeStart  <-  getCPUTime

    lines'  <-  liftM lines getContents
    let (n, d)  =  (readPair . head) lines'
    let (a, b)  =  (readPair . (head . tail)) lines'
    let xs  =  (take n . map readPair . (tail . tail)) lines'
    printAns $ solve n d a b xs

--    timeEnd  <-  getCPUTime
--    hPutStrLn stderr $ concat ["Time = ", show $ fromIntegral (timeEnd - timeStart) / (10^12), " sec."]

import Data.List

data Client = Client { size :: Int,
					ident :: Int
					}
					deriving(Eq,Ord)
instance Show Client where
	show (Client _s i) = show i

process ls hs  = flip go 1
	where
		go [] _ = []
		go (l:h:cs) n = Client (l*ls+h*hs) n : go cs (succ n)

serve mem = flip go 0
	where
		go [] _ = []
		go (c@(Client s _):xs) n
			| n+s<=mem = c:go xs (n+s)
			| otherwise = []

main = do
	s <- fmap words getContents
	let (_:mem:ls:hs:cs) = map read s
	let servedclients =serve mem $ sort $ process ls hs cs
	print $ length servedclients
	putStrLn $ unwords $ map show servedclients

{-# LANGUAGE BangPatterns #-}

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

readInt s = let Just (n,_) = B.readInt s in n

main = do
  [_,d] <- map read.words <$> getLine
  [a,b] <- map read.words <$> getLine
  let toCosts [] = []
      toCosts (x:y:xys) = (a*x+b*y):toCosts xys
  costs <- zip[1..].toCosts.map readInt.B.words <$> B.getContents
  let solve !ans !total [] = do
        print $ length ans
        putStrLn $ unwords $ map show $  ans
      solve !ans !total ((i,c):rest)
        | total+c<=d = solve (i:ans) (total+c) rest
        | otherwise = do
          print $ length ans
          putStrLn $ unwords $ map show $ ans
  solve [] 0 $ sortBy(comparing snd)costs


import Data.List

main = do
  _ <- getLine
  t <- getLine
  putStrLn $ sort t

import Control.Applicative
import Data.List

main = do
  n <- readLn :: IO Int
  s <- sort <$> getLine

  putStrLn $ s

-- Codeforces 1064 C
import qualified Data.Map.Strict as Map
import Data.List

createMap :: String -> Map.Map Char Int
createMap string = Map.fromListWith (+) [(c, 1) | c <- string]

toString :: Map.Map Char Int -> String
toString charMap = concat $ map (\(c, n) -> replicate n c) (Map.toList charMap)

main :: IO ()
main = do
    n <- getLine
    input <- getLine
    putStrLn ((toString . createMap) input )


main = do
	t<-getLine
	rest<-getContents
	let dict = map words $ lines rest
	putStrLn $ unlines $ solve dict

solve c = map head
           ((filter (elem "rat") c) ++
           (filter (\x->elem "child" x || elem "woman" x) c) ++
           (filter (elem "man") c) ++
           (filter (elem "captain") c))

import Data.List
main=interact$unlines.map snd.sort.map f.zip[1..].tail.lines
f(i,x)=((g b,i),a) where [a,b]=words x
g('m':_)=3
g('w':_)=2
g(_:'h':_)=2
g('c':_)=4
g _=1

import Data.List (sortBy)
import Data.Function (on)

main :: IO ()
main = getContents >>= mapM_ putStrLn . solve . map words . tail . lines

solve :: [[String]] -> [String]
solve = map (!!0) . sortBy (compare `on` (priority . (!!1)))
  where priority "rat" = 0 :: Int
        priority "woman" = 1
        priority "child" = 1
        priority "man" = 2
        priority "captain" = 3
        priority _ = 4

import Data.List
import Data.Ord
rank "rat" = 0
rank "child" = 1
rank "woman" = 1
rank "man" = 2
rank "captain" = 3
main = interact $ unlines . map head . sortBy (comparing $ rank . (!!1)) . map words . tail . lines

import Prelude
import List
import Char

main = interact q

q = func.tail.lines

func::[String]->String
func = unlines.solve.map words
fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

solve::[[String]]->[String]
solve a = rat ++ wac ++ man ++ cap
    where
      rat = map (!!0) $ filter (\ (_:a:[]) -> a `elem` ["rat"]) a
      wac = map (!!0) $ filter (\ (_:a:[]) -> a `elem` ["woman","child"]) a
      man = map (!!0) $ filter (\ (_:a:[]) -> a `elem` ["man"]) a
      cap = map (!!0) $ filter (\ (_:a:[]) -> a `elem` ["captain"]) a

import qualified Data.Map as M
import Data.List
pri = M.fromList [("rat", 1), ("child", 2), ("woman", 2), ("man", 4), ("captain", 5)]
main = do
    n <- read `fmap` getLine
    l <- mapM (\_ -> words `fmap` getLine) [1..n]
    let l1 = unlines $ map head $ sortBy (\[_, a] [_, b] -> compare (pri M.! a) (pri M.! b)) l
    putStr l1

import Data.List

order s = case s of
    "rat"       -> 0
    "woman"     -> 1
    "child"     -> 1
    "man"       -> 2
    _           -> 3

parseInput input = zip3 as bs cs where
    n = read $ head $ lines input :: Int
    is = map words $ tail $ lines input
--    xs = [x | [x,_] <- is]
    cs = map head is
    ys = map last is
    as = map order ys
    bs = take n [1..]

solve xs = ys where
    ys = map (\(_, _, c) -> c) $ sort xs

main = do
    input <- getContents
    let xs = parseInput input
    putStrLn $ intercalate "\n" $ solve xs

module Main where

import Control.Monad
import Data.List

data Crew = Crew { crewPri, crewPos :: Int, crewName :: String } deriving (Eq, Ord, Show)

groupPri "rat" = 1
groupPri "woman" = 2
groupPri "child" = 2
groupPri "man" = 3
groupPri "captain" = 4

main = do
    n <- read `liftM` getLine
    crews <- forM [1..n] $ \i -> do
        [name, group] <- words `liftM` getLine
        return $ Crew ( groupPri group ) i name

    putStr $ unlines $ map crewName $ sort crews

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

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

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

main = do
  getLine
  ls <- fmap (map (\[a, b] -> (a, b)) . map words . lines) getContents

  let
    f ((a, b), i) = (j, i)
      where
        j = case b of
              "rat" -> 0
              "woman" -> 1
              "child" -> 1
              "man" -> 2
              "captain" -> 3

  putStrLn $ unlines $ map (fst . fst) $ sortBy (compare `on` f) $ zip ls [1..]

import Data.List
import Data.Ord
import System.IO

main :: IO()
main = do
  interact $ unlines . map head . sortBy (comparing $ rank . (!!1)) . map words . tail . lines

rank :: String -> Int
rank x
  |x == "rat" = 0
  |x == "child" = 1
  |x == "woman" = 1
  |x == "man" = 2
  |x == "captain" = 3

import List

data CrewMember =  Rat Int String | WomanOrChild Int String | Man Int String | Captain Int String
    deriving (Show, Eq, Ord)

crewMember :: String -> Int -> String -> CrewMember
crewMember "captain" n name = Captain n name
crewMember "man" n name = Man n name
crewMember "woman" n name = WomanOrChild n name
crewMember "child" n name = WomanOrChild n name
crewMember _ n name = Rat n name

readLine :: Int -> IO CrewMember
readLine n = do
    line <- getLine
    let [name, status] = words line
    return (crewMember status n name)

myPrint :: [CrewMember] -> IO ()
myPrint members = do
    sequence_ (map myPrint_ members)
    where
        myPrint_ :: CrewMember -> IO ()
        myPrint_ (Captain n name) = putStrLn name
        myPrint_ (Man n name) = putStrLn name
        myPrint_ (WomanOrChild n name) = putStrLn name
        myPrint_ (Rat n name) = putStrLn name

main = do
    n <- readLn::(IO Int)
    lines <- sequence (map readLine [1..n])
    myPrint (sort lines)

import Data.List
main=interact$unlines.map snd.sort.map f.zip[1..].tail.lines
f(i,x)=((g b,i),a) where [a,b]=words x
g('m':_)=3
g('w':_)=2
g(_:'h':_)=4
g('c':_)=2
g _=1

import Data.List (sort)

main :: IO ()
main = getContents >>= mapM_ putStrLn . solve . map words . tail . lines

solve :: [[String]] -> [String]
solve = map snd . sort . map f
  where f [x, "rat"] = (0 :: Int, x)
        f [x, "woman"] = (1, x)
        f [x, "child"] = (2, x)
        f [x, "man"] = (3, x)
        f [x, "captain"] = (4, x)
        f _ = undefined

import Data.List (sort)

main :: IO ()
main = getContents >>= mapM_ putStrLn . solve . map words . tail . lines

solve :: [[String]] -> [String]
solve = map snd . sort . map f
  where f [x, "rat"] = (0 :: Int, x)
        f [x, "woman"] = (1, x)
        f [x, "child"] = (1, x)
        f [x, "man"] = (2, x)
        f [x, "captain"] = (3, x)
        f _ = undefined


{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}

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

rInt :: StateT BSL.ByteString Maybe Int
rInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')

main :: IO ()
main = do
  n <- readInt <$> getLine
  as <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine
  print $ query n as

query :: Int -> [Int] -> Int
query n as = (summ -) $ maximum $ map gainFor as
  where
    (!mini,!summ) = foldl' (\(!mini,!summ) a -> (mini `min` a, summ + a))
                    (maxBound,0) as
    gainFor a = search a 2 1 0
    search !a !x !prevx !prevgain
      | x > a `shiftR` 1 = prevgain
      | r /= 0           = search a (x+1) prevx prevgain
      | gain > prevgain  = search a (x+1) x gain
      | otherwise        = prevgain
      where
        (q,r) = a `divMod` x
        gain = (a + mini) - (q + mini * x)

#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read
#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling
C(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)
C(toInt,readInt,floorInt,ceilInt,Int)
C(toI8,readI8,floorI8,ceilI8,Int8)
C(toI16,readI16,floorI16,ceilI16,Int16)
C(toI32,readI32,floorI32,ceilI32,Int32)
C(toI64,readI64,floorI64,ceilI64,Int64)
C(toWord,readWord,floorWord,ceilWord,Word)
C(toW8,readW8,floorW8,ceilW8,Word8)
C(toW16,readW16,floorW16,ceilW16,Word16)
C(toW32,readW32,floorW32,ceilW32,Word32)
C(toW64,readW64,floorW64,ceilW64,Word64)
D(toDouble,readDouble,Double)
D(toFloat,readFloat,Float)
#undef D
#undef C

#define N(f,g,a,m)\
  f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\
  g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_
#define C(a,m)
N(newIOA,newIOA_,IOArray,IO)
N(newSTA,newSTA_,STArray s,ST s)
#undef C
#define C(a,m) MArray (a) e (m),
N(newIOUA,newIOUA_,IOUArray,IO)
N(newSTUA,newSTUA_,STUArray s,ST s)
#undef C
#undef N

import Data.List
main = interact $ show . solve . sort . map read . tail . words
solve (a0:as) = sum (as) + minimum (map f as) where
  f a = minimum [ x*a0 + a `div` x - a | x <- [1..a], a `mod` x == 0 ]

main = interact (format . solve . parse)

parse :: String -> [Int]
parse = (map read) . (drop 1) . words

solve a = (sum a) - maximum (0:
  (concat [
    map (\x -> let (q, r) = divMod ai x in if r == 0
      then ai - x - minA * (q - 1)
      else 0)
    [minA + 1..ai]
    | ai <- a])
  )
  where minA = minimum a

format = show


import Data.Int (Int64)
import qualified Data.IntMap.Strict as S
import Data.Maybe (fromJust, isNothing)

main = do
    _ <- getLine
    a <- map read . words <$> getLine
    print $ solve S.empty 0 a

solve :: S.IntMap Int -> Int64 -> [Int] -> Int
solve s h [] = sum $ S.elems s
solve s h (x:xs)
    | h' >= 0 = solve s' h' xs
    | otherwise =
        let ((y, c), s'') = S.deleteFindMin s'
         in solve
                (if c > 1
                     then S.insert y (c - 1) s''
                     else s'')
                (h' - fromIntegral y)
                xs
  where
    s' = S.insert x (1 + count s x) s
    h' = h + fromIntegral x

count :: S.IntMap Int -> Int -> Int
count s x
    | isNothing c = 0
    | otherwise = fromJust c
  where
    c = S.lookup x s

import Data.Maybe
import Data.Int
import Data.List
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder
import qualified Data.IntMap.Strict as IM
import System.IO

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

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

main :: IO ()
main = do
  _ <- getInts
  as <- getInts
  let (result, _, _) = foldl' acc (0, 0, IM.empty) as
      acc :: (Int, Int64, IM.IntMap Int) -> Int -> (Int, Int64, IM.IntMap Int)
      acc (num, hp, mp) a
        | a >= 0 = (num + 1, hp + fromIntegral a, mp)
        | hp + fromIntegral a < 0 = (num, hp', IM.alter dec a' mp')
        | otherwise = (num + 1, hp + fromIntegral a, IM.alter inc a mp)
        where Just (a', _) = IM.lookupMin mp'
              mp' = IM.alter inc a mp
              hp' = hp + fromIntegral a - fromIntegral a'
              inc Nothing = Just 1
              inc (Just x) = Just (x + 1)
              dec Nothing = Nothing
              dec (Just 1) = Nothing
              dec (Just x) = Just (x - 1)
  hPutBuilder stdout $ intDec result `mappend` charUtf8 '\n'


import qualified Data.List.Split as Split
import qualified Data.Tree as T
import qualified Data.Array as A
import Data.Int

data Color = Black | White

type Node = Int64

myToInt64 x = read x :: Int64
getInt64List = fmap ((map myToInt64) .(Split.splitOn " ")) getLine

listToAdjList :: Int64 -> [Int64] -> A.Array Int64 [Node]
listToAdjList n edges =
  A.accumArray (\l i -> (i+1):l) [] (0, n-1) (zip edges [0..])

modu x = x `mod` 1000000007

f :: A.Array Int64 Color -> A.Array Int64 [Node] -> Node -> Int64 -> Int64
f colors edges node b = go node b
  where memo = A.array ((0,0), (n-1, 1)) [ ((i, j), recu i j) | i <- [0 .. n - 1], j <- [0, 1]]
        go node b = memo A.! (node, b)
        n = snd (A.bounds colors) + 1
        recu node b = ways (colors A.! node) b (edges A.! node)
        ways :: Color -> Int64 -> [Node] -> Int64
        ways Black 1 ch = multiplyAll ch
        ways Black 0 ch = 0
        ways White 1 ch = fst $
          foldr (\c (r,p) ->
                   (modu $ modu (r * both c) + modu(p * go c 1),
                    modu $ p * both c))
                (0, 1)
                ch
        ways White 0 ch = multiplyAll ch
        multiplyAll :: [Node] -> Int64
        multiplyAll = moduProduct . (map both)
        both c = modu $ sum [go c b | b <- [0, 1]]

moduProduct :: [Int64] -> Int64
moduProduct = foldr (\x y -> modu $ x * y) 1

main = do
  n <- fmap myToInt64 getLine
  edges <- getInt64List
  colors <- fmap (map (\x -> case x of
                              1 -> Black
                              0 -> White))
                 getInt64List
  print $ f (A.listArray (0, n - 1) colors) (listToAdjList n edges) 0 1

import qualified Data.List.Split as Split
import qualified Data.Tree as T
import qualified Data.Array as A
import Data.Int
import Data.List as L

data Color = Black | White

type Node = Int64

myToInt64 x = read x :: Int64
getInt64List = fmap ((map myToInt64) .(Split.splitOn " ")) getLine

listToAdjList :: Int64 -> [Int64] -> A.Array Int64 [Node]
listToAdjList n edges =
  A.accumArray (\l i -> (i+1):l) [] (0, n-1) (zip edges [0..])

modu x = x `mod` 1000000007

f :: A.Array Int64 Color -> A.Array Int64 [Node] -> Node -> Int64 -> Int64
f colors edges node b = go node b
  where memo = A.array ((0,0), (n-1, 1)) [ ((i, j), recu i j) | i <- [0 .. n - 1], j <- [0, 1]]
        go node b = memo A.! (node, b)
        n = snd (A.bounds colors) + 1
        recu node b = ways (colors A.! node) b (edges A.! node)
        ways :: Color -> Int64 -> [Node] -> Int64
        ways Black 1 ch = multiplyAll ch
        ways Black 0 ch = 0
        ways White 1 ch = fst $
          L.foldl' (\(r,p) c ->
                   (modu $ modu (r * both c) + modu(p * go c 1),
                    modu $ p * both c))
                (0, 1)
                ch
        ways White 0 ch = multiplyAll ch
        multiplyAll :: [Node] -> Int64
        multiplyAll = moduProduct . (map both)
        both c = modu $ sum [go c b | b <- [0, 1]]

moduProduct :: [Int64] -> Int64
moduProduct = L.foldl' (\x y -> modu $ x * y) 1

main = do
  n <- fmap myToInt64 getLine
  edges <- getInt64List
  colors <- fmap (map (\x -> case x of
                              1 -> Black
                              0 -> White))
                 getInt64List
  print $ f (A.listArray (0, n - 1) colors) (listToAdjList n edges) 0 1

import qualified Data.List.Split as Split
import qualified Data.Tree as T
import qualified Data.Array as A

data Color = Black | White

type Node = Integer

myToInteger x = read x :: Integer
getIntegerList = fmap ((map myToInteger) .(Split.splitOn " ")) getLine

listToAdjList :: Integer -> [Integer] -> A.Array Integer [Node]
listToAdjList n edges =
  A.accumArray (\l i -> (i+1):l) [] (0, n-1) (zip edges [0..])

modu x = x `mod` 1000000007

f :: A.Array Integer Color -> A.Array Integer [Node] -> Node -> Integer -> Integer
f colors edges node b = go node b
  where memo = A.array ((0,0), (n-1, 1)) [ ((i, j), recu i j) | i <- [0 .. n - 1], j <- [0, 1]]
        go node b = memo A.! (node, b)
        n = snd (A.bounds colors) + 1
        recu node b = ways (colors A.! node) b (edges A.! node)
        ways :: Color -> Integer -> [Node] -> Integer
        ways Black 1 ch = multiplyAll ch
        ways Black 0 ch = 0
        ways White 1 ch = fst $
          foldr (\c (r,p) ->
                   (modu $ modu (r * both c) + modu(p * go c 1),
                    modu $ p * both c))
                (0, 1)
                ch
        ways White 0 ch = multiplyAll ch
        multiplyAll :: [Node] -> Integer
        multiplyAll = moduProduct . (map both)
        both c = modu $ sum [go c b | b <- [0, 1]]

moduProduct :: [Integer] -> Integer
moduProduct = foldr (\x y -> modu $ x * y) 1

main = do
  n <- fmap myToInteger getLine
  edges <- getIntegerList
  colors <- fmap (map (\x -> case x of
                              1 -> Black
                              0 -> White))
                 getIntegerList
  print $ f (A.listArray (0, n - 1) colors) (listToAdjList n edges) 0 1

import qualified Data.List.Split as Split
import qualified Data.Tree as T
import qualified Data.Array as A

data Color = Black | White

type Node = Int

toInt x = read x :: Int
getIntList = fmap ((map toInt) .(Split.splitOn " ")) getLine

listToAdjList :: Int -> [Int] -> A.Array Int [Node]
listToAdjList n edges =
  A.accumArray (\l i -> (i+1):l) [] (0, n-1) (zip edges [0..])

modu x = x `mod` 1000000007

f :: A.Array Int Color -> A.Array Int [Node] -> Node -> Int -> Int
f colors edges node b = go node b
  where memo = A.array ((0,0), (n-1, 1)) [ ((i, j), recu i j) | i <- [0 .. n - 1], j <- [0, 1]]
        go node b = memo A.! (node, b)
        n = snd (A.bounds colors) + 1
        recu node b = ways (colors A.! node) b (edges A.! node)
        ways :: Color -> Int -> [Node] -> Int
        ways Black 1 ch = multiplyAll ch
        ways Black 0 ch = 0
        ways White 1 ch = fst $
          foldr (\c (r,p) ->
                   (modu $ modu (r * both c) + modu(p * go c 1),
                    modu $ p * both c))
                (0, 1)
                ch
        ways White 0 ch = multiplyAll ch
        multiplyAll :: [Node] -> Int
        multiplyAll = moduProduct . (map both)
        both c = modu $ sum [go c b | b <- [0, 1]]

moduProduct :: [Int] -> Int
moduProduct = foldr (\x y -> modu $ x * y) 1

main = do
  n <- fmap toInt getLine
  edges <- getIntList
  colors <- fmap (map (\x -> case x of
                              1 -> Black
                              0 -> White))
                 getIntList
  print $ f (A.listArray (0, n - 1) colors) (listToAdjList n edges) 0 1

import qualified Data.List.Split as Split
import qualified Data.Tree as T
import qualified Data.Array as A

data Color = Black | White

type Node = Int

toInt x = read x :: Int
getIntList = fmap ((map toInt) .(Split.splitOn " ")) getLine

listToAdjList :: Int -> [Int] -> A.Array Int [Node]
listToAdjList n edges =
  A.accumArray (\l i -> (i+1):l) [] (0, n-1) (zip edges [0..])

modu x = x `mod` 1000000007

f :: A.Array Int Color -> A.Array Int [Node] -> Node -> Int -> Int
f colors edges node b = go node b
  where memo = A.array ((0,0), (n-1, 1)) [ ((i, j), recu i j) | i <- [0 .. n - 1], j <- [0, 1]]
        go node b = memo A.! (node, b)
        n = snd (A.bounds colors) + 1
        recu node b = ways (colors A.! node) b (edges A.! node)
        ways :: Color -> Int -> [Node] -> Int
        ways Black 1 ch = multiplyAll ch
        ways Black 0 ch = 0
        ways White 1 ch = fst $
          foldr (\c (r,p) ->
                   (modu $ r * both c + p * go c 1,
                    modu $ p * both c))
                (0, 1)
                ch
        ways White 0 ch = multiplyAll ch
        multiplyAll :: [Node] -> Int
        multiplyAll = moduProduct . map both
        both c = modu $ sum [go c b | b <- [0, 1]]

moduProduct :: [Int] -> Int
moduProduct = foldr (\x y -> modu $ x * y) 1

main = do
  n <- fmap toInt getLine
  edges <- getIntList
  colors <- fmap (map (\x -> case x of
                              1 -> Black
                              0 -> White))
                 getIntList
  print $ f (A.listArray (0, n - 1) colors) (listToAdjList n edges) 0 1


import Control.Monad; import Data.List; main = do { t <- readLn; replicateM_ t $ do { [a, b] <- fmap (sort . map read . words) getLine; putStrLn $ if or [mod (a + b) 3 > 0, b - a > a] then "NO" else "YES" } }

import Control.Monad
import Data.List

getStrList :: IO [String]
getStrList = fmap words getLine

getIntList :: IO [Integer]
getIntList = fmap (map read) getStrList

f :: Integer -> Integer -> String
f a b
    | mod (a + b) 3 > 0 = "NO"
    | b - a > a = "NO"
    | otherwise = "YES"

main :: IO()
main = do
    t <- readLn
    replicateM_ t $ do
        [a, b] <- fmap sort getIntList
        putStrLn $ f a b

import Control.Monad

solve :: Integer -> Integer -> Bool
solve x y = ((x+y) `mod` 3 ==0) && (2*min x y>=max x y)

routine :: IO ()
routine = do
  l <- fmap (map read . words) getLine
  if solve (head l) (l!!1) then putStrLn "YES" else putStrLn "NO"

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

import Control.Monad

solve :: Int -> Int -> Bool
solve x y = ((x+y) `mod` 3 ==0) && (3*min x y>=max x y)

routine :: IO ()
routine = do
  l <- fmap (map read . words) getLine
  if solve (head l) (l!!1) then putStrLn "YES" else putStrLn "NO"

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

import Control.Monad

solve :: Integer -> Integer -> Bool
solve x y = ((x+y) `mod` 3 ==0) && (3*min x y>=max x y)

routine :: IO ()
routine = do
  l <- fmap (map read . words) getLine
  if solve (head l) (l!!1) then putStrLn "YES" else putStrLn "NO"

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


readArr :: IO [Int]
readArr = (map (\s -> read s :: Int)) <$> (words <$> getLine)

gen :: Int -> Int -> Int
gen x y = let (x1, y1) = (x `mod` 4, y `mod` 4) in [[1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 0], [1, 0, 0, 1]] !! x1 !! y1

pr :: [[Int]] -> IO ()
pr [] = pure ()
pr (x: xs) = do
  putStrLn $ concat $ map (\x -> show x ++ " ") x
  pr xs

for :: Int -> IO ()
for 0 = pure ()
for i = do
  (n: m: _) <- readArr
  pr $ map (\x -> map (\y -> gen x y) [0..(m - 1)]) [0..(n - 1)]
  for $ i - 1

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

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

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,m] <- ri
        return (n,m)
    mapM_ (putStr.showM.solve) tcs

showM = unlines . map showL
showL = unwords . map show

solve (n,m) = matr
  where
    matr = [[f (y-1,x-1) | x <- [1..m]]
            |              y <- [1..n] ]
    f (a,b) = (y+x) `mod` 2
      where
        y = (a+1) `div` 2
        x = (b+1) `div` 2

(>>>) = flip (.)

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

solve :: [Int] -> [[Int]]
solve [n, m] =
  [ [ (bits (i `mod` 4) + bits (j `mod` 4)) `mod` 2
      | j <- [0 .. m - 1]
    ]
    | i <- [0 .. n - 1]
  ]

bits :: Int -> Int
bits 0 = 0
bits n = bits (n `div` 2) + (n `mod` 2)

getRow :: Int -> Int -> String
getRow i m = unwords $ take m $ cycle (if i `mod` 4 == 0 || i `mod` 4 == 3 then ["0", "1", "1", "0"] else ["1", "0", "0", "1"])

getNRows :: Int -> Int -> String
getNRows 0 _ = ""
getNRows n m = getNRows (n - 1) m ++ "\n" ++ getRow (n - 1) m

solveCase :: IO ()
solveCase = do
    dimensions <- getLine
    let nm = map (\w -> (read w :: Int)) $ words dimensions
    let n = head nm
    let m = last nm
    putStrLn $ getNRows n m

solve :: Int -> IO ()
solve 0 = do
    return ()
solve cases_left = do
    solveCase
    solve $ cases_left - 1

main = do
    s_testcases <- getLine
    solve $ (read s_testcases :: Int)

getRow :: Int -> Int -> String
getRow i m = unwords $ take m $ cycle (if i `mod` 4 == 0 || i `mod` 4 == 3 then ["0", "1", "1", "0"] else ["1", "0", "0", "1"])

getNRows :: Int -> Int -> String
getNRows 0 _ = ""
getNRows n m = getNRows (n - 1) m ++ "\n" ++ getRow (n - 1) m

solveCase :: IO ()
solveCase = do
    dimensions <- getLine
    let nm = map (\w -> (read w :: Int)) $ words dimensions
    let n = head nm
    let m = last nm
    putStrLn $ getNRows n m

solve :: Int -> IO ()
solve cases_left = do
    if cases_left == 1 then
        solveCase
    else do
        solveCase
        solve $ cases_left - 1

main = do
    s_testcases <- getLine
    solve $ (read s_testcases :: Int)

--
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}

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

import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.IO.Safe as IOA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import Data.Bits
import qualified Data.ByteString.Char8 as B8
import Data.Char
import Data.Int

import Data.Function (on)
import Data.Functor ((<&>))
import Data.Bifunctor (bimap)
import Data.Maybe (fromJust, fromMaybe, isJust)
import qualified Data.Maybe as MB

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

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

-- import Debug.Trace (trace, traceM, traceShowM)
-- debug = flip trace
--
-- tracing t x = trace (t ++ " = " ++ show x) x
-- debugging x t = tracing t x

-- debug x t = x
-- trace t x = x
-- tracing t x = x
-- debugging x t = x

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

readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))

readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)

readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

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

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

m :: Int64
m = 998_244_353

newtype M = M { unM :: Int64 }
  deriving (Eq, Ord)

mI :: Int -> M
mI = M . fromIntegral

instance Show M where
    show (M v) = "M" ++ show v

instance Num M where
    fromInteger n = M $ fromInteger (n `mod` fromIntegral m)

    (M a) + (M b) | a + b >= m = M $ a + b - m
    (M a) + (M b) = M $ a + b

    (M a) - (M b) | a - b < 0 = M $ m + a - b
    (M a) - (M b) = M $ a - b

    (M a) * (M b) = M $ (a * b) `mod` m

    abs    = id
    signum = undefined

powM :: M -> Int64 -> M
powM a@(M ma) x
    | x == 0 = M 1
    | x == 1 = a
    | even x = let t = powM a (x `div` 2) in t * t
    | odd x = a * powM a (x - 1)

instance Fractional M where
    recip a = powM a $ m - 2
    fromRational d = (M . fromInteger . R.numerator $ d) * (recip . M . fromInteger . R.denominator $ d)

type GraphA = A.Array Int [Int]

graphFromEdges :: Int -> [(Int, Int)] -> GraphA
graphFromEdges n edges = graph
    where
        graph = STA.runSTArray $ do
            graphA <- MA.newArray (1, n) ([] :: [Int])
            forM_ edges $ \(u, v) -> do
                modifyArray graphA u (v:)
                modifyArray graphA v (u:)
            return graphA

{- END OF GENERAL -}

solve :: Int -> Int -> [[Int]]
solve n m = do
    i <- [1 .. n]
    let iValue = (i `div` 2) `mod` 2
    let
        row :: [Int] = do
            j <- [1 .. m]
            let jValue = (j `div` 2) `mod` 2
            return $ iValue `xor` jValue
    return row

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [n, m] <- B8.getLine <&> readIntB8s
        let answer = solve n m
        forM_ answer $ \row -> do
            forM_ row $ \value -> do
                printf "%d " value
            putStrLn ""

-- 1 0 0 1
-- 0 1 1 0
-- 0 1 1 0
-- 1 0 0 1
-- 1 0 0 1
-- 0 1 1 0
-- 0 1 1 0
-- 1 0 0 1

{-# LANGUAGE CPP #-}
import qualified Data.ByteString.Lazy.Char8 as P
import Control.Monad.ST
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
-- import qualified Data.ByteString.Lazy.Char8 as B
import System.IO
import Control.Monad.Trans.State
import Control.Monad.Trans
import Data.Maybe
import Data.Bits
import Prelude hiding (reverse)
import Data.List
import Debug.Trace

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

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

str = string7

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
#ifdef LOCAL
  handle <- openFile "input" ReadMode
  inp <- P.hGetContents handle
#else
  inp <- P.getContents
#endif
  let outp = evalState tloop inp
  P.putStr $ toLazyByteString outp

tloop :: SP Builder
tloop = do
  t <- getInt
  -- let t = 1
  fmap mconcat $ replicateM t $ solve

solve :: SP Builder
solve = do
  n <- getInt
  m <- getInt
  let
    row1 = take m $ cycle $ [1, 0] ++ [0, 1]
    row2 = take m $ cycle $ [0, 1] ++ [1, 0]
    rows = cycle $ [row1, row2, row2, row1]
    ans = take n rows
  fmap mconcat $ sequence $ fmap (pure . putInts) ans

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

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,m] <- ri
        return (n,m)
    mapM_ (putStr.showM.solve) tcs

showM = unlines . map showL
showL = unwords . map show

solve (n,m) = matr
  where
    matr = [[f (y,x) | x <- [1..m]]
            |          y <- [1..n] ]
    f (y,x) = (y+x) `mod` 2

(>>>) = flip (.)

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

solve :: [Int] -> [[Int]]
solve [n, m] =
  [ [ (bits i + bits j) `mod` 2
      | j <- [0 .. m -1]
    ]
    | i <- [0 .. n -1]
  ]

bits :: Int -> Int
bits 0 = 0
bits n = bits (n `div` 2) + (n `mod` 2)