module Main where

import Control.Monad (replicateM_)

testCase :: IO ()
testCase = do
  getLine
  healths <- map read . words <$> getLine
  blessings <- map read . words <$> getLine
  print $ sum healths + sum blessings - maximum blessings

main :: IO ()
main = do
  testCases <- read <$> getLine
  replicateM_ testCases testCase

module Main where

import Control.Monad (replicateM_)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B

testCase :: IO ()
testCase = do
  B.getLine
  healths <- map (maybe 0 fst . B.readInt) . B.words <$> B.getLine
  blessings <- map (maybe 0 fst . B.readInt) . B.words <$> B.getLine
  print $ sum healths + sum blessings - maximum blessings

main :: IO ()
main = do
  testCases <- B.readInt <$> B.getLine
  replicateM_ (maybe 0 fst testCases) testCase

{-# LANGUAGE CPP #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
#ifndef DEBUG
{-# LANGUAGE Safe #-}
#endif
{-# LANGUAGE Strict #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# 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 as M
import qualified Control.Monad.ST.Strict as ST
import qualified Control.Monad.State.Strict as S
import qualified Control.Monad.Trans.Class as T

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

#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

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

{- END OF GENERAL -}

solve :: Int -> [Int64] -> [Int64] -> Int64
solve n as bs = damage
    where
        damage = sum as + sum bs - maximum bs

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        n <- B8.getLine <&> readIntB8
        as <- B8.getLine <&> readIntegerB8s <&> L.map fromInteger
        bs <- B8.getLine <&> readIntegerB8s <&> L.map fromInteger
        let answer = solve n as bs
        printf "%lld\n" $ answer

{-# LANGUAGE LambdaCase, OverloadedLists, OverloadedStrings, TypeFamilies #-}
import Control.Monad
import Control.Monad.Fix
import Control.Monad.Reader
import Data.List
import Data.Maybe
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as C
import qualified GHC.Exts as Exts

-- Mike ༼ つ ◕_◕ ༽つ pls add lisps

solveCase :: E
solveCase =
    ["lambda", ["inp"],
        ["letrec", [["a", ["car", "inp"]],
                    ["b", ["cadr", "inp"]],
                    ["asum", ["apply", "+", "a"]],
                    ["bsum", ["apply", "+", "b"]],
                    ["bmax", ["apply", "max", "b"]]],
            ["-", ["+", "asum", "bsum"], "bmax"]]]

main :: IO ()
main = do
    [t] <- getInts
    replicateM_ t $ do
        getInts
        as <- getInts
        bs <- getInts
        print $ unI $ run [solveCase, ["q", [L (map I as), L (map I bs)]]]

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

----------

data E = I { unI :: Int } | M { unM :: String } | L { unL :: [E] } | F { unF :: [E] -> E }

instance Eq E where
    I x == I y = x == y
    M x == M y = x == y
    L x == L y = x == y
    _   == _   = False

instance Exts.IsString E where
    fromString = M

instance Exts.IsList E where
    type Item E = E
    fromList = L

run :: E -> E
run p = runReader (eval p) $ M.fromList
    [ ("+",     F $ I . sum . map unI)
    , ("-",     F $ I . \case [I x] -> -x; (I x : xs) -> foldl' (-) x (map unI xs))
    , ("max",   F $ I . maximum . map unI)
    , ("car",   F $ \[L x] -> head x)
    , ("cadr",  F $ \[L x] -> head (tail x))
    , ("apply", F $ \[F x, L xs] -> x xs)
    ]

eval :: E -> Reader (M.Map String E) E
eval = \case
    I x -> pure (I x)
    M x -> asks (M.! x)
    L x -> case x of
        ["q", x] -> pure x
        "lambda" : L xs : body -> do
            cur <- ask
            pure $ F $ \ys ->
                runReader (last <$> mapM eval body) (M.fromList (zip (map unM xs) ys) <> cur)
        "letrec" : L xs : body -> do
            new <- mfix $ \new -> do
                cur <- ask
                local (const new) $
                    (<> cur) . M.fromList <$> mapM (\(L [M x, y]) -> (,) x <$> eval y) xs
            local (const new) $ last <$> mapM eval body
        f : xs -> unF <$> eval f <*> mapM eval xs

import Data.Char
import Control.Monad

solve as bs = sum as + sum bs - foldr max 0 bs

loop = do
  _ <- getLine
  as <- map read <$> words <$> getLine
  bs <- map read <$> words <$> getLine
  print (solve as bs)

main = do
  t  <- read <$> getLine
  replicateM_ t loop

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

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

----- Solution
data TC = TC { n :: Int, as :: [Int64], bs :: [Int64] }

type Output = Int64

input :: Scanner TC
input = do
  n <- int
  as <- n >< int64
  bs <- n >< int64
  return TC {..}

solve :: TC -> Output
solve TC {..} = sum as + sum (bs >$> sort >>> init)

output :: Int -> Output -> C.ByteString
output ix = showB

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

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

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

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

infixl 0 >$>

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

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

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

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

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

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

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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

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

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

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

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

(><) = times

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

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

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

{-# LANGUAGE RecordWildCards #-}

module Main where

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

data Game = Game
  { positionToBlessing :: M.Map Int Int
  , monsters :: [Monster]
  }

data Monster = Monster
  { position :: Int
  , health :: Int
  , blessing :: Int
  }

solve :: Game -> Int
solve g@Game{..}
  | null monsters = 0
  | otherwise     = health bestMonster + positionalBlessing g bestMonster +
                    solve newGame
    where topMonsters = take 3 monsters
          (bestMonster:otherMonsters') = sortOn (greedyScore g) topMonsters
          otherMonsters = sortOn blessing otherMonsters'
          newGame = Game
            { positionToBlessing = M.delete (position bestMonster) positionToBlessing
            , monsters = otherMonsters ++ drop 3 monsters
            }

greedyScore :: Game -> Monster -> Int
greedyScore Game{..} Monster{..}
  | atFront && atBack    = 0
  | atFront              = blessing - snd (M.elemAt (M.findIndex position positionToBlessing + 1) positionToBlessing)
  | atBack               = blessing - snd (M.elemAt (M.findIndex position positionToBlessing - 1) positionToBlessing)
  | otherwise            = 2 * blessing
  where atFront = position == fst (M.findMin positionToBlessing)
        atBack = position == fst (M.findMax positionToBlessing)

positionalBlessing :: Game -> Monster -> Int
positionalBlessing Game{..} Monster{..}
  | atFront && atBack   = 0
  | atFront || atBack   = blessing
  | otherwise           = 2 * blessing
  where atFront = position == fst (M.findMin positionToBlessing)
        atBack = position == fst (M.findMax positionToBlessing)

testCase :: IO ()
testCase = do
  numberMonsters <- read <$> getLine
  healths <- map read . words <$> getLine
  blessings <- map read . words <$> getLine
  print $ solve $
    Game
      { positionToBlessing = M.fromList $ [1..numberMonsters] `zip` blessings
      , monsters = sortOn blessing $ map (\(position, health, blessing) -> Monster{..}) $ zip3 [1..numberMonsters] healths blessings
      }

main :: IO ()
main = do
  testCases <- read <$> getLine
  replicateM_ testCases testCase

{-# LANGUAGE RecordWildCards #-}

module Main where

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

data Game = Game
  { positionToBlessing :: M.Map Int Int
  , monsters :: [Monster]
  }

data Monster = Monster
  { position :: Int
  , health :: Int
  , blessing :: Int
  }

solve :: Game -> Int
solve g@Game{..}
  | null monsters = 0
  | otherwise     = health bestMonster + positionalBlessing g bestMonster +
                    solve newGame
    where topMonsters = take 3 monsters
          (bestMonster:otherMonsters') = sortOn (greedyScore g) topMonsters
          otherMonsters = sortOn blessing otherMonsters'
          newGame = Game
            { positionToBlessing = M.delete (position bestMonster) positionToBlessing
            , monsters = otherMonsters ++ drop 3 monsters
            }

greedyScore :: Game -> Monster -> Int
greedyScore Game{..} Monster{..}
  | atFront && atBack    = 0
  | atFront              = blessing - snd (M.elemAt (M.findIndex position positionToBlessing + 1) positionToBlessing)
  | atBack               = blessing + snd (M.elemAt (M.findIndex position positionToBlessing - 1) positionToBlessing)
  | otherwise            = 2 * blessing
  where atFront = position == fst (M.findMin positionToBlessing)
        atBack = position == fst (M.findMax positionToBlessing)

positionalBlessing :: Game -> Monster -> Int
positionalBlessing Game{..} Monster{..}
  | atFront && atBack   = 0
  | atFront || atBack   = blessing
  | otherwise           = 2 * blessing
  where atFront = position == fst (M.findMin positionToBlessing)
        atBack = position == fst (M.findMax positionToBlessing)

testCase :: IO ()
testCase = do
  numberMonsters <- read <$> getLine
  healths <- map read . words <$> getLine
  blessings <- map read . words <$> getLine
  print $ solve $
    Game
      { positionToBlessing = M.fromList $ [1..numberMonsters] `zip` blessings
      , monsters = sortOn blessing $ map (\(position, health, blessing) -> Monster{..}) $ zip3 [1..numberMonsters] healths blessings
      }

main :: IO ()
main = do
  testCases <- read <$> getLine
  replicateM_ testCases testCase

{-# LANGUAGE RecordWildCards #-}

module Main where

import Control.Monad (replicateM_)
import Data.List (sortOn)
import qualified Data.Set as S

data Game = Game
  { positions :: S.Set Int
  , monsters :: [Monster]
  }

data Monster = Monster
  { position :: Int
  , health :: Int
  , blessing :: Int
  }

solve :: Game -> Int
solve g@Game{..}
  | null monsters = 0
  | otherwise     = health bestMonster + fst (positionalBlessing g bestMonster) +
                    solve newGame
    where topMonsters = take 3 monsters
          (bestMonster:otherMonsters') = sortOn (positionalBlessing g) topMonsters
          otherMonsters = sortOn blessing otherMonsters'
          newGame = Game
            { positions = S.delete (position bestMonster) positions
            , monsters = otherMonsters ++ drop 3 monsters
            }

positionalBlessing :: Game -> Monster -> (Int, Bool)
positionalBlessing Game{..} Monster{..}
  | position == S.findMin positions && position == S.findMax positions  = (0, False)
  | position == S.findMin positions || position == S.findMax positions  = (blessing, False)
  | otherwise                                                           = (2 * blessing, True)

testCase :: IO ()
testCase = do
  numberMonsters <- read <$> getLine
  healths <- map read . words <$> getLine
  blessings <- map read . words <$> getLine
  print $ solve $
    Game
      { positions = S.fromList [1..numberMonsters]
      , monsters = sortOn blessing $ map (\(position, health, blessing) -> Monster{..}) $ zip3 [1..numberMonsters] healths blessings
      }

main :: IO ()
main = do
  testCases <- read <$> getLine
  replicateM_ testCases testCase

{-# LANGUAGE RecordWildCards #-}

module Main where

import Control.Monad (replicateM_)
import Data.List (sortOn)
import qualified Data.Set as S

data Game = Game
  { positions :: S.Set Int
  , monsters :: [Monster]
  }

data Monster = Monster
  { position :: Int
  , health :: Int
  , blessing :: Int
  }

solve :: Game -> Int
solve g@Game{..}
  | null monsters = 0
  | otherwise     = health bestMonster + positionalBlessing g bestMonster +
                    solve newGame
    where topMonsters = take 3 monsters
          (bestMonster:otherMonsters') = sortOn (positionalBlessing g) topMonsters
          otherMonsters = sortOn blessing otherMonsters'
          newGame = Game
            { positions = S.delete (position bestMonster) positions
            , monsters = otherMonsters ++ drop 3 monsters
            }

positionalBlessing :: Game -> Monster -> Int
positionalBlessing Game{..} Monster{..}
  | position == S.findMin positions && position == S.findMax positions  = 0
  | position == S.findMin positions || position == S.findMax positions  = blessing
  | otherwise                                                           = 2 * blessing

testCase :: IO ()
testCase = do
  numberMonsters <- read <$> getLine
  healths <- map read . words <$> getLine
  blessings <- map read . words <$> getLine
  print $ solve $
    Game
      { positions = S.fromList [1..numberMonsters]
      , monsters = sortOn blessing $ map (\(position, health, blessing) -> Monster{..}) $ zip3 [1..numberMonsters] healths blessings
      }

main :: IO ()
main = do
  testCases <- read <$> getLine
  replicateM_ testCases testCase


{-# LANGUAGE BlockArguments #-}

import Control.Arrow
import Data.List

main = do { n <- getLine
          ; x <- getLine
          ; putStrLn $ (words >>> map read >>> solve >>> map show >>> unwords) x
          }

cmp :: (Int,Int) -> (Int,Int) -> Ordering
cmp (x,_) (y,_) | x == y = EQ
                | x <  y = LT
                | x >  y = GT

solve :: [Int] -> [Int]
solve a = mapAccumL (\a j -> (a+1, (j,a))) 1 >>> snd >>> sortBy cmp >>> map snd $ a

import Data.List

main :: IO ()
main = interact g

g :: String -> String
g = unwords . (map show) . (map fst) . (sortBy f) . (zip [1..]) . map (fromIntegral . read) . words . last . lines
  where
    f = (\(_,a) (_,b) -> compare a b)

import Data.List
import Data.Tuple

main = do
    getLine
    as <- fmap (map read . words) getLine :: IO [Int]
    let bs = map snd $ sort $ zip as [1..]
    putStrLn $ unwords $ map show bs

import Data.List
main = interact $ unwords. map show. gao. map read. words
gao (n:s) = map snd. sort . map swap. zip [1..n] $ s
swap (a, b) = (b, a)

import Data.List

main = do
  n <- fmap read getLine  :: IO Int
  nums <- fmap (map read . words) getLine :: IO [Int]
  let answer = map snd $ sort $ zip nums [(1::Int)..]
  putStrLn $ intercalate " " (map show answer)

-- 136A
import Array
getT a = do
			c <- getChar
			if (c == ' ' || c == '\n') then return $ read $ reverse a
			                           else getT (c:a)

getList 0 = return []
getList n = do {x <- getT [] :: IO Int; xs <- getList (n-1); return (x:xs)}

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

solve n [] arr = arr
solve n (x:xs) arr = solve (n+1) xs (arr//[(x,n)])

main = do
			n <- readLn :: IO Int
			s <- getList n
			putStrLn $ prList $ elems $ solve 1 s (array (1,n) [(i,0) | i <- [1..n]])

main = interact $ unwords . map show . solve . map read . words . head . tail . lines

solve s = solve' s 1 (length s)
solve' s p n
  | p > n = []
  | otherwise = (calc s p 1):(solve' s (p+1) n)

calc (c:cs) p a
  | c == p = a
  | otherwise = calc cs p (a+1)

import List
getAns ::[Int] -> [Int]
getAns a = map snd (sort$zip a [1..l])
       where l = length a
main=interact$unwords.(map show).getAns.(map read).tail.words

import Data.List
import Data.Maybe
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve . concat.map (map read.words).take (2) . lines
solve :: [Int]->String
solve (x:xs) =unwords [show (z+1)|y <-[1..x],let z = fromJust $ elemIndex y xs]

solve :: [Int] -> [Int]
solve xs = map (find xs) [1..length xs]

find :: [Int] -> Int -> Int
find xs x = head (filter (\n -> xs !! n == x) [0..length xs - 1]) + 1

main = do
    getLine
    line <- getLine
    let xs = map read (words line)
    mapM_ (\x -> putStr (show x ++ " ")) (solve xs)

import Data.Array.Unboxed
import Control.Applicative

main = do
  n <- read <$> getLine
  xs <- map read . words <$> getLine
  let arr = array (1,n) [(x,i) | (x,i) <- zip xs [1..]] :: UArray Int Int
  putStrLn . unwords . map show $ elems arr

import Data.Array

solve (n:xs) = elems $ foldr transmit initial $ zip xs [1 ..]
    where initial = array (1, n) [(i, 0) | i <- [1 .. n]]
          transmit (x, i) ans = ans // [(x, i)]

main = interact $ unwords.map show.solve.map read.words

import List
solve :: [Int] -> [Int]
solve xs = map snd $ sortBy (\x y -> compare (fst x) (fst y)) $ zip xs [1..]
main = interact $ unwords.map show.solve.map read.tail.words

import Control.Monad
import Data.Sequence

main = getTwoLines >>= putStrLn . unwords . calc

getTwoLines :: IO (Int, Seq Int)
getTwoLines = liftM2 toTuple getLine getLine
  where toTuple a b = (read a, fromList $ map read $ words b)

calc :: (Int, Seq Int) -> [String]
calc (n, input) = resStr
  where res = foldr change input [0..n - 1]
        resStr = foldr (\x xs -> show x:xs) [] res
        change i res = update newIndex newValue res
          where value = index input i
                newIndex = value - 1
                newValue = i + 1

import Text.Printf
import Data.List
import Data.Functor
import Control.Applicative
import Prelude
import Control.Monad
import Data.Maybe
import Data.Function
import Data.Array

readInt :: String -> Int
readInt = Prelude.read

solve :: [Int] -> [Int]
solve a = elems $ array (1, length a) (zip a [1 ..])

main :: IO ()
main = do
    n <- readInt <$> getLine
    a <- (map readInt . words) <$> getLine
    let answer = solve a
    forM_ answer (printf "%d ")

getInt :: IO Int
getInt = readLn

readNumbers :: String -> [Int]
readNumbers = map read . words

resolveGifts a = [y | x <- [1 .. length(a)], y <- [1 .. length(a)], a !! (y - 1) == x]

solve a b = putStrLn $ foldr (\x y -> (show x) ++ " " ++ y) "" (resolveGifts (readNumbers b))
main = getInt >>= (\a -> getLine >>= solve a)

import Control.Monad
import Data.Array
import Data.Char
import Data.Int
import Data.List
import Data.Maybe
import qualified Data.ByteString.Char8 as B
getList :: Read a => IO [a]
getList = fmap (map (read . B.unpack) . B.words) B.getLine
getIntList :: IO [Int]
getIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine

pass :: String -> String
pass [] = []
pass ('B':'G':t) = 'G' : 'B' : pass t
pass (h:t) = h : pass t

solve :: [Int] -> [Int]
solve a = [1 + fromJust (elemIndex x a) | x <- [1 .. length a]]

main :: IO ()
main = do
        _ <- getLine
        a <- getIntList
        putStrLn . intercalate " " . map show $ solve a

import Control.Monad
import Data.Array
import Data.Char
import Data.Int
import Data.List
import Data.Maybe
import qualified Data.ByteString.Char8 as B
getList :: Read a => IO [a]
getList = fmap (map (read . B.unpack) . B.words) B.getLine
getIntList :: IO [Int]
getIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine

pass :: String -> String
pass [] = []
pass ('B':'G':t) = 'G' : 'B' : pass t
pass (h:t) = h : pass t

solve :: [Int] -> [Int]
-- solve a = [1 + fromJust (elemIndex x a) | x <- [1 .. length a]]
solve a = elems $ array (1, length a) (zip a [1..])

main :: IO ()
main = do
        _ <- getLine
        a <- getIntList
        putStrLn . intercalate " " . map show $ solve a

import Data.List
import Maybe

main = interact $ join . loc 1 . map read . words . head . tail . lines
loc n ls = loc' n (length ls) ls
loc' n 0 ls = []
loc' n m ls = (fromJust (elemIndex n ls) + 1): (loc' (n+1) (m-1) ls)
join [] = ""
join (n:ns) = show n ++ " " ++ join ns

import Control.Applicative
import Data.List

main=do
      getLine
      a<-(map read <$> words<$> getLine)::IO [Int]
      putStrLn $ intercalate " "$ map show $ map snd $ sort $ zip a [1..]

import List
main=interact$unwords.map(show.snd).sort.(`zip`[1..]).drop 2.(0:).map read.words

import Data.List (elemIndex)
import Data.Maybe (fromJust)

main :: IO ()
main = getContents >>= putStrLn . format . solve . map (map read . words) . lines

solve :: [[Int]] -> [Int]
solve [[n], ps] = [ 1 + fromJust (elemIndex i ps) | i <- [1..n] ]

format :: [Int] -> String
format = unwords . map show

import Prelude hiding (readList, showList)
import Control.Monad
import Control.Applicative
import Data.List

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

readList' :: Read a => a -> IO [a]
readList' _ = readList

readInt :: IO Int
readInt = head <$> readList' (undefined::Int)

showList :: Show a => [a] -> IO ()
showList = putStrLn . unwords . map show

skipLine :: IO ()
skipLine = void $ getLine

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

divUp :: Integral a => a -> a -> a
divUp x y
  | x `mod` y /= 0 = x `div` y + 1
  | otherwise      = x `div` y

main :: IO ()
main = do
  skipLine
  xs <- readList' (undefined::Int)
  showList $ map snd $ sort $ zip xs [1..]

import Data.List

getInts :: IO [Int]
getInts = do
  xs <- getLine
  return $ map read $ words xs

getInt :: IO Int
getInt = do
  x <- getLine
  return $ read x

pos :: [Int] -> Int -> Int
pos xs x = head [a | (a,b) <- zip [1..] xs, b == x]

solve :: [Int] -> [Int]
solve xs = [a | a <- map (pos xs) [1..length xs]]

main :: IO ()
main = do
  n  <- getInt
  xs <- getInts
  putStrLn $ unwords $ map show $ solve xs

import Data.Array
main = do
  n <- readLn
  a <- fmap (array (1,n) . flip zip [1..] . map read . words) getLine
  putStrLn . unwords . map show $ elems a

import Prelude
import List
import Char

main = interact q

q = func.words

func::[String]->String
func = solve.map toInt.tail

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

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

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

solve::[Int]->String
solve = tail . concat . map ((" "++).toString.snd). sort . map reverseTuple . zip [1..]

-- Vicfred
-- https://codeforces.com/problemset/problem/136/A

import Data.List
import Data.Char
import Data.Array
import qualified Data.ByteString.Char8 as B

getIntList :: IO [Int]
getIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine

solve :: [Int] -> [Int]
solve a = elems $ array (1, length a) (zip a [1..])

main :: IO ()
main = do
    _ <- getLine
    a <- getIntList
    putStrLn . intercalate " " . map show $ solve a

import Data.List
import Data.Function

transform :: [Int] -> [Int]
transform = fmap fst . sortBy (compare `on` snd) . zip [1..]

displ :: [Int] -> String
displ = unwords . fmap show

parseList :: String -> [Int]
parseList = map read . tail . words

solve :: String -> String
solve = displ . transform . parseList

main :: IO ()
main = interact solve

import Data.List
solve :: [Int] -> [(Int, Int)]
solve = sortOn snd . zip [1..]
p ((x,_):[]) = show x
p ((x,_):xs) = show x ++ " " ++ p xs
main = interact $ p . solve . map read . tail . words

import Data.List
main = interact $ unwords.map show.map(\(x,y) -> y+1).sort.(`zip` [0..]).map (read::String->Int).tail.words

import Data.List
main = interact $ unwords.map (show.snd).sort.(`zip` [1..]).map ((+0).read).tail.words

import Data.List
import Data.Maybe
--f :: Int -> (Int,Int)
--f x = fromJust $ elemIndex x [0..]
main = interact $ unwords.map show.map(\(x,y) -> y+1).sort.(`zip` [0..]).map (read::String->Int).tail.words

import Data.List
main = interact$unwords.map(show.snd).sort.(`zip`[1..]).map((+0).read).tail.words

import Data.List
main = interact $ unwords.map(\(x,y) -> show $ y+1).sort.(`zip` [0..]).map ((+0).read).tail.words

import Data.List(sort)
import Control.Applicative

main = do n <- read <$> getLine
          xs <- map read <$> words <$> getLine
          putStrLn $ unwords $ map show $ solve n xs

solve :: Int -> [Int] -> [Int]
solve _ xs = map snd $ sort $ zip xs [1..]

import Data.List

main :: IO ()
main = do
    line <- getLine
    let n = read line :: Int
    line <- getLine
    let pairs = [(read $ m!!(k - 1) :: Int, k) | k <- [1..n], let m = words line]
    putStrLn $ concatMap  ((++" ") . show) [get x pairs | x <- [1..n]]

get :: Int -> [(Int, Int)] -> Int
get k (x:xs)
    | k == fst x = snd x
    | otherwise = get k xs

import Data.List

f :: [Int] -> [Int]
f = snd . unzip . sortBy (\(a, _) (b, _) -> compare a b) . flip zip [1..]

main = interact $ intercalate " " . map show . f . map read . tail . words

import Data.List
import Data.Char
import Control.Applicative
import Control.Monad.Trans.State
import Control.Monad
--import System.Random
--sortOn
divup x y= -div(-x)y
digs 0 _=[];digs x b=mod x b:digs(div x b)b--BASE!!
iInts=fmap(\l->map read$words l)getLine::IO[Int]
skln=(>>)getLine
stail[]=[];stail a=tail a
eq3 a b c=a==b&&b==c
pop[_]=[];pop(x:s)=x:pop s;pop _=[]
foldli f o a=r o a 0 where r c(x:s)i=r(f x i c)s(i+1);r c[]_=c
trac=foldli(\r i c->c+r!!i)0

putArr :: [Int] -> IO ()
putArr xs = putStrLn (concat (map (\x -> show x ++ " ") xs))

invertPermutation ns = map fst (sortOn snd (zip [1..length ns] ns))

main = skln $ iInts >>= (putArr . invertPermutation)

import Data.List
import Data.Char
import Control.Applicative
import Control.Monad.Trans.State
import Control.Monad
--import System.Random
--sortOn
divup x y= -div(-x)y
digs 0 _=[];digs x b=mod x b:digs(div x b)b--BASE!!
iInts=fmap(\l->map read$words l)getLine::IO[Int]
skln=(>>)getLine
stail[]=[];stail a=tail a
eq3 a b c=a==b&&b==c
pop[_]=[];pop(x:s)=x:pop s;pop _=[]
foldli f o a=r o a 0 where r c(x:s)i=r(f x i c)s(i+1);r c[]_=c
trac=foldli(\r i c->c+r!!i)0

putArr :: [Int] -> (IO [()])
putArr xs = sequence (map (\x -> putStr (" " ++ show x ++ " ")) xs)

invertPermutation ns = map fst (sortOn snd (zip [1..length ns] ns))

main = skln $ iInts >>= (putArr . invertPermutation)

module Main where
atoi :: String->Int
atoi str = (read str :: Int)

insert :: [String] -> Int -> Int -> String -> [String]
insert list i tidx val = if(i < tidx) then (head list) : insert (tail list) (i+1) tidx val
						 else val : (tail list)

loop :: [String]->Int->[String]->[String]
loop [] i oprList = oprList
loop list i oprList = loop (tail list) (i+1) (insert oprList 1 (atoi(head list)) (show i))

printLoop [] = return()
printLoop lst = do
					putStr ((head lst) ++ " ")
					printLoop (tail lst)
main = do
		nstr <- getLine
		-- n = (atoi nstr)
		str <- getLine
		let res = (loop (words str) 1 (words str))  in
			printLoop res

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

main= do
	  getLine
	  s<- map read. words <$> getContents::IO [Int]
	  let t= map snd $ sort  $ zip  s [1..]
	  putStrLn $   intercalate " " $ map show t

{-}
A. Presents
============
time limit per test: 2 seconds
memory limit per test: 256 megabytes
input: standard input
output: standard output

Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.

If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.

Now Petya wants to know for each friend i the number of a friend who has given him a gift.

Input
------
The first line contains one integer n (1 ≤ n ≤ 100) — the quantity of friends Petya invited to the party. The second line contains n space-separated integers: the i-th number is pi — the number of a friend who gave a gift to friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.

Output
-------
Print n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i.

Sample test(s)
---------------
input
4
2 3 4 1
output
4 1 2 3
input
3
1 3 2
output
1 3 2
input
2
1 2
output
1 2
-}

import Data.List (sort)

inversePermutation :: [Int] -> [Int]
inversePermutation xs = map snd $ sort (zip xs ys)
  where ys = [1 .. length xs]

main = do
  input <- getContents
  let xs = map read $ (words . last) (lines input)
  putStrLn . unwords . map show $ inversePermutation xs

import Data.List
import Data.Function
toInt = read :: String -> Int
main = interact $ unwords . map show . fst . unzip . sortBy (compare `on` snd) . zip [1..] . map toInt . words . (!! 1) . lines

import Data.List
main = getLine >> getLine >>= putStrLn.unwords.map show.solve.map read.words

solve :: [Int] -> [Int]
solve x = map snd $ sortBy compare $ zip x [1..]

--ghc 7.10

import Data.List

sortedIndices :: (Ord a) => [a] -> [Int]
sortedIndices a = map snd $ sort (zip a [1..])

main = do
    nStr <- getLine
    pStr <- getLine
    let p = map read . words $ pStr :: [Int]
    putStrLn . unwords . map show $ sortedIndices p

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

sol :: [Int] -> [Int]
sol xx =
  let a = listArray (1, length xx) xx :: Array Int Int
  in aux xx a 1 []

aux :: [Int] -> Array Int Int -> Int -> [(Int, Int)] -> [Int]
aux [] a i updates = elems $ a // updates
aux (x:xs) a i updates = aux xs a (i+1) ((x, i):updates)

main = do
  i <- getLine
  let t = read i :: Int
  input_raw <- getLine
  let input = map (\n -> read n :: Int) $ words input_raw
  let ret = sol input
  putStrLn (intercalate " " (map show ret))

import Data.List

intFromMaybe m = case m of Just i -> i
                           Nothing -> 0

process :: Int -> [Int] -> [Int]
process count dataList =
   map ((+1) . intFromMaybe) $ map (\x -> elemIndex x dataList) [1..count]

main :: IO ()
main = do
    source <- getLine
    let count = read source :: Int
    sources <- getLine
    let numbers = read <$> words sources :: [Int]
    let result = process count numbers
    putStrLn (intercalate " " $ map show result)

import Data.List
main = interact $ unwords . map (show . snd) . sort . (`zip` [1..]) . drop 2 . (0:) . map read . words

import Data.List
main = do
        n_s <- getLine
        i_s <- getLine
        let fs = (zip (map read $ words i_s) [1..])::[(Int,Int)]
        putStrLn $ unwords (map show $ func fs)
func m = map snd  $ sort m

import Data.List
f::[Int] -> [Int]
f xs = let n = length xs
       in map fst.sortBy (\x y-> (snd x)`compare`(snd y)).zip [1..n] $ xs
main = interact $ intercalate " ".map show.f.map read.tail.words

import Data.Function
import Data.List

read_pair :: IO [Int]
read_pair = fmap (map read.words) getLine

main :: IO ()
main = do
  _ <- getLine
  cost <- read_pair
  let rev = zip cost [1..(length cost)]
  let res = sortBy (compare `on` fst) rev
  let to_p = [x | (_, x) <- res]
  putStrLn (intercalate " " (map show to_p))

import Control.Monad

main = do
  n <- readLn :: IO Int
  aa <- getLine
  let xs = map read $ words aa :: [Int]
  let ys = [1..n]
  let xy = zip xs ys

  let ans = map (\y -> snd $ head $ filter (\(x,_) -> x==y) xy  ) ys

  putStrLn $ unwords $ map show ans

module Main (main)
    where

import Data.List (sortBy)
import Data.Ord (comparing)

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

main :: IO ()
main = putStrLn . unwords . map show . solve . readInts =<< (getLine >> getLine)
    where solve = map fst . sortBy (comparing snd) . zip [1..]

main = do
	n<-getLine
	s<-getLine
	putStrLn $ hepler $map read (words s)

hepler s =init $concat $map (++" ") $map (solve s) [1..length s]

solve s pos=show ( head [x+1 | x<-[0..length s-1], pos==s!!x])

import Data.List
import Data.Maybe

main = do
   n <- fmap read getLine
   p <- fmap (map read . words) getLine :: IO [Int]
   putStrLn . unwords . map show $ map ((+1) . fromJust . flip elemIndex p) [1..n]

-- vim: set expandtab:

import Data.Array.IArray

-- Snippet: readItems
readItems = do
    line <- getLine
    return $ map read $ words line

main = do
    n <- readLn
    a <- readItems
    let b = array (1, n) (zip a [1 ..])
    putStrLn $ unwords $ map show $ elems (b :: Array Int Int)

import Data.List
import Data.Tuple

main = do
    getLine
    as <- fmap (map read . words) getLine :: IO [Int]
    let bs = map snd $ sort $ map swap $ zip as [1..]
    putStrLn $ unwords $ map show bs

import Data.List
import Data.Maybe
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ show.solve . concat.map (map read.words).take (2) . lines
solve :: [Int]->[Int]
solve (x:xs) =[z+1|y <-[1..x],let z = fromJust $ elemIndex y xs]

solve :: [Int] -> [Int]
solve xs = map (find xs) [1..length xs]

find :: [Int] -> Int -> Int
find xs x = head (filter (\n -> xs !! n == x) [0..length xs - 1]) + 1

main = do
    getLine
    line <- getLine
    let xs = map read (words line)
    print (solve xs)

solve :: [Int] -> [Int]
solve xs = map (find xs) [1..length xs]

find :: [Int] -> Int -> Int
find xs x = head (filter (\n -> xs !! n == x) [0..length xs - 1]) + 1

main = do
    print 1

getInt :: IO Int
getInt = readLn

readNumbers :: String -> [Int]
readNumbers = map read . words

resolveGifts a = foldr (\x y -> y ++ (show x) ++ " ") "" [(y + 1) | x <- [0 .. length(a) -1], y <- [0 .. length(a) - 1], a !! y == (x + 1)]

solve a b = putStrLn $ resolveGifts (readNumbers b)
main = getInt >>= (\a -> getLine >>= solve a)

import Data.List
solve :: [Int] -> [(Int, Int)]
solve = sortOn snd . zip [1..]
main = interact $ unwords . map (show . snd) . solve . map read . tail . words

import Data.List

main :: IO ()
main = do
    line <- getLine
    let n = read line :: Int
    line <- getLine
    let pairs = [(read $ m!!(k - 1) :: Int, k) | k <- [1..n], let m = words line]
    putStrLn $ intersperse ' ' $ concatMap show [get x pairs | x <- [1..n]]

get :: Int -> [(Int, Int)] -> Int
get k (x:xs)
    | k == fst x = snd x
    | otherwise = get k xs

import Data.List
import Data.Char
import Control.Applicative
import Control.Monad.Trans.State
import Control.Monad
--import System.Random
--sortOn
divup x y= -div(-x)y
digs 0 _=[];digs x b=mod x b:digs(div x b)b--BASE!!
iInts=fmap(\l->map read$words l)getLine::IO[Int]
skln=(>>)getLine
stail[]=[];stail a=tail a
eq3 a b c=a==b&&b==c
pop[_]=[];pop(x:s)=x:pop s;pop _=[]
foldli f o a=r o a 0 where r c(x:s)i=r(f x i c)s(i+1);r c[]_=c
trac=foldli(\r i c->c+r!!i)0

invertPermutation ns = map fst (sortOn snd (zip [1..length ns] ns))

main = skln $ iInts >>= (print . invertPermutation)

{-}
A. Presents
============
time limit per test: 2 seconds
memory limit per test: 256 megabytes
input: standard input
output: standard output

Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.

If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.

Now Petya wants to know for each friend i the number of a friend who has given him a gift.

Input
------
The first line contains one integer n (1 ≤ n ≤ 100) — the quantity of friends Petya invited to the party. The second line contains n space-separated integers: the i-th number is pi — the number of a friend who gave a gift to friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.

Output
-------
Print n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i.

Sample test(s)
---------------
input
4
2 3 4 1
output
4 1 2 3
input
3
1 3 2
output
1 3 2
input
2
1 2
output
1 2
-}

import Data.List (sort)

inversePermutation :: Ord a => [a] -> [a]
inversePermutation xs = map snd $ sort (zip ys xs)
  where ys = [1 .. length xs]

main = do
  input <- getContents
  let xs = words . last $ lines input
  putStrLn . unwords $ inversePermutation xs

import Data.List
import Data.Function
toInt = read :: String -> Int
main = interact $ unwords . map show . snd . unzip . sortBy (compare `on` snd) . zip [1..] . map toInt . words . (!! 1) . lines


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

process [a,b,c,d] = do
			putStrLn $ intercalate " " $ map show $ if a==c then [a,d] else [a,c]

main = do
		n<- read <$> getLine ::IO Int
		a<-map(map read) <$> map words <$> replicateM n getLine ::IO [[Int]]
		mapM_ process a

import Control.Monad
main = do
  q <- readLn
  replicateM_ q $ do
    [l1,r1,l2,r2] <- map read . words <$> getLine :: IO [Int]
    let (a,b) = head [ (a,b) | a <- [l1..r1], b <- [l2..r2], a /= b ]
    putStrLn $ show a ++ " " ++ show b

main :: IO ()
main = do
  queries <- readLn :: IO Int
  do_queries queries

do_queries :: Int -> IO ()
do_queries 0 = return ()
do_queries n = do
  l <- getLine
  let numbers = map (read :: String -> Int) (words l)
  let (a,b) = solve numbers
  putStrLn $ (show a) ++ " " ++ (show b)
  do_queries $ n-1

solve :: [Int] -> (Int,Int)
solve (l1:r1:l2:r2:[]) = head [(i,j) | i <- [l1..r1], j <- [l2..r2], i /= j]

process :: (Int, Int, Int, Int) -> (Int, Int)
process (l1,r1,l2,r2)
    | l1 /= l2 = (l1,l2)
    | otherwise = (r1,l2)

readInt :: String -> Int
readInt = read

printPair :: (Int, Int) -> IO ()
printPair (x,y) = putStrLn $ show x ++ " " ++ show y

main :: IO ()
main = do
    t <- fmap readInt getLine
    ts <- fmap (map (map readInt.words).lines) getContents
    mapM_ printPair $ map (\[l1,r1,l2,r2] -> process (l1,r1,l2,r2)) ts

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

solve (a:_:b:_)
    | a == b = show a ++ (' ' : show (b + 1))
    | otherwise = show a ++ (' ' : show b)


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

import Data.Map((!))

result [] = []
result [x] = [0]
result array = (fmap (+1) $ result aLeft) ++ [0] ++ (fmap (+1) $ result aRight) where
	aRight = reverse $ takeWhile (<maxi) $ reverse array
	aLeft = takeWhile (<maxi) array
	maxi = maximum array

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

main = do
	t <- getLine >>= return . read :: IO Integer
	let loop t = if t == 0 then return () else do
		n <- getLine >>= return . read :: IO Integer
		a <- getLine >>= return . (fmap read) . words :: IO [Integer]
		putStrLn $ showR $ result $ fmap (\x->x-1) a
		loop $ t - 1
	loop t

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

main :: IO ()
main = B.interact $ B.unlines . map B.unwords . solve . tail . B.words

solve :: [ByteString] -> [[ByteString]]
solve []       = []
solve (n:rest) = construct (take n_int rest) 0:solve (drop n_int rest)
    where n_int = bstToInt n

bstToInt :: ByteString -> Int
bstToInt = fst . fromJust . B.readInt

construct :: [ByteString] -> Int -> [ByteString]
construct []  _     = []
construct arr depth = construct left (depth+1)++(B.pack . show $ depth):construct right (depth+1)
    where (left, _:right) = splitAt (snd . maximum $ zip (map bstToInt arr) [0..]) arr

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

main :: IO ()
main = B.interact $ B.unlines . map B.unwords . solve . tail . B.words

solve :: [B.ByteString] -> [[B.ByteString]]
solve []       = []
solve (n:rest) = (construct (take n_int rest) 0):solve (drop n_int rest)
    where n_int = bstToInt n

bstToInt :: B.ByteString -> Int
bstToInt = fst . fromJust . B.readInt

construct :: [B.ByteString] -> Int -> [B.ByteString]
construct []  _     = []
construct arr depth = (construct left (depth+1))++(B.pack . show $ depth):(construct right (depth+1))
    where (left, _:right) = splitAt (snd . maximum $ zip (map bstToInt arr) [0..]) arr

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

main :: IO ()
main = B.interact $ B.unlines . map B.unwords . solve . tail . B.words

solve :: [B.ByteString] -> [[B.ByteString]]
solve []       = []
solve (n:rest) = (construct (take n_int rest) 0):solve (drop n_int rest)
    where n_int = bstToInt n

bstToInt :: B.ByteString -> Int
bstToInt = fst . fromJust . B.readInt

construct :: [B.ByteString] -> Int -> [B.ByteString]
construct []  _     = []
construct arr depth = (construct left (depth+1))++(B.pack . show $ depth):(construct right (depth+1))
    where (left, _:right) = splitAt (snd . maximum $ zip (map bstToInt arr) [0..]) arr

import qualified Data.Array as A

type Arr = A.Array Int Int

recurse :: [Int] -> Int -> Int -> Arr -> Arr
recurse nodes depth offset depths
    | null nodes        = depths
    | length nodes == 1 = depths A.// [(offset, depth)]
    | otherwise         =
        let maxPair = maximum $ zip nodes [0..]
            maxIndex = snd maxPair
            lChunk = take maxIndex nodes
            rChunk = drop (maxIndex + 1) nodes
            newDepths1 = recurse lChunk (depth + 1) offset depths
            newDepths2 = recurse rChunk (depth + 1) (offset + maxIndex + 1) newDepths1
            newDepth = newDepths2 A.// [(offset + maxIndex, depth)]
         in newDepth

solveTest :: [Int] -> [Int]
solveTest perm = A.elems $ recurse perm 0 0 depths
    where depths = A.listArray (0, n - 1) [0 | _ <- [1..n]]
          n = length perm

showResult :: [Int] -> String
showResult = foldl (\s x -> s ++ show x ++ " ") ""

solve :: String -> String
solve = unlines . map solveStringTest . odds . drop 1 . lines
    where odds = map snd . filter (odd . fst) . zip [0..]
          solveStringTest = showResult . solveTest . map read . words

main :: IO ()
main = interact solve

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P

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

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

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

go :: Int -> [Int] -> [Int]
go d [] = []
go d [x] = [d]
go d xs = go (d+1) ys ++ [d] ++ go (d+1) zs
  where mx = maximum xs
        Just mxidx = elemIndex mx xs
        (yys, zs) = splitAt (mxidx+1) xs
        ys = init yys

solve :: IO ()
solve = do
  n <- readLn :: IO Int
  xs <- readInts :: IO [Int]
  let res = intercalate " " $ map show $ go 0 xs
    in putStrLn res

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

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

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

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

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

import Control.Applicative
import Control.Exception (assert)
import Control.Monad
import Control.Monad.State
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Bits
import Data.Bool
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.Int
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Ratio
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Traversable
import System.IO

------

type Hopper r = State [r]

type HopperT r = StateT [r]

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

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

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

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

type MonadHopper r m = MonadState [r] m

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

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

------

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

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

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

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

------

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

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

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

------

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

run1 = do
  n <- popInt
  ds <- popInts
  return $ B.unwords $ map bshow $ solve n ds

solve n ds = map snd $ sort $ go [(0, 0, n)]
  where
    segt = segTree max $ zip ds [0..]

    go [] = []
    go ((d, l, r) : qs)
      | l == r = go qs
      | otherwise = let (_, i) = segGet segt l r in
                      (i, d) : go ((d + 1, l, i) : (d + 1, i + 1, r) : qs)

data SegTree a = SegTree (a -> a -> a) [Array Int a]

segTree :: (a -> a -> a) -> [a] -> SegTree a
segTree f as = SegTree f $ make (length as) as
  where
    make 1 as = [listArray (0, 0) as]
    make n as = listArray (0, n - 1) as : half n as

    half n as | even n = make (n `quot` 2) $ go (n `quot` 2) as
              | otherwise = make (n `quot` 2 + 1) $ go (n `quot` 2) as

    go 0 as = as
    go n (a : b : as) = f a b : go (n - 1) as

segGet :: SegTree a -> Int -> Int -> a
segGet (SegTree f segs) l r = foldl1' f $ go segs l r
  where
    go (seg : segs) l r
      | r - l <= 0 = []
      | r - l == 1 = [seg ! l]
      | otherwise =
          let (l', la) | even l = (l, [])
                       | otherwise = (l + 1, [seg ! l])
              (r', ra) | even r = (r, [])
                       | otherwise = (r - 1, [seg ! (r - 1)]) in
            la ++ ra ++ go segs (l' `quot` 2) (r' `quot` 2)

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

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

import Data.Array.IArray

step :: [Int] -> Int -> [Int]
step li x = x : dropWhile (<= x) li

solve :: Int -> [Int] -> [Int]
solve n li = let
  lpotpars = map tail $ tail $ scanl step [] li
  rpotpars = map tail $ scanr (flip step) [] li
  depths :: Array Int Int
  depths = array (1, n) $ do
    (v, potL, potR) <- zip3 li lpotpars rpotpars
    pure $ (,) v $ case  potL ++ potR  of
      [] -> 0
      w  -> 1 + depths ! minimum w
  in  map (depths !) li

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n] <- readInts
    a <- readInts
    putInts $ solve n a

type SIO = StateT P.ByteString IO

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

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

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

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -Wno-name-shadowing #-}
{-# OPTIONS_GHC -Wno-type-defaults #-}

module Main where

import Control.Monad
import Data.List
import Data.Maybe
import GHC.Types

readNumbers :: (Integral b, Read b) => IO [b]
readNumbers = fmap read . words <$> getLine

{-# WARNING todo "'todo' remains in code" #-}
{-# INLINEABLE todo #-}
todo :: a
todo = error "Not implemented"

(!&) :: forall r a (b :: TYPE r). a -> (a -> b) -> b
x !& f = let !vx = x in f vx

infixl 1 !&

data Tree a = Branch (Tree a) a (Tree a) | Leaf

main :: IO [()]
main = do
  [t] <- readNumbers

  replicateM t $ do
    [n] <- readNumbers
    as <- readNumbers
    let sortedAs = sort as
        createTree [] = Leaf
        createTree as =
          let max = maximum as
              i = fromJust $ elemIndex max as
           in Branch (createTree $ take i as) max (createTree $ drop (i + 1) as)
        collectTree _ Leaf = []
        collectTree n (Branch left _ right) = collectTree (n + 1) left <> [n] <> collectTree (n + 1) right

    putStrLn . unwords . fmap show . collectTree 0 $ createTree as

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -Wno-name-shadowing #-}
{-# OPTIONS_GHC -Wno-type-defaults #-}

module Main where

import Control.Monad
import Data.List
import Data.Maybe
import GHC.Types

readNumbers :: (Integral b, Read b) => IO [b]
readNumbers = fmap read . words <$> getLine

{-# WARNING todo "'todo' remains in code" #-}
{-# INLINEABLE todo #-}
todo :: a
todo = error "Not implemented"

(!&) :: forall r a (b :: TYPE r). a -> (a -> b) -> b
x !& f = let !vx = x in f vx

infixl 1 !&

data Tree a = Branch (Tree a) a (Tree a) | Leaf

main :: IO [()]
main = do
  [t] <- readNumbers

  replicateM t $ do
    [n] <- readNumbers
    as <- readNumbers
    let sortedAs = sort as
        createTree [] = Leaf
        createTree as =
          let max = maximum as
              i = fromJust $ elemIndex max as
           in Branch (createTree $ take i as) max (createTree $ drop (i + 1) as)
        collectTree _ Leaf = []
        collectTree n (Branch left _ right) = collectTree (n + 1) left <> [n] <> collectTree (n + 1) right

    print . unwords . fmap show . collectTree 0 $ createTree as

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -Wno-name-shadowing #-}
{-# OPTIONS_GHC -Wno-type-defaults #-}

module Main where

import Control.Monad
import Data.List
import Data.Maybe
import GHC.Types

readNumbers :: (Integral b, Read b) => IO [b]
readNumbers = fmap read . words <$> getLine

{-# WARNING todo "'todo' remains in code" #-}
{-# INLINEABLE todo #-}
todo :: a
todo = error "Not implemented"

(!&) :: forall r a (b :: TYPE r). a -> (a -> b) -> b
x !& f = let !vx = x in f vx

infixl 1 !&

data Tree a = Branch (Tree a) a (Tree a) | Leaf

main :: IO [()]
main = do
  [t] <- readNumbers

  replicateM t $ do
    [n] <- readNumbers
    as <- readNumbers
    let sortedAs = sort as
        createTree [] = Leaf
        createTree as =
          let max = maximum as
              i = fromJust $ elemIndex max as
           in Branch (createTree $ take i as) max (createTree $ drop (i + 1) as)
        collectTree n Leaf = []
        collectTree n (Branch left _ right) = collectTree (n + 1) left <> [n] <> collectTree (n + 1) right

    print $ collectTree 0 $ createTree as

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -Wno-name-shadowing #-}
{-# OPTIONS_GHC -Wno-type-defaults #-}

module Main where

import Control.Monad
import Data.List
import Data.Maybe
import GHC.Types

readNumbers :: (Integral b, Read b) => IO [b]
readNumbers = fmap read . words <$> getLine

{-# WARNING todo "'todo' remains in code" #-}
{-# INLINEABLE todo #-}
todo :: a
todo = error "Not implemented"

(!&) :: forall r a (b :: TYPE r). a -> (a -> b) -> b
x !& f = let !vx = x in f vx

infixl 1 !&

data Tree a = Branch (Tree a) a (Tree a) | Leaf

main :: IO [()]
main = do
  [t] <- readNumbers

  replicateM t $ do
    [n] <- readNumbers
    as <- readNumbers
    let sortedAs = sort as
        createTree [] = Leaf
        createTree as =
          let max = maximum as
              i = fromJust $ elemIndex max as
           in Branch (createTree $ take i as) max (createTree $ drop (i + 1) as)
        collectTree n Leaf = [n]
        collectTree n (Branch left node right) = collectTree (n + 1) left <> [n] <> collectTree (n + 1) right

    print $ collectTree 0 $ createTree as

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -Wno-name-shadowing #-}
{-# OPTIONS_GHC -Wno-type-defaults #-}

module Main where

import Control.Monad
import Data.List
import Data.Maybe
import GHC.Types

readNumbers :: (Integral b, Read b) => IO [b]
readNumbers = fmap read . words <$> getLine

{-# WARNING todo "'todo' remains in code" #-}
{-# INLINEABLE todo #-}
todo :: a
todo = error "Not implemented"

(!&) :: forall r a (b :: TYPE r). a -> (a -> b) -> b
x !& f = let !vx = x in f vx

infixl 1 !&

data Tree a = Branch (Tree a) a (Tree a) | Leaf

main :: IO [()]
main = do
  [t] <- readNumbers

  replicateM t $ do
    [n] <- readNumbers
    as <- readNumbers
    let sortedAs = sort as
        createTree [] = Leaf
        createTree as =
          let max = maximum as
              i = fromJust $ elemIndex max as
           in Branch (createTree $ take i as) max (createTree $ drop (i + 1) as)
        collectTree Leaf = []
        collectTree (Branch left node right) = collectTree left <> [node] <> collectTree right

    print $ collectTree $ createTree as

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

main :: IO ()
main = B.interact $ B.unlines . map B.unwords . solve . tail . B.words

solve :: [B.ByteString] -> [[B.ByteString]]
solve []       = []
solve (n:rest) = (construct (take n_int rest) 0):solve (drop n_int rest)
    where n_int = bstToInt n

bstToInt :: B.ByteString -> Int
bstToInt = fst . fromJust . B.readInt

construct :: [B.ByteString] -> Int -> [B.ByteString]
construct []  _     = []
construct arr depth = (construct left (depth+1))++(B.pack . show $ depth):(construct right (depth+1))
    where (left, _:right) = splitAt (snd . maximum $ zip arr [0..]) arr


{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}
{-# LANGUAGE BangPatterns #-}

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

#if __GLASGOW_HASKELL__ < 706
modifyIORef' :: IORef a -> (a -> a) -> IO ()
modifyIORef' r f=do x<-readIORef r;writeIORef r$!f x
{-# INLINE modifyIORef' #-}
#endif

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

main = do
  [n,q] <- map read.words <$> getLine
  (as,lrs) <- splitAt n.map readInt.B.words <$> B.getContents
  segtree <- mkSegTree 0 (n-1) (listArray (0,n-1) $ repeat 0)
  let go st (l:r:rest) = update (l-1) (r-1) 1 st >> go st rest
      go _ _ = return ()
  go segtree lrs
  cnts <- fromSegTree 0 (n-1) segtree
  print $ solve as cnts

solve :: [Int] -> [Int] -> Integer
solve as cnts = go 0 (sortBy (flip compare) as) (sortBy (flip compare) cnts)
   where
     go !acc (x:xs) (y:ys) = go (toInteger x * toInteger y + acc) xs ys
     go acc _ _ = acc

data SegTree = Node !Int !Int !(IORef Int) !(IORef Int) !SegTree !SegTree
             | Leaf !Int !(IORef Int)

fromSegTree :: Int -> Int -> SegTree -> IO [Int]
fromSegTree l r segtree = mapM (\i -> query i i segtree) [l..r]

mkSegTree :: Int -> Int -> UArray Int Int -> IO SegTree
mkSegTree l r arr
  | l<r = do
      let !m = (l+r) `quot` 2
      lt <- mkSegTree l m arr
      rt <- mkSegTree (m+1) r arr
      let get (Node _ _ _ bref _ _) = readIORef bref
          get (Leaf _ ref) = readIORef ref
      xy <- (+) <$> get lt <*> get rt
      aref <- newIORef 0
      bref <- newIORef $! xy
      return $! Node l r aref bref lt rt
  | otherwise = do
      ref <- newIORef $! unsafeAt arr l
      return $! Leaf l ref

update :: Int -> Int -> Int -> SegTree -> IO ()
update kl kr x segtree = go segtree
   where
     go (Node l r aref bref lt rt) = do
       unless (r<kl || kr<l) $ do
         if kl<=l && r<=kr
            then modifyIORef' aref (x+)
            else do
              b <- readIORef bref
              writeIORef bref $! b + (min r kr-max l kl+1)*x
              go lt >> go rt
     go (Leaf k ref) = do
       when (kl<=k && k<=kr) $ do
          modifyIORef' ref (x+)

query :: Int -> Int -> SegTree -> IO Int
query kl kr segtree = go segtree
   where
     go (Node l r aref bref lt rt)
       | r<kl || kr<l   = return 0
       | kl<=l && r<=kr = do
           a <- readIORef aref
           b <- readIORef bref
           return $! a*(r-l+1)+b
       | otherwise = do
           xy <- (+) <$> go lt <*> go rt
           a <- readIORef aref
           return $! (min r kr-max l kl+1)*a + xy
     go (Leaf k ref)
       | kl<=k && k<=kr = readIORef ref
       | otherwise = return 0

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

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

main :: IO ()
main = do
  (n:_:t) <- map (fst . fromJust . C.readInt) <$> C.words <$> C.getContents
  let (a, q) = splitAt n t
      (l, r) = unzip $ pairs q
      x = accumArray (+) 0 (0, n) $
        zip (map pred l) (repeat 1) ++ zip r (repeat $ -1)
      y = scanl1 (+) $ init $ elems x
      f = map fromIntegral . sort
      z = sum $ zipWith (*) (f a) (f y)
  print $ (z :: Int64)

{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}
{-# LANGUAGE BangPatterns, TupleSections #-}

import Control.Applicative
import Control.Monad
import Data.Array.Base
import qualified Data.ByteString.Char8 as B
import Data.Function
import Data.List
import Data.IORef

#if __GLASGOW_HASKELL__ < 706
modifyIORef' :: IORef a -> (a -> a) -> IO ()
modifyIORef' r f=do x<-readIORef r;writeIORef r$!f x
{-# INLINE modifyIORef' #-}
#endif

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

main = do
  [n,q] <- map read.words <$> getLine
  (as,lrs) <- splitAt n.map readInt.B.words <$> B.getContents
  segtree <- mkSegTree 0 (n-1) (listArray (0,n-1) $ repeat 0)
  let go st (l:r:rest) = update (l-1) (r-1) 1 st >> go st rest
      go _ _ = return ()
  go segtree lrs
  xs <- fromSegTree 0 (n-1) segtree
  print $ sum $ zipWith ((*)`on`toInteger) (sortBy (flip compare) xs) (sortBy (flip compare) as)

data SegTree = Node !Int !Int !(IORef Int) !(IORef Int) !SegTree !SegTree
             | Leaf !Int !(IORef Int)

fromSegTree :: Int -> Int -> SegTree -> IO [Int]
fromSegTree l r segtree = go id [l..r]
   where
     go ans (x:xs) = do
       !qxx <- query x x segtree
       go (ans.(qxx:)) xs
     go ans _ = return $ ans []

mkSegTree :: Int -> Int -> UArray Int Int -> IO SegTree
mkSegTree l r arr
  | l<r = do
      let !m = (l+r) `quot` 2
      lt <- mkSegTree l m arr
      rt <- mkSegTree (m+1) r arr
      let get (Node _ _ _ bref _ _) = readIORef bref
          get (Leaf _ ref) = readIORef ref
      xy <- (+) <$> get lt <*> get rt
      aref <- newIORef 0
      bref <- newIORef $! xy
      return $! Node l r aref bref lt rt
  | otherwise = do
      ref <- newIORef $! unsafeAt arr l
      return $! Leaf l ref

update :: Int -> Int -> Int -> SegTree -> IO ()
update kl kr x segtree = go segtree
   where
     go (Node l r aref bref lt rt) = do
       unless (r<kl || kr<l) $ do
         if kl<=l && r<=kr
            then modifyIORef' aref (x+)
            else do
              b <- readIORef bref
              writeIORef bref $! b + (min r kr-max l kl+1)*x
              go lt >> go rt
     go (Leaf k ref) = do
       when (kl<=k && k<=kr) $ do
          modifyIORef' ref (x+)

query :: Int -> Int -> SegTree -> IO Int
query kl kr segtree = go segtree
   where
     go (Node l r aref bref lt rt)
       | r<kl || kr<l   = return 0
       | kl<=l && r<=kr = do
           a <- readIORef aref
           b <- readIORef bref
           return $! a*(r-l+1)+b
       | otherwise = do
           xy <- (+) <$> go lt <*> go rt
           a <- readIORef aref
           return $! (min r kr-max l kl+1)*a + xy
     go (Leaf k ref)
       | kl<=k && k<=kr = readIORef ref
       | otherwise = return 0

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

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

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

main = do
  [n,q] <- map read.words <$> getLine
  (as,lrs) <- splitAt n.map readInt.B.words <$> B.getContents
  print $ solve as $ imos n lrs

solve :: [Int] -> [Integer] -> Integer
solve as cnts = go 0 (sort as) (sort cnts)
   where
     go !acc (x:xs) (y:ys) = go (toInteger x * y + acc) xs ys
     go acc _ _ = acc

imos :: Int -> [Int] -> [Integer]
imos n lrs = scanl1 (+) $ map (toInteger.unsafeAt cnt) [0..n-1]
   where
     cnt :: UArray Int Int
     !cnt = unsafeAccumArray (+) 0 (0,n) $ go lrs
     go (l:r:lrs) = (l-1,1):(r,-1):go lrs
     go _ = []

{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.IORef

#if __GLASGOW_HASKELL__ < 706
modifyIORef' :: IORef a -> (a -> a) -> IO ()
modifyIORef' r f=do x<-readIORef r;writeIORef r$!f x
{-# INLINE modifyIORef' #-}
#endif

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

main = do
  [n,q] <- map read.words <$> getLine
  (as,lrs) <- splitAt n.map readInt.B.words <$> B.getContents
  segtree <- mkSegTree 0 (n-1) 0
  let go st (l:r:rest) = update (l-1) (r-1) 1 st >> go st rest
      go _ _ = return ()
  go segtree lrs
  cnts <- fromSegTree 0 (n-1) segtree
  print $ solve as cnts

solve :: [Int] -> [Int] -> Integer
solve as cnts = go 0 (radixSortRev as) (radixSortRev cnts)
   where
     go !acc (x:xs) (y:ys) = go (toInteger x * toInteger y + acc) xs ys
     go acc _ _ = acc

data SegTree = Node !Int !Int !(IORef Int) !(IORef Int) !SegTree !SegTree
             | Leaf !Int !(IORef Int)

fromSegTree :: Int -> Int -> SegTree -> IO [Int]
fromSegTree kl kr segtree = mapM f [kl..kr]
   where
     f key = go 0 segtree
      where
        go !acc (Node l r aref _ lt rt) = do
          if 2*key <= l+r
             then do
               a <- readIORef aref
               go (acc+a) lt
             else do
               a <- readIORef aref
               go (acc+a) rt
        go !acc (Leaf _ ref) = do
          r <- readIORef ref
          return $! acc+r

mkSegTree :: Int -> Int -> Int -> IO SegTree
mkSegTree !kl !kr !x0 = go kl kr
   where
     go !l !r
       | l<r = do
           let !m = (l+r) `quot` 2
           lt <- go l m
           rt <- go (m+1) r
           aref <- newIORef x0
           bref <- newIORef x0
           return $! Node l r aref bref lt rt
       | otherwise = do
           !ref <- newIORef x0
           return $! Leaf l ref

update :: Int -> Int -> Int -> SegTree -> IO ()
update !kl !kr !x segtree = go segtree
   where
     go (Node l r aref bref lt rt) = do
       unless (r<kl || kr<l) $ do
         if kl<=l && r<=kr
            then modifyIORef' aref (x+)
            else do
              b <- readIORef bref
              writeIORef bref $! b + (min r kr-max l kl+1)*x
              go lt >> go rt
     go (Leaf k ref) = do
       when (kl<=k && k<=kr) $ do
          modifyIORef' ref (x+)

radixSortRev :: [Int] -> [Int]
radixSortRev xs = runST $ do

  let !mask = 0xffff
      !n = length xs

  arr <- newListArray (0,n-1) xs :: ST s (STUArray s Int Int)
  tmp <- newArray (0,n-1) 0      :: ST s (STUArray s Int Int)
  count <- newArray (0,mask) 0   :: ST s (STUArray s Int Int)

  forM_ (map (mask.&.) xs) $ \mx -> do
    unsafeRead count mx >>= unsafeWrite count mx.(1+)
  forM_ [1..mask] $ \i-> do
    x <- unsafeRead count $ i-1
    unsafeRead count i >>= unsafeWrite count i.(x+)
  forM_ [n-1,n-2..0] $ \i-> do
    xi <- unsafeRead arr i
    let !mi = xi.&.mask
    !j <- subtract 1 <$> unsafeRead count mi
    unsafeWrite count mi j
    unsafeWrite tmp j xi

  forM_ [0..mask] $ \i-> do
    unsafeWrite count i 0

  forM_ (map ((mask.&.).(`unsafeShiftR`16)) xs) $ \mx -> do
    unsafeRead count mx >>= unsafeWrite count mx.(1+)
  forM_ [1..mask] $ \i-> do
    x <- unsafeRead count $ i-1
    unsafeRead count i >>= unsafeWrite count i.(x+)
  forM_ [n-1,n-2..0] $ \i-> do
    xi <- unsafeRead tmp i
    let !mi = (xi`unsafeShiftR`16).&.mask
    !j <- subtract 1 <$> unsafeRead count mi
    unsafeWrite count mi j
    unsafeWrite arr j xi

  forM [n-1,n-2..0] $ \i-> do
    unsafeRead arr i

{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.IORef

#if __GLASGOW_HASKELL__ < 706
modifyIORef' :: IORef a -> (a -> a) -> IO ()
modifyIORef' r f=do x<-readIORef r;writeIORef r$!f x
{-# INLINE modifyIORef' #-}
#endif

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

main = do
  [n,q] <- map read.words <$> getLine
  (as,lrs) <- splitAt n.map readInt.B.words <$> B.getContents
  segtree <- mkSegTree 0 (n-1) (listArray (0,n-1) $ repeat 0)
  let go st (l:r:rest) = update (l-1) (r-1) 1 st >> go st rest
      go _ _ = return ()
  go segtree lrs
  cnts <- fromSegTree 0 (n-1) segtree
  print $ solve as cnts

solve :: [Int] -> [Int] -> Integer
solve as cnts = go 0 (reverse $ radixSort as) (reverse $ radixSort cnts)
   where
     go !acc (x:xs) (y:ys) = go (toInteger x * toInteger y + acc) xs ys
     go acc _ _ = acc

data SegTree = Node !Int !Int !(IORef Int) !(IORef Int) !SegTree !SegTree
             | Leaf !Int !(IORef Int)

fromSegTree :: Int -> Int -> SegTree -> IO [Int]
fromSegTree l r segtree = mapM (\i -> query i i segtree) [l..r]

mkSegTree :: Int -> Int -> UArray Int Int -> IO SegTree
mkSegTree l r arr
  | l<r = do
      let !m = (l+r) `quot` 2
      lt <- mkSegTree l m arr
      rt <- mkSegTree (m+1) r arr
      let get (Node _ _ _ bref _ _) = readIORef bref
          get (Leaf _ ref) = readIORef ref
      xy <- (+) <$> get lt <*> get rt
      aref <- newIORef 0
      bref <- newIORef $! xy
      return $! Node l r aref bref lt rt
  | otherwise = do
      ref <- newIORef $! unsafeAt arr l
      return $! Leaf l ref

update :: Int -> Int -> Int -> SegTree -> IO ()
update kl kr x segtree = go segtree
   where
     go (Node l r aref bref lt rt) = do
       unless (r<kl || kr<l) $ do
         if kl<=l && r<=kr
            then modifyIORef' aref (x+)
            else do
              b <- readIORef bref
              writeIORef bref $! b + (min r kr-max l kl+1)*x
              go lt >> go rt
     go (Leaf k ref) = do
       when (kl<=k && k<=kr) $ do
          modifyIORef' ref (x+)

query :: Int -> Int -> SegTree -> IO Int
query kl kr segtree = go segtree
   where
     go (Node l r aref bref lt rt)
       | r<kl || kr<l   = return 0
       | kl<=l && r<=kr = do
           a <- readIORef aref
           b <- readIORef bref
           return $! a*(r-l+1)+b
       | otherwise = do
           xy <- (+) <$> go lt <*> go rt
           a <- readIORef aref
           return $! (min r kr-max l kl+1)*a + xy
     go (Leaf k ref)
       | kl<=k && k<=kr = readIORef ref
       | otherwise = return 0

radixSort :: [Int] -> [Int]
radixSort xs = elems $ runSTUArray $ do

  let !mask = 0xffff
      !n = length xs

  arr <- newListArray (0,n-1) xs :: ST s (STUArray s Int Int)
  tmp <- newArray (0,n-1) 0      :: ST s (STUArray s Int Int)
  count <- newArray (0,mask) 0   :: ST s (STUArray s Int Int)

  forM_ xs $ \x-> do
    let !mx = x.&.mask
    unsafeRead count mx >>= unsafeWrite count mx.(1+)
  forM_ [1..mask] $ \i-> do
    x <- unsafeRead count $ i-1
    unsafeRead count i >>= unsafeWrite count i.(x+)
  forM_ [n-1,n-2..0] $ \i-> do
    xi <- unsafeRead arr i
    let !mi = xi.&.mask
    j <- subtract 1 <$> unsafeRead count mi
    unsafeWrite count mi j
    unsafeWrite tmp j xi

  forM_ [0..mask] $ \i-> do
    unsafeWrite count i 0

  forM_ xs $ \x-> do
    let !mx = (x`shiftR`16).&.mask
    unsafeRead count mx >>= unsafeWrite count mx.(1+)
  forM_ [1..mask] $ \i-> do
    x <- unsafeRead count $ i-1
    unsafeRead count i >>= unsafeWrite count i.(x+)
  forM_ [n-1,n-2..0] $ \i-> do
    xi <- unsafeRead tmp i
    let !mi = (xi`shiftR`16).&.mask
    j <- subtract 1 <$> unsafeRead count mi
    unsafeWrite count mi j
    unsafeWrite arr j xi

  return arr

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.List

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

main = do
  [n,_] <- map read.words <$> getLine
  (as,lrs) <- splitAt n.map readInt.B.words <$> B.getContents
  print $ solve as $ imos n lrs

solve :: [Int] -> [Int] -> Integer
solve as cnts = go 0 (radixSort as) (radixSort cnts)
   where
     go !acc (x:xs) (y:ys) = go (toInteger x * toInteger y + acc) xs ys
     go acc _ _ = acc

imos :: Int -> [Int] -> [Int]
imos n lrs = scanl1 (+) $ map (unsafeAt cnt) [0..n-1]
   where
     !cnt = unsafeAccumArray (+) 0 (0,n) $ go lrs :: UArray Int Int
     go (l:r:lrs) = (l-1,1):(r,-1):go lrs
     go _ = []

radixSort :: [Int] -> [Int]
radixSort xs = runST $ do

  let !mask = 0xffff
      !n = length xs

  arr <- newListArray (0,n-1) xs :: ST s (STUArray s Int Int)
  tmp <- newArray (0,n-1) 0      :: ST s (STUArray s Int Int)
  count <- newArray (0,mask) 0   :: ST s (STUArray s Int Int)

  forM_ xs $ \x-> do
    let !mx = x.&.mask
    unsafeRead count mx >>= unsafeWrite count mx.(1+)
  forM_ [1..mask] $ \i-> do
    x <- unsafeRead count $ i-1
    unsafeRead count i >>= unsafeWrite count i.(x+)
  forM_ [n-1,n-2..0] $ \i-> do
    xi <- unsafeRead arr i
    let !mi = xi.&.mask
    j <- subtract 1 <$> unsafeRead count mi
    unsafeWrite count mi j
    unsafeWrite tmp j xi

  forM_ [0..mask] $ \i-> do
    unsafeWrite count i 0

  forM_ xs $ \x-> do
    let !mx = (x`shiftR`16).&.mask
    unsafeRead count mx >>= unsafeWrite count mx.(1+)
  forM_ [1..mask] $ \i-> do
    x <- unsafeRead count $ i-1
    unsafeRead count i >>= unsafeWrite count i.(x+)
  forM_ [n-1,n-2..0] $ \i-> do
    xi <- unsafeRead tmp i
    let !mi = (xi`shiftR`16).&.mask
    j <- subtract 1 <$> unsafeRead count mi
    unsafeWrite count mi j
    unsafeWrite arr j xi

  getElems arr


import Data.List
main = do
    [n, k] <- (map read . words) `fmap` getLine :: IO [Int]
    l <- (map read . words) `fmap` getLine :: IO [Int]
    let f l = concat $ map (\l'@(s:ss) -> reverse $ if s < k then (s+1):ss else l') $ group l
        f1 i l | all (==k) l = i
               | otherwise = f1 (i+1) $ f l
    print $ f1 0 l

module Main where

import Control.Monad

main = do
    [n, k] <- ( map read . words ) `liftM` getLine
    as <- ( map read . words ) `liftM` getLine

    let (_, count) = until ( (==k) . head . fst ) (\(as, count) ->
                let (as', _) = foldr (\a (res, last) ->
                            ( ( if a == last then a else a+1 ) : res, a )
                        ) ([], k) as
                in (as', count+1)
            ) (as, 0)

    putStrLn $ show count

main = do
	[n,k] <- getLine >>= return . map read . words :: IO [Int]
	lst <- getLine >>= return . map read . words :: IO [Int]
	let low x = length $ filter ((>=) x) lst
	(putStrLn . show . foldl max 0) [ (k - i) + (low i - 1) | i <- [1..k-1], low i > 0 ]

import List

next :: Int -> [Int] -> [Int]
next _ [] = []
next m [a] = if a < m then [a+1] else [a]
next m (a:b:as) = if a < b then (a+1):(next m (b:as)) else a:(next m (b:as))

solve :: Int -> [Int] -> Int
solve m as = length (takeWhile (\x -> head x < m) (iterate (next m) as))

main = do
  line <- getLine
  let [n, m] = map read (words line)
  line <- getLine
  let as = map read (words line)
  print (solve m as)

import List

notOver k xs = any (<k) xs
levelUp = concatMap (\(x:xs) -> (x + 1):xs).group.sort
solve (k:xs) = length $ takeWhile (notOver k) $ iterate levelUp xs

main = interact $ show.solve.tail.map read.words

import Prelude
import List
import Char
import Data.Ord
import Data.List

main = interact q

q = func.map words.lines

func::[[String]]->String
func x = toString $ solve a b
    where
      a = toInt (x!!0!!1)
      b = map toInt (x!!1)

toInt::String->Int
toInt = read
toString::Int->String
toString=show

solve::Int->[Int]->Int
solve k x = if le == 0 then 0 else (+1) $ solve k x4
    where
      x' = filter ((< k).head) $ group x
      le = length x'
      x1 = concat $ filter ((>= k).head) $ group x
      x2 = concat $ map tail x'
      x3 = map ((+1).head) x'
      x4 = sort $ concat [x1,x2,x3]

main = do
	[n,k] <- getLine >>= return . map read . words :: IO [Int]
	lst <- getLine >>= return . map read . words :: IO [Int]
	let low x = length $ filter ((>=) x) lst
	(putStrLn . show . foldl max 0) [ (k - i) + (low i - 1) | i <- [1..k], low i > 0 ]

main = do
	[n,k] <- getLine >>= return . map read . words :: IO [Int]
	lst <- getLine >>= return . map read . words :: IO [Int]
	let low x = length $ filter ((>=) x) lst
	(putStrLn . show . foldl max 0) [ (k - i) + (low i - 1) | i <- [1..k] ]


import Data.List
import Control.Monad

main = readLn >>= flip replicateM_ test

test = do
    getLine
    as <- map read . words <$> getLine
    print $ sum $ maximum <$> groupBy (\a b -> (a < 0) == (b < 0)) as

import Control.Monad

type Test = [Integer]

getTests :: Integer -> IO [Test]
getTests count = replicateM (fromIntegral count) getTest

getTest :: IO Test
getTest = do
    n <- getLine
    line <- getLine
    let list = map read (words line)
    return list

processTest :: Test -> Integer
processTest test = quantifyResult ([head test] ++ (tail test) ++ [-lastElement]) (head test) 0
    where lastElement = head $ reverse test

quantifyResult :: Test -> Integer -> Integer -> Integer
quantifyResult [x] maxElement result = result
quantifyResult (first:rest) maxElement result = if first*(head rest) > 0
                                                then quantifyResult rest (max maxElement (head rest)) result
                                                else quantifyResult rest (head rest) (result + maxElement)

printResult :: Integer -> IO ()
printResult result = print result

main :: IO ()
main = do
    count <- getLine
    tests <- getTests $ read count
    let results = map processTest tests
    mapM_ printResult results

module Main where

import Control.Monad
import Data.List

getStrList :: IO [String]
getStrList = words <$> getLine

getIntList :: IO [Integer]
getIntList = map read <$> getStrList

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        getLine
        a <- getIntList
        print $ f 0 0 a

pos :: Integer -> Bool
pos = (>0)

f :: Integer -> Integer -> [Integer] -> Integer
f v s [] = s + v
f 0 s (x:xs) = f x s xs
f v s (x:xs)
    | pos v == pos x = f (max x v) s xs
    | otherwise = f x (v + s) xs

module Main where

import Control.Monad
import Data.List

getStrList :: IO [String]
getStrList = words <$> getLine

getIntList :: IO [Integer]
getIntList = map read <$> getStrList

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        getLine
        a <- getIntList
        print $ f a

f :: [Integer] -> Integer
f = sum . map maximum . groupBy (\x y -> (x > 0) == (y > 0))

import           Control.Applicative
readArray :: IO [Integer]
readArray = do
  arrLine <- getLine
  return (map read (words arrLine) :: [Integer])

getSplitIdxs :: [(Integer, Integer, Int)] -> [Int]
getSplitIdxs [] = []
getSplitIdxs ((x, y, idx) : xs) | signum x /= signum y = idx : getSplitIdxs xs
                                | otherwise            = getSplitIdxs xs

getDifferences :: [Int] -> [Int]
getDifferences (x : xs) = x : ([ b - a | (b, a) <- zip xs (x : xs) ])
getDifferences []       = []

partition :: [Integer] -> [Int] -> [[Integer]]
partition []   []           = []
partition nums []           = [nums]
partition nums (cut : cuts) = take cut nums : partition (drop cut nums) cuts

solveCase :: IO ()
solveCase = do
  _   <- getLine
  arr <- readArray
  let zipped =
        getZipList $ (,,) <$> ZipList (drop 1 arr) <*> ZipList arr <*> ZipList
          [1 ..]
  let splitIdxs = getSplitIdxs zipped
  let diffs     = getDifferences splitIdxs
  let parts     = partition arr diffs
  putStrLn $ show (sum $ map maximum parts)

main :: IO ()
main = do
  tline <- getLine
  let ts = read tline :: Int
  sequence_ [ solveCase | _ <- [1 .. ts] ]

import Control.Monad
import Data.List

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

routine :: IO ()
routine = do
  _ <- getLine
  ns <- (map read.words) <$> getLine
  print $ solve ns

solve :: [Integer] -> Integer
solve ns = sum $ map maximum $ groupBy (\x y -> (x>0) == (y>0)) ns

import Control.Monad (replicateM_)
import Data.List (groupBy)

getList :: Read b => IO [b]
getList = map read . words <$> getLine

main :: IO ()
main = readLn >>= flip replicateM_ solveIO

solveIO :: IO ()
solveIO = getLine >> getList >>= print . solve

solve :: [Integer] -> Integer
solve = sum . map maximum . groupBy (\a b -> signum a == signum b)

data Mode = Pos | Neg

isPos :: Integer -> Bool
isPos n = n > 0

isNeg :: Integer -> Bool
isNeg n = n < 0

solve :: [Integer] -> Mode -> [Integer] -> [Integer]
solve [] _ ans = ans
solve numbers Pos ans = solve others Neg (m:ans)
  where (positives, others) = break isNeg numbers
        m = maximum positives
solve numbers Neg ans = solve others Pos (m:ans)
  where (negatives, others) = break isPos numbers
        m = maximum negatives

groupByTwo :: [String] -> [(String, String)]
groupByTwo [] = []
groupByTwo (a:b:xs) = (a,b):groupByTwo xs

solve' :: [Integer] -> Integer
solve' (x:xs)
  | x > 0 = sum $ solve (x:xs) Pos []
  | otherwise = sum $ solve (x:xs) Neg []

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

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

module Main where

import Control.Monad
import Data.List

getStrList :: IO [String]
getStrList = words <$> getLine

getIntList :: IO [Int]
getIntList = map read <$> getStrList

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        getLine
        a <- getIntList
        print $ f a

f :: [Int] -> Int
f = sum . map maximum . groupBy (\x y -> (x > 0) == (y > 0))

import Control.Monad
import Data.List

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

routine :: IO ()
routine = do
  _ <- getLine
  ns <- (map read.words) <$> getLine
  print $ solve ns

solve :: [Int] -> Int
solve ns = sum $ map maximum $ groupBy (\x y -> (x>0) == (y>0)) ns

import Control.Monad (replicateM_)
import Data.List (groupBy)

getList :: Read b => IO [b]
getList = map read . words <$> getLine

main :: IO ()
main = readLn >>= flip replicateM_ solveIO

solveIO :: IO ()
solveIO = getLine >> getList >>= print . solve

solve :: [Int] -> Int
solve = sum . map maximum . groupBy (\a b -> signum a == signum b)


import Control.Applicative ((<$>), (<*>))
import Data.List (transpose)
import Data.Maybe (listToMaybe)

main :: IO ()
main = printSolution =<< solve <$> (toTuple . map read . words <$> getLine)
                               <*> (map (map read . words) . lines <$> getContents)

solve :: (Int, Int) -> [[Int]] -> Maybe [[Int]]
solve (n, m) xss = listToMaybe [ cross (&&) n m is js | cross (||) n m is js == xss, not (null is) == not (null js) ]
  where (is, js) = (indices xss, indices (transpose xss))

indices :: [[Int]] -> [Int]
indices xss = [ i | (i, xs) <- zip [0..] xss, all (==1) xs ]

cross :: (Bool -> Bool -> Bool) -> Int -> Int -> [Int] -> [Int] -> [[Int]]
cross f n m is js = [ [ fromEnum ((i `elem` is) `f` (j `elem` js)) | j <- [0..m-1] ] | i <- [0..n-1] ]

toTuple :: [a] -> (a, a)
toTuple xs = (head xs, xs !! 1)

printSolution :: Maybe [[Int]] -> IO ()
printSolution Nothing = putStrLn "NO"
printSolution (Just xss) = putStrLn "YES" >> mapM_ (putStrLn . unwords . map show) xss

import Data.List (transpose)
import Data.Maybe (listToMaybe)

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

solve :: [[Int]] -> Maybe [[Int]]
solve ([n, m] : xss) = listToMaybe [ cross (&&) n m is js | cross (||) n m is js == xss, null is == null js ]
  where (is, js) = (indices xss, indices (transpose xss))

indices :: [[Int]] -> [Int]
indices xss = [ i | (i, xs) <- zip [0..] xss, all (==1) xs ]

cross :: (Bool -> Bool -> Bool) -> Int -> Int -> [Int] -> [Int] -> [[Int]]
cross f n m is js = [ [ fromEnum ((i `elem` is) `f` (j `elem` js)) | j <- [0..m-1] ] | i <- [0..n-1] ]

printSolution :: Maybe [[Int]] -> IO ()
printSolution Nothing = putStrLn "NO"
printSolution (Just xss) = putStrLn "YES" >> mapM_ (putStrLn . unwords . map show) xss

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

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

chunksOf :: Int -> [a] -> [[a]]
chunksOf n = map(take n).takeWhile(not.null).iterate(drop n)

main :: IO ()
main = do
  [n,m] <- map read.words <$> getLine
  mat <- map readInt.B.words <$> B.getContents
  case solve n m $ listArray((0,0),(n-1,m-1))mat of
    Nothing -> putStrLn "NO"
    Just res -> do
      putStrLn "YES"
      let xss = chunksOf m $ elems res
      putStr.unlines.map(unwords.map show) $ xss

solve :: Int -> Int -> UArray (Int,Int) Int -> Maybe (UArray (Int,Int) Int)
solve n m matB
  | calc n m matA == matB = Just matA
  | otherwise = Nothing
   where
    !matA = runSTUArray $ do
       mat <- newArray ((0,0),(n-1,m-1)) (-1) :: ST s (STUArray s (Int,Int) Int)
       let idx i j = i*m+j
       rep n $ \i-> do
         rep m $ \j-> do
           let bij = unsafeAt matB $ idx i j
           when (bij == 0) $ do
             rep n $ \k -> do
               unsafeWrite mat (idx k j) 0
             rep m $ \k -> do
               unsafeWrite mat (idx i k) 0
       rep n $ \i-> do
         rep m $ \j-> do
            aij <- unsafeRead mat $ idx i j
            when (aij<0) $ do
              unsafeWrite mat (idx i j) 1
       return mat

calc :: Int -> Int -> UArray (Int,Int) Int -> UArray (Int,Int) Int
calc n m mat = listArray ((0,0),(n-1,m-1)) [f i j|i<-[0..n-1],j<-[0..m-1]]
   where
     f i j
       | and [unsafeAt mat (i*m+k)==0|k<-[0..m-1]]
         && and [unsafeAt mat (k*m+j)==0|k<-[0..n-1]] = 0
       | otherwise = 1

import Control.Applicative ((<$>), (<*>))
import Data.List (transpose)
import Data.Maybe (listToMaybe)

main :: IO ()
main = printSolution =<< solve <$> (toTuple . map read . words <$> getLine)
                               <*> (map (map read . words) . lines <$> getContents)

solve :: (Int, Int) -> [[Int]] -> Maybe [[Int]]
solve (n, m) xss = listToMaybe [ cross (&&) n m is js | cross (||) n m is js == xss, not (null is), not (null js) ]
  where (is, js) = (indices xss, indices (transpose xss))

indices :: [[Int]] -> [Int]
indices xss = [ i | (i, xs) <- zip [0..] xss, all (==1) xs ]

cross :: (Bool -> Bool -> Bool) -> Int -> Int -> [Int] -> [Int] -> [[Int]]
cross f n m is js = [ [ fromEnum ((i `elem` is) `f` (j `elem` js)) | j <- [0..m-1] ] | i <- [0..n-1] ]

toTuple :: [a] -> (a, a)
toTuple xs = (head xs, xs !! 1)

printSolution :: Maybe [[Int]] -> IO ()
printSolution Nothing = putStrLn "NO"
printSolution (Just xss) = putStrLn "YES" >> mapM_ (putStrLn . unwords . map show) xss

import Control.Applicative ((<$>), (<*>))
import Data.List (transpose)
import Data.Maybe (listToMaybe)

main :: IO ()
main = printSolution =<< solve <$> (toTuple . map read . words <$> getLine)
                               <*> (map (map read . words) . lines <$> getContents)

solve :: (Int, Int) -> [[Int]] -> Maybe [[Int]]
solve (n, m) xss = listToMaybe [ cross (&&) n m is js | cross (||) n m is js == xss ]
  where (is, js) = (indices xss, indices (transpose xss))

indices :: [[Int]] -> [Int]
indices xss = [ i | (i, xs) <- zip [0..] xss, all (==1) xs ]

cross :: (Bool -> Bool -> Bool) -> Int -> Int -> [Int] -> [Int] -> [[Int]]
cross f n m is js = [ [ fromEnum ((i `elem` is) `f` (j `elem` js)) | j <- [0..m-1] ] | i <- [0..n-1] ]

toTuple :: [a] -> (a, a)
toTuple xs = (head xs, xs !! 1)

printSolution :: Maybe [[Int]] -> IO ()
printSolution Nothing = putStrLn "NO"
printSolution (Just xss) = putStrLn "YES" >> mapM_ (putStrLn . unwords . map show) xss


main = interact $ printAns. solve. readInp

readInp = lines
solve (a:b:_)
	| a /= b = max (length a) (length b)
	| otherwise = -1
printAns = show

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

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as B
import Text.Printf

readInt = ( readLn :: IO Int )
readInts = map ( read :: String -> Int ) . words <$> getLine

getList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

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

main = do
	[ s, t ] <- lines <$> getContents
	print $ which (-1) ( max ( length s ) ( length t ) ) $ s == t

main = interact $ show . solve . words

solve [a, b] = if a == b then -1 else max (length a) (length b)

main = do
        str1 <- getLine
        str2 <- getLine
        print (if str1 /= str2 then (max (length str1) (length str2)) else -1)

{-#  LANGUAGE NegativeLiterals #-}
import Data.List
import Data.Function
main = interact $  show . (\[x,y] -> if x == y then -1 else length $ maximumBy (compare `on` length) [x,y]) . lines

main :: IO ()
main = interact foo

foo :: String -> String
foo inp =
    let (a:b:_) = lines inp
    in if a == b
        then "-1"
        else show $ max (length a) (length b)

main = interact $ show . solve . lines
solve [a,b] | length a == length b = if a == b then -1 else length a
            | otherwise = max (length a) (length b)

main = do
    s1 <- getLine
    s2 <- getLine
    if s1 == s2
        then print (-1)
    else print $ max (length s1) (length s2)

main = do
    a_ <- getLine
    b_ <- getLine
    let
	lenA = length a_
	lenB = length b_
    print $ if a_/=b_
	then max lenA lenB
	else -1

main = do
    a <- getLine
    b <- getLine
    print $ if a == b then -1 else max (length a) (length b)

main = do
        str1 <- getLine
        str2 <- getLine
        putStrLn (if str1 /= str2 then (if (length str1) > (length str2) then str1 else str2) else "-1")

import Data.List
import Data.Function
main = interact $  (\[x,y] -> if x == y then "-1" else maximumBy (compare `on` length) [x,y]) . lines


module Main where

getNumbers :: IO [Int]
getNumbers = do
  line <- getLine
  return $ map read $ words line

solution :: () -> IO ()
solution _ = do
  [a, b, c, x, y] <- getNumbers
  let a_ = max 0 $ (x - a)
      b_ = max 0 $ (y - b)
      ans = if a_ + b_ <= c then "Yes" else "No"
  putStrLn ans

main :: IO ()
main = do
  [t] <- getNumbers

  mapM_ solution $ replicate t ()

module Main where

import Control.Monad (replicateM_)

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

solution :: IO ()
solution = do
  [a, b, c, x, y] <- getNumbers
  let a_ = max 0 (x - a)
      b_ = max 0 (y - b)
      ans = if a_ + b_ <= c then "Yes" else "No"
  putStrLn ans

main :: IO ()
main = do
  [t] <- getNumbers
  replicateM_ t solution

type Task = [TestCase]
type TestCase = (Int, Int, Int, Int, Int)

readInt :: String -> Int
readInt = read

showBool :: Bool -> String
showBool False = "NO"
showBool True = "YES"

parseInput :: String -> Task
parseInput contents = let input = tail . map (map readInt . words) . lines $ contents in
                      let parseTestCase (a:b:c:x:y:[]) = (a, b, c, x, y) in
                      map parseTestCase input

solve :: Task -> [Bool]
solve = map solveTestCase
    where solveTestCase (a, b, c, x, y) = x <= a + c && y <= b + c && x + y <= a + b + c

formatOutput :: [Bool] -> String
formatOutput = unlines . map showBool

main = getContents >>= (putStr . formatOutput . solve . parseInput)