Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present — the clock that shows not only the time, but also the date.The clock's face can display any number from 1 to d. It is guaranteed that ai ≤ d for all i from 1 to n. The clock does not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number d + 1, so after day number d it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day d is also followed by day 1.Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month.A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the n-th month inclusive, considering that on the first day of the first month the clock display showed day 1.

The first line contains the single number d — the maximum number of the day that Vasya's clock can show (1 ≤ d ≤ 106). The second line contains a single integer n — the number of months in the year (1 ≤ n ≤ 2000). The third line contains n space-separated integers: ai (1 ≤ ai ≤ d) — the number of days in each month in the order in which they follow, starting from the first one.

Print a single number — the number of times Vasya manually increased the day number by one throughout the last year.

NoteIn the first sample the situation is like this:   Day 1. Month 1. The clock shows 1. Vasya changes nothing.  Day 2. Month 1. The clock shows 2. Vasya changes nothing.  Day 1. Month 2. The clock shows 3. Vasya manually increases the day number by 1. After that the clock shows 4. Vasya increases the day number by 1 manually. After that the clock shows 1.  Day 2. Month 2. The clock shows 2. Vasya changes nothing.  In total, Vasya manually changed the day number by 1 exactly 2 times.

main :: IO()
main = do
    str1 <- getLine
    str2 <- getLine
    str3 <- getLine
    let d = read str1 :: Int
    let n = read str2 :: Int
    let a = map read (words str3) :: [Int]
    putStrLn $ show ((n - 1) * d - (sum . tail . reverse) a)

reads :: Read a => IO [a]
reads = getLine >>= sequence . map readIO . words

solve :: Integer -> [Integer] -> Integer
solve d []  =  error "Empty List!"
solve d [a]  =  0
solve d (a:as)  =  (d-a) + solve d as

main :: IO ()
main  =  do
    d <- readLn
    getLine
    as <- Main.reads
    print $ solve d as

main = do
  d <- readLn
  getLine
  as <- fmap (map read . words) getLine
  print $ sum $ map ((`mod` d) . (d -)) $ init as

solve :: (Integral a) => a -> a -> [a] -> a
solve d n xs =
    let
        full = (n-1)*d
        act = sum.init $ xs
    in
        full - act

main =
    do
        dstr <- getLine
        nstr <- getLine
        astr <- getLine
        putStrLn.show $ solve (read dstr) (read nstr) (map read $ words astr)

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

process :: Int -> [Int] -> Int
process d [] = 0
process d [a] = 0
process d (a: as) = (d - a) + (process d as)

main :: IO ()
main = do
	line <- getLine
	_ <- getLine
	arr1 <- getLine
	let
		d = read line:: Int
		a = map (\x -> read x :: Int).words $ arr1
	print $ process d a

answer :: Int -> [Int] -> Int
answer d as = sum . map (d -) . init $ as

main = do
	d <- getLine
	_ <- getLine
	as <- getLine
	putStrLn . show $ answer (read d) (map read . words $ as)

answer d a = sum . map(d-) . init $ a
main = do
    line <- getLine
    let d = read line :: Int
    getLine
    line <- getLine
    let a = map read . words $ line
    putStrLn . show $ answer d a

main=putStrLn.show.(\(d:z:as) -> slv d (take (z-1) $ as)).map read.words=<<getContents
slv d [] = 0
slv d (a:as) = f d (a:as) 1 0
f d [] t acc = acc
f d (a:as) t acc = (length (a:as))*d - sum(a:as)

main = do
  d <- readLn
  getLine
  as <- fmap (map read . words) getLine
  print $ sum $ map ((`mod` d) . (d -)) $ tail as

main=putStrLn.show.(\(d:z:as) -> slv d (take z $ as)).map read.words=<<getContents
slv d (a:as) = f d (as) 1 0
f d [] t acc = acc
f d (a:as) t acc
    | (t > a) = f d as 1 (acc + d - a)
    | otherwise = f d (a:as) (t+1) acc

main=putStrLn.show.(\(d:z:as) -> slv d (take z $ as)).map read.words=<<getContents
slv d [a] = 0
slv d (a:as) = f d (as) 1 0
f d [] t acc = acc
f d (a:as) t acc
    | (t > d) = f d as 1 (acc + d - a)
    | otherwise = f d (a:as) (t+1) acc

main=putStrLn.show.(\(d:z:as) -> slv d (take z $ as)).map read.words=<<getContents
slv d [a] = 0
slv d (a:as) = f d (as) 1 0
f d [] t acc = acc
f d (a:as) t acc
    | (t > a) = f d as 1 (acc + d - a)
    | otherwise = f d (a:as) (t+1) acc


Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise.However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not.Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring—that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.

The first line contains the number of questions on the olympiad n (1 ≤ n ≤ 100 000). The following line contains a binary string of length n representing Kevin's results on the USAICO.

Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.

NoteIn the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'.In the second sample, Kevin can flip the entire string and still have the same score.

import Data.List

solve :: String -> Int
solve x | n_threes > 0 || n_twos > 1 = 2 + n_groups
        | n_twos == 1 = 1 + n_groups
        | otherwise = n_groups
  where
    groups = map length $ group x
    n_groups = length groups
    f :: Int -> [Int] -> Int
    f i = length . filter (>=i)
    n_twos = f 2 groups
    n_threes = f 3 groups

main = interact $ show . solve . last . lines

import Data.Char (ord)

parse :: String -> String
parse = (!! 1) . lines

solve :: String -> Int
solve s = 1 + ones + min zeros 2
    where a = map (\c -> ord c - 48) s
          zeros = length . filter id $ zipWith (==) a (tail a)
          ones = length a - 1 - zeros

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

import Data.List

(|>) a b = b a

main = do
  s1 <- getLine
  s2 <- getLine
  let n = s1 |> (read :: String -> Int)
      d = s2 |> group |> map length |> length
      r = min (d + 2) (length s2)
  print r

import Data.List

(|>) a b = b a

getInt = do
  s <- getLine
  return (s |> (read :: String -> Int))

main = do
  n <- getInt
  s <- getLine
  f n s |> print

f n s = let
  ms = s |> group |> map length in
  length ms + if any (>= 3) ms then 2 else
    min 2 (ms |> filter (== 2) |> length)

count :: Char -> String -> Int
count _ [] = 0
count a (b:bs)
  | a == b = count a bs
  | otherwise = 1 + count b bs

solve' :: String -> Int
solve' (x:xs) = count x xs
solve' _ = 0

solve :: Int -> String -> Int
solve a b = min a $ ( (solve' b) + 3 )

parse :: String -> String
parse a = show $ solve (read $ head x) $ last x where x = words a

main = interact parse

import Data.List

parse :: String -> String
parse = (!! 1) . lines

adder :: [[Char]]->Int
adder s = min 2 $ sum $ map (\a -> length a - 1) s

solve :: String->Int
solve s = (length a) + adder a
 where a = group s

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

import Data.List

solve :: String -> Int
solve x | n_threes > 0 || n_twos > 1 = 2 + n_groups
        | otherwise = n_groups
  where
    groups = map length $ group x
    n_groups = length groups
    f :: Int -> [Int] -> Int
    f i = length . filter (>=i)
    n_twos = f 2 groups
    n_threes = f 3 groups

main = interact $ show . solve . last . lines

import Data.List

solve :: String -> Int
solve x | n_threes > 0 || n_twos > 1 = 2 + n_groups
        | head groups == 2 || last groups == 2 = 1 + n_groups
        | otherwise = n_groups
  where
    groups = map length $ group x
    n_groups = length groups
    f :: Int -> [Int] -> Int
    f i = length . filter (>=i)
    n_twos = f 2 groups
    n_threes = f 3 groups

main = interact $ show . solve . last . lines

import Data.List

(|>) a b = b a

getInt = do
  s <- getLine
  return (s |> (read :: String -> Int))

main = do
  n <- getInt
  s <- getLine
  f n s |> print

f n s = let
  ms = s |> group |> map length in
  length ms + if any (>= 3) ms then 2 else
    (if head ms >= 2 then 1 else 0) + (if last ms >= 2 then 1 else 0)

import Data.List

parse :: String -> String
parse = (!! 1) . lines

adder :: [[Char]]->Int
adder s = min 2 $ sum $ map (\a -> length a + 1) s

solve :: String->Int
solve s = (length a) + adder a
 where a = group s

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


Основой любой социальной сети является отношение дружбы между двумя пользователями в том или ином смысле. В одной известной социальной сети дружба симметрична, то есть если a является другом b, то b также является другом a. В этой же сети есть функция, которая демонстрирует множество людей, имеющих высокую вероятность быть знакомыми для пользователя. Эта функция работает следующим образом. Зафиксируем пользователя x. Пусть некоторый другой человек y, не являющийся другом x на текущий момент, является другом не менее, чем для k% друзей x. Тогда он является предполагаемым другом для x.У каждого человека в социальной сети есть свой уникальный идентификатор — это целое число от 1 до 109. Вам дан список пар пользователей, являющихся друзьями. Определите для каждого упомянутого пользователя множество его предполагаемых друзей.

В первой строке следуют два целых числа m и k (1 ≤ m ≤ 100, 0 ≤ k ≤ 100) — количество пар друзей и необходимый процент общих друзей для того, чтобы считаться предполагаемым другом. В последующих m строках записано по два числа ai, bi (1 ≤ ai, bi ≤ 109, ai ≠ bi), обозначающих идентификаторы пользователей, являющихся друзьями.  Гарантируется, что каждая пара людей фигурирует в списке не более одного раза.

Для всех упомянутых людей в порядке возрастания id выведите информацию о предполагаемых друзьях. Информация должна иметь вид "id:  k id1 id2 ... idk", где id — это id самого человека, k — количество его предполагаемых друзей, а id1, id2, ..., idk — идентификаторы его предполагаемых друзей в возрастающем порядке.

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

type Flist = M.Map Int (S.Set Int)

main = interact $ format . solve . parse

solve (m, k) = M.mapWithKey (findNew k m) m

findNew :: Int -> Flist -> Int ->  S.Set Int -> S.Set Int
findNew k m x s = M.keysSet
    . M.filter (\s' -> 100 * S.size s' >= k * S.size s)
    . M.map (S.intersection s)
    . flip M.difference (M.fromSet S.singleton s)
    . M.delete x
    $ m

parse :: String -> (Flist, Int)
parse = (\([_, k]:xss) -> (extract xss, k)) . map (map read) . map words . lines

extract :: [[Int]] -> Flist
extract = foldr takePair M.empty

takePair :: [Int] -> Flist -> Flist
takePair [x, y] = addFriend x y . addFriend y x

addFriend :: Int -> Int -> Flist -> Flist
addFriend x = M.insertWith S.union x . S.singleton

format :: Flist -> String
format = unlines . M.elems . M.mapWithKey (\k s -> show k ++ ": " ++ formatSet s)

formatSet :: S.Set Int -> String
formatSet s = unwords . map show $ S.size s : S.elems s


You are playing a computer game. To pass the current level, you have to kill a big horde of monsters. In this horde, there are $$$n$$$ monsters standing in the row, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th monster has $$$a_i$$$ health and a special "Death's Blessing" spell of strength $$$b_i$$$ attached to it.You are going to kill all of them one by one. It takes exactly $$$h$$$ seconds to kill a monster with health $$$h$$$.When the $$$i$$$-th monster dies, it casts its spell that increases the health of its neighbors by $$$b_i$$$ (the neighbors of the $$$j$$$-th monster in the row are the monsters on places $$$j - 1$$$ and $$$j + 1$$$. The first and the last monsters have only one neighbor each).After each monster is killed, the row shrinks, so its former neighbors become adjacent to each other (so if one of them dies, the other one is affected by its spell). For example, imagine a situation with $$$4$$$ monsters with health $$$a = [2, 6, 7, 3]$$$ and spells $$$b = [3, 6, 0, 5]$$$. One of the ways to get rid of the monsters is shown below:  $$$2$$$$$$6$$$$$$7$$$$$$3$$$$$$\xrightarrow{6\ s}$$$$$$8$$$$$$13$$$$$$3$$$$$$\xrightarrow{13\ s}$$$$$$8$$$$$$3$$$$$$\xrightarrow{8\ s}$$$$$$6$$$$$$\xrightarrow{6\ s}$$$$$$\{\}$$$$$$3$$$$$$6$$$$$$0$$$$$$5$$$$$$3$$$$$$0$$$$$$5$$$$$$3$$$$$$5$$$$$$5$$$ The first row represents the health of each monster, the second one — the power of the spells. As a result, we can kill all monsters in $$$6 + 13 + 8 + 6$$$ $$$=$$$ $$$33$$$ seconds. Note that it's only an example and may not be the fastest way to get rid of the monsters.What is the minimum time required to kill all monsters in the row?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of monsters in the row. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial health of corresponding monsters. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \le b_i \le 10^9$$$), where $$$b_i$$$ is the strength of the spell for the $$$i$$$-th monster. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer — the minimum possible total time to kill all monsters.

NoteIn the first test case, there is only one monster that will be killed in $$$10$$$ seconds.In the second test case, it's optimal to kill the first monster, the last monster and then the middle one. It will take $$$100 + 100 + (1 + 1 + 1)$$$ $$$=$$$ $$$203$$$ seconds.In the third test case, it's optimal to kill the first monster, then the third one, then the fourth one and finally the second one. It will take $$$2 + 7 + (3 + 0) + (3 + 6 + 5)$$$ $$$=$$$ $$$26$$$ seconds.

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

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

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


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.

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

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

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

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

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


You are given an array $$$a$$$ consisting of $$$n$$$ integers. You can perform the following operations with it:   Choose some positions $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n, i \ne j$$$), write the value of $$$a_i \cdot a_j$$$ into the $$$j$$$-th cell and remove the number from the $$$i$$$-th cell;  Choose some position $$$i$$$ and remove the number from the $$$i$$$-th cell (this operation can be performed no more than once and at any point of time, not necessarily in the beginning). The number of elements decreases by one after each operation. However, the indexing of positions stays the same. Deleted numbers can't be used in the later operations.Your task is to perform exactly $$$n - 1$$$ operations with the array in such a way that the only number that remains in the array is maximum possible. This number can be rather large, so instead of printing it you need to print any sequence of operations which leads to this maximum number. Read the output format to understand what exactly you need to print.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the elements of the array.

Print $$$n - 1$$$ lines. The $$$k$$$-th line should contain one of the two possible operations. The operation of the first type should look like this: $$$1~ i_k~ j_k$$$, where $$$1$$$ is the type of operation, $$$i_k$$$ and $$$j_k$$$ are the positions of the chosen elements. The operation of the second type should look like this: $$$2~ i_k$$$, where $$$2$$$ is the type of operation, $$$i_k$$$ is the position of the chosen element. Note that there should be no more than one such operation. If there are multiple possible sequences of operations leading to the maximum number — print any of them.

NoteLet X be the removed number in the array. Let's take a look at all the examples:The first example has, for example, the following sequence of transformations of the array: $$$[5, -2, 0, 1, -3] \to [5, -2, X, 1, -3] \to [X, -10, X, 1, -3] \to$$$ $$$[X, X, X, -10, -3] \to [X, X, X, X, 30]$$$. Thus, the maximum answer is $$$30$$$. Note, that other sequences that lead to the answer $$$30$$$ are also correct.The second example has, for example, the following sequence of transformations of the array: $$$[5, 2, 0, 4, 0] \to [5, 2, X, 4, 0] \to [5, 2, X, 4, X] \to [X, 10, X, 4, X] \to$$$ $$$[X, X, X, 40, X]$$$. The following answer is also allowed: 1 5 31 4 21 2 12 3Then the sequence of transformations of the array will look like this: $$$[5, 2, 0, 4, 0] \to [5, 2, 0, 4, X] \to [5, 8, 0, X, X] \to [40, X, 0, X, X] \to$$$ $$$[40, X, X, X, X]$$$.The third example can have the following sequence of transformations of the array: $$$[2, -1] \to [2, X]$$$.The fourth example can have the following sequence of transformations of the array: $$$[0, -10, 0, 0] \to [X, 0, 0, 0] \to [X, X, 0, 0] \to [X, X, X, 0]$$$.The fifth example can have the following sequence of transformations of the array: $$$[0, 0, 0, 0] \to [X, 0, 0, 0] \to [X, X, 0, 0] \to [X, X, X, 0]$$$.

import Control.Applicative
import Data.List
import Text.Printf
import Data.Ratio
import Data.Array.IO.Safe
import Control.Monad
import Data.Int
import Data.Maybe
import qualified Data.ByteString.Char8 as BS

readIntBS = fst . fromJust . BS.readInt

main = do
  n <- readLn :: IO Int
  as <- map readIntBS . BS.words <$> BS.getLine :: IO [Int]

  let
    countNeg = length . filter (<0) $ as
    countZero = length . filter (==0) $ as
    countPos = length . filter (>0) $ as

    positives = map snd . filter ((>0) . fst) $ zip as ([1..] :: [Int])
    negatives = map snd . filter ((<0) . fst) $ zip as ([1..] :: [Int])
    zeros = map snd . filter ((==0) . fst) $ zip as ([1..] :: [Int])
    maxneg = maximum $ filter (<0) as
    maxnegpos = if null negatives then Nothing else fmap (+1) (elemIndex maxneg as)

  if countZero == 0 && countNeg == 0 then do
    forM_ (f $ positives) $ \(a,b) -> printf "1 %d %d\n" a b

    else if odd countNeg then do
    forM_ (f $ reverse $ (fromJust maxnegpos) : zeros) $ \(a,b) -> printf "1 %d %d\n" a b
    unless (countZero == n-1 && countNeg == 1) $ printf "2 %d\n" (fromJust maxnegpos)
    forM_ (f $ positives ++ (delete (fromJust maxnegpos) negatives)) $ \(a,b) -> printf "1 %d %d\n" a b

    else do
    forM_ (f $ zeros) $ \(a,b) -> printf "1 %d %d\n" a b
    unless (countZero == 0 || countZero == n) $ printf "2 %d\n" (last zeros)
    forM_ (f $ positives ++ negatives) $ \(a,b) -> printf "1 %d %d\n" a b

f xs = zip xs (tail xs)

import Control.Applicative
import Data.List
import Text.Printf
import Data.Ratio
import Data.Array.IO.Safe
import Control.Monad
import Data.Int
import Data.Maybe
import qualified Data.ByteString.Char8 as BS

readIntBS = fst . fromJust . BS.readInt

main = do
  n <- readLn :: IO Int
  as <- map readIntBS . BS.words <$> BS.getLine :: IO [Int]

  let
    countNeg = length . filter (<0) $ as
    countZero = length . filter (==0) $ as
    countPos = length . filter (>0) $ as

    positives = map snd . filter ((>0) . fst) $ zip as ([1..] :: [Int])
    negatives = map snd . filter ((<0) . fst) $ zip as ([1..] :: [Int])
    zeros = map snd . filter ((==0) . fst) $ zip as ([1..] :: [Int])
    maxneg = maximum $ filter (<0) as
    maxnegpos = if null negatives then Nothing else fmap (+1) (elemIndex maxneg as)

  if countZero == 0 && countNeg == 0 then do
    forM_ (f $ positives) $ \(a,b) -> printf "1 %d %d\n" a b

    else if odd countNeg then do
    forM_ (f $ reverse $ (fromJust maxnegpos) : zeros) $ \(a,b) -> printf "1 %d %d\n" a b
    when (countPos > 0) $ do
      printf "2 %d\n" (fromJust maxnegpos)
      forM_ (f $ positives ++ (delete (fromJust maxnegpos) negatives)) $ \(a,b) -> printf "1 %d %d\n" a b

    else do
    forM_ (f $ zeros) $ \(a,b) -> printf "1 %d %d\n" a b
    when ((countPos > 0 || countNeg > 0) && countZero > 0) $ printf "2 %d\n" (last zeros)
    forM_ (f $ positives ++ negatives) $ \(a,b) -> printf "1 %d %d\n" a b

f xs = zip xs (tail xs)

import Control.Applicative
import Data.List
import Text.Printf
import Data.Ratio
import Data.Array.IO.Safe
import Control.Monad
import Data.Int
import Data.Maybe
import qualified Data.ByteString.Char8 as BS

readIntBS = fst . fromJust . BS.readInt

main = do
  n <- readLn :: IO Int
  as <- map readIntBS . BS.words <$> BS.getLine :: IO [Int]

  let
    countNeg = length . filter (<0) $ as
    countZero = length . filter (==0) $ as
    countPos = length . filter (>0) $ as

    positives = map snd . filter ((>0) . fst) $ zip as ([1..] :: [Int])
    negatives = map snd . filter ((<0) . fst) $ zip as ([1..] :: [Int])
    zeros = map snd . filter ((==0) . fst) $ zip as ([1..] :: [Int])
    maxneg = maximum $ filter (<0) as
    maxnegpos = if null negatives then Nothing else fmap (+1) (elemIndex maxneg as)

  if countZero == 0 && countNeg == 0 then do
    forM_ (f $ positives) $ \(a,b) -> printf "1 %d %d\n" a b

    else if odd countNeg then do
    forM_ (f $ (fromJust maxnegpos) : zeros) $ \(a,b) -> printf "1 %d %d\n" a b
    when (countPos > 0) $ do
      printf "2 %d\n" (fromJust maxnegpos)
      forM_ (f $ positives ++ (delete (fromJust maxnegpos) negatives)) $ \(a,b) -> printf "1 %d %d\n" a b

    else do
    forM_ (f $ zeros) $ \(a,b) -> printf "1 %d %d\n" a b
    when ((countPos > 0 || countNeg > 0) && countZero > 0) $ printf "2 %d\n" (last zeros)
    forM_ (f $ positives ++ negatives) $ \(a,b) -> printf "1 %d %d\n" a b

f xs = zip xs (tail xs)

import Control.Applicative
import Data.List
import Text.Printf
import Data.Ratio
import Data.Array.IO.Safe
import Control.Monad
import Data.Int
import Data.Maybe
import qualified Data.ByteString.Char8 as BS

readIntBS = fst . fromJust . BS.readInt

main = do
  n <- readLn :: IO Int
  as <- map readIntBS . BS.words <$> BS.getLine :: IO [Int]

  let
    countNeg = length . filter (<0) $ as
    countZero = length . filter (==0) $ as
    countPos = length . filter (>0) $ as

    positives = map snd . filter ((>0) . fst) $ zip as ([1..] :: [Int])
    negatives = map snd . filter ((<0) . fst) $ zip as ([1..] :: [Int])
    zeros = map snd . filter ((==0) . fst) $ zip as ([1..] :: [Int])
    maxneg = maximum $ filter (<0) as
    maxnegpos = if null negatives then Nothing else fmap (+1) (elemIndex maxneg as)

  if countZero > 0 && odd countNeg then do
    forM_ (f $ positives ++ negatives ++ zeros) $ \(a,b) -> printf "1 %d %d\n" a b

    else if odd countNeg then do
    printf "2 %d\n" (fromJust maxnegpos)
    forM_ (f $ positives ++ (delete (fromJust maxnegpos) negatives)) $ \(a,b) -> printf "1 %d %d\n" a b

    else if even countNeg then do
    forM_ (f $ zeros) $ \(a,b) -> printf "1 %d %d\n" a b
    when ((countPos > 0 || countNeg > 0) && countZero > 0) $ printf "2 %d\n" (last zeros)
    forM_ (f $ positives ++ negatives) $ \(a,b) -> printf "1 %d %d\n" a b

    else
    return ()

f xs = zip xs (tail xs)

import Control.Applicative
import Data.List
import Text.Printf
import Data.Ratio
import Data.Array.IO.Safe
import Control.Monad
import Data.Int
import Data.Maybe
import qualified Data.ByteString.Char8 as BS

readIntBS = fst . fromJust . BS.readInt

main = do
  n <- readLn :: IO Int
  as <- map readIntBS . BS.words <$> BS.getLine :: IO [Int]

  let
    countNeg = length . filter (<0) $ as
    countZero = length . filter (==0) $ as

    positives = map snd . filter ((>0) . fst) $ zip as ([1..] :: [Int])
    negatives = map snd . filter ((<0) . fst) $ zip as ([1..] :: [Int])
    zeros = map snd . filter ((==0) . fst) $ zip as ([1..] :: [Int])
    maxneg = maximum $ filter (<0) as
    maxnegpos = if null negatives then Nothing else fmap (+1) (elemIndex maxneg as)

  if countZero > 0 && odd countNeg then do
    forM_ (f $ positives ++ negatives ++ zeros) $ \(a,b) -> printf "1 %d %d\n" a b

    else if odd countNeg then do
    printf "2 %d\n" (fromJust maxnegpos)
    forM_ (f $ positives ++ (delete (fromJust maxnegpos) negatives)) $ \(a,b) -> printf "1 %d %d\n" a b

    else if even countNeg then do
    forM_ (f $ zeros) $ \(a,b) -> printf "1 %d %d\n" a b
    when ((not (null positives) || not (null negatives)) && countZero > 0) $ printf "2 %d\n" (last zeros)
    forM_ (f $ positives ++ negatives) $ \(a,b) -> printf "1 %d %d\n" a b

    else
    return ()

f xs = zip xs (tail xs)


You are given two segments $$$[l_1; r_1]$$$ and $$$[l_2; r_2]$$$ on the $$$x$$$-axis. It is guaranteed that $$$l_1 < r_1$$$ and $$$l_2 < r_2$$$. Segments may intersect, overlap or even coincide with each other.    The example of two segments on the $$$x$$$-axis. Your problem is to find two integers $$$a$$$ and $$$b$$$ such that $$$l_1 \le a \le r_1$$$, $$$l_2 \le b \le r_2$$$ and $$$a \ne b$$$. In other words, you have to choose two distinct integer points in such a way that the first point belongs to the segment $$$[l_1; r_1]$$$ and the second one belongs to the segment $$$[l_2; r_2]$$$.It is guaranteed that the answer exists. If there are multiple answers, you can print any of them.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Each of the next $$$q$$$ lines contains four integers $$$l_{1_i}, r_{1_i}, l_{2_i}$$$ and $$$r_{2_i}$$$ ($$$1 \le l_{1_i}, r_{1_i}, l_{2_i}, r_{2_i} \le 10^9, l_{1_i} < r_{1_i}, l_{2_i} < r_{2_i}$$$) — the ends of the segments in the $$$i$$$-th query.

Print $$$2q$$$ integers. For the $$$i$$$-th query print two integers $$$a_i$$$ and $$$b_i$$$ — such numbers that $$$l_{1_i} \le a_i \le r_{1_i}$$$, $$$l_{2_i} \le b_i \le r_{2_i}$$$ and $$$a_i \ne b_i$$$. Queries are numbered in order of the input. It is guaranteed that the answer exists. If there are multiple answers, you can print any.

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

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

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


A permutation — is a sequence of length $$$n$$$ integers from $$$1$$$ to $$$n$$$, in which all the numbers occur exactly once. For example, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ — permutations, and $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ — no.Polycarp was recently gifted a permutation $$$a[1 \dots n]$$$ of length $$$n$$$. Polycarp likes trees more than permutations, so he wants to transform permutation $$$a$$$ into a rooted binary tree. He transforms an array of different integers into a tree as follows:   the maximum element of the array becomes the root of the tree;  all elements to the left of the maximum — form a left subtree (which is built according to the same rules but applied to the left part of the array), but if there are no elements to the left of the maximum, then the root has no left child;  all elements to the right of the maximum — form a right subtree (which is built according to the same rules but applied to the right side of the array), but if there are no elements to the right of the maximum, then the root has no right child. For example, if he builds a tree by permutation $$$a=[3, 5, 2, 1, 4]$$$, then the root will be the element $$$a_2=5$$$, and the left subtree will be the tree that will be built for the subarray $$$a[1 \dots 1] = [3]$$$, and the right one — for the subarray $$$a[3 \dots 5] = [2, 1, 4]$$$. As a result, the following tree will be built:     The tree corresponding to the permutation $$$a=[3, 5, 2, 1, 4]$$$. Another example: let the permutation be $$$a=[1, 3, 2, 7, 5, 6, 4]$$$. In this case, the tree looks like this:     The tree corresponding to the permutation $$$a=[1, 3, 2, 7, 5, 6, 4]$$$. Let us denote by $$$d_v$$$ the depth of the vertex $$$a_v$$$, that is, the number of edges on the path from the root to the vertex numbered $$$a_v$$$. Note that the root depth is zero. Given the permutation $$$a$$$, for each vertex, find the value of $$$d_v$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the permutation. This is followed by $$$n$$$ numbers $$$a_1, a_2, \ldots, a_n$$$ — permutation $$$a$$$.

For each test case, output $$$n$$$ values — $$$d_1, d_2, \ldots, d_n$$$.

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

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

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

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

    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