import qualified Data.ByteString.Char8 as B
import           Data.Functor
import           Data.List
import           Data.Maybe
import qualified Data.Set              as S

getInts :: IO [Int]
getInts = map (fst . fromJust . B.readInt) <$> B.words <$> B.getContents
getIntegers :: IO [Integer]
getIntegers = map (fst . fromJust . B.readInteger) <$> B.words <$> B.getContents
pair []       = []
pair (x:y:rs) = (x, y) : pair rs
clamp u v w = max u $ min v $ w

main = do
    _:xs <- getIntegers
    putStrLn $ if solve xs then "YES" else "NO"

solve xs = mod s 2 == 0 && (res1 || res2) where
    s = sum xs
    want = - div s 2
    res1 = go xs want S.empty
    res2 = go (reverse xs) want S.empty
    go [] want s     = S.member want s
    go (x:xs) want s = S.member want s || go xs (want+x) (S.insert x s)

--- 20:36 - 20:40
import qualified Data.ByteString.Char8 as B
import           Data.Functor
import           Data.List
import           Data.Maybe
import qualified Data.Set              as S

getInts :: IO [Int]
getInts = map (fst . fromJust . B.readInt) <$> B.words <$> B.getContents
getIntegers :: IO [Integer]
getIntegers = map (fst . fromJust . B.readInteger) <$> B.words <$> B.getContents
pair []       = []
pair (x:y:rs) = (x, y) : pair rs
clamp u v w = max u $ min v $ w

main = do
    _:xs <- getIntegers
    s <- return $ sum xs
    if mod s 2 == 0 && (solve xs (-div s 2) S.empty
                         || solve (reverse xs) (-div s 2) S.empty)
        then putStrLn "YES"
        else putStrLn "NO"

solve [] want s     = S.member want s
solve (x:xs) want s = S.member want s || solve xs (want+x) (S.insert x s)

{-# LANGUAGE FlexibleContexts #-}
import Data.Int
import Data.List
import Data.Array
import qualified Data.ByteString.Char8 as BS
readInt s = let Just (a,_) = BS.readInt s in a

main = BS.interact $ BS.pack . out . solve . map (fromIntegral . readInt) . tail . BS.words

out True = "YES"
out _ = "NO"

solve :: [Int64] -> Bool
solve ns = (solveleft ns) || (solveleft $ reverse ns)

solveleft ns = or $ map (\(a, i) -> checkl a i psum) $ ns `zip` [1..]
    where len = length ns
          psum = listArray (1, len) $
            head ns : [ psum ! (i - 1) + a | (a, i) <- (tail ns) `zip` [2..]]

checkl balance i psum = diff (check_ i $ ir + 1) == 0
  where (il, ir) = bounds psum
        check_ l r
          | r - l <= 1 = l
          | diff mid >= 0 = check_ mid r
          | otherwise = check_ l mid
          where mid = (l + r) `div` 2
        diff mid = (psum ! ir) - 2 * (psum ! mid) + 2 * balance

{-# OPTIONS_GHC -O3 #-}
{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}

import qualified Data.ByteString as B (ByteString, getLine)
import qualified Data.ByteString.Char8 as C (readInt, words)
import qualified Data.Maybe as M (fromJust)
import qualified Data.Int as I (Int64)
import qualified Data.Map.Strict as MP (fromList, Map, alter, member, empty)

readInt :: B.ByteString -> I.Int64
readInt = fromIntegral . fst . M.fromJust . C.readInt

data MultiSet a = MS (MP.Map a Int)
empty = MS (MP.empty)
fromList xs | xs == [] = empty | otherwise = let x:xr = xs in insert x (fromList xr)
member x (MS m) = MP.member x m
insert x (MS m) = MS (MP.alter msucc x m) where
    msucc Nothing = Just 1
    msucc (Just x) = Just (x + 1)
delete x (MS m) = MS (MP.alter mpred x m) where
    mpred (Just 1) = Nothing
    mpred (Just x) = Just (x - 1)

run _ _ _ _ [] = "NO"
run sl sr tl tr (r:rs) | sl == sr = "YES"
    | sl > sr && even (sl - sr) && ((sl - sr) `div` 2) `member` tl = "YES"
    | sl < sr && even (sr - sl) && ((sr - sl) `div` 2) `member` tr = "YES"
    | otherwise = run (sl + r) (sr - r) (r `insert` tl) (r `delete` tr) rs
runx xs = run 0 (sum xs) empty (fromList xs) xs

main = B.getLine >> B.getLine >>= putStrLn . runx . map readInt . C.words

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import qualified Data.Map.Lazy as M
import Data.Int

main = do
  n <- fmap readInt B.getLine
  xs <- fmap readInts B.getLine
  putStrLn $ if solve n xs then "YES" else "NO"

solve n xs
  | r /= 0 = False
  | otherwise = (any (\(i, s) -> s == hs || maybe False (> i) (M.lookup (hs - s) m)) $ zip [1..] $ scanl1 (+) xs')
             || (any (\(i, s) -> maybe False (< i) $ M.lookup (hs - s) mr) $ zip [n + 2, n + 1..] $ scanl1 (+) $ reverse xs')
  where
    xs' = 0:xs ++ [0]
    m = M.fromListWith max $ zip xs' [(1 :: Int64)..]
    mr = M.fromListWith min $ zip xs' [(1 :: Int64)..]
    (hs, r) = sum xs `quotRem` 2 :: (Int64, Int64)

readInt = maybe undefined (fromIntegral . fst) . B.readInteger
readInts = fmap readInt . B.words

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import qualified Data.Map.Strict as M
import Data.Int

main = do
  n <- fmap readInt B.getLine
  xs <- fmap readInts B.getLine
  putStrLn $ if solve n xs then "YES" else "NO"

solve n xs
  | r /= 0 = False
  | otherwise = (any (\(i, s) -> maybe False (> i) $ M.lookup (hs - s) m) $ zip [1..] $ scanl1 (+) xs')
             || (any (\(i, s) -> maybe False (< i) $ M.lookup (hs - s) mr) $ zip [n + 2, n + 1..] $ scanl1 (+) $ reverse xs')
  where
    xs' = 0:xs ++ [0]
    m = M.fromListWith max $ zip xs' [(1 :: Int64)..]
    mr = M.fromListWith min $ zip xs' [(1 :: Int64)..]
    (hs, r) = sum xs `quotRem` 2 :: (Int64, Int64)

readInt = maybe undefined (fromIntegral . fst) . B.readInteger
readInts = fmap readInt . B.words

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import qualified Data.Map.Strict as M
import Data.Int

main = do
  n <- fmap readInt B.getLine
  xs <- fmap readInts B.getLine
  putStrLn $ if solve n xs then "YES" else "NO"

solve n xs
  | r /= 0 = False
  | otherwise = (any (\(i, s) -> s == hs || maybe False (> i) (M.lookup (hs - s) m)) $ zip [1..] $ scanl1 (+) xs')
             || (any (\(i, s) -> maybe False (< i) $ M.lookup (hs - s) mr) $ zip [n + 2, n + 1..] $ scanl1 (+) $ reverse xs')
  where
    xs' = 0:xs ++ [0]
    m = M.fromListWith max $ zip xs' [(1 :: Int64)..]
    mr = M.fromListWith min $ zip xs' [(1 :: Int64)..]
    (hs, r) = sum xs `quotRem` 2 :: (Int64, Int64)

readInt = maybe undefined (fromIntegral . fst) . B.readInteger
readInts = fmap readInt . B.words

{-# LANGUAGE FlexibleContexts #-}
import Data.List
import Data.Array
import qualified Data.ByteString.Char8 as BS
readInt s = let Just (a,_) = BS.readInt s in a

main = BS.interact $ BS.pack . out . solve . map readInt . tail . BS.words

out True = "YES"
out _ = "NO"

solve ns = (solveleft ns) || (solveleft $ reverse ns)

solveleft ns = or $ map (\(a, i) -> checkl a i psum) $ ns `zip` [1..]
    where len = length ns
          psum = listArray (1, len) $
            head ns : [ psum ! (i - 1) + a | (a, i) <- (tail ns) `zip` [2..]]

checkl balance i psum = diff (check_ i $ ir + 1) == 0
  where (il, ir) = bounds psum
        check_ l r
          | r - l <= 1 = l
          | diff mid >= 0 = check_ mid r
          | otherwise = check_ l mid
          where mid = (l + r) `div` 2
        diff mid = (psum ! ir) - 2 * (psum ! mid) + 2 * balance

{-# OPTIONS_GHC -O3 #-}
{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}

import qualified Data.ByteString as B (ByteString, getLine)
import qualified Data.ByteString.Char8 as C (readInt, words)
import qualified Data.Maybe as M (fromJust)
import qualified Data.Int as I (Int64)
import qualified Data.Set as S (fromList, member, insert, delete, empty)

readInt :: B.ByteString -> I.Int64
readInt = fromIntegral . fst . M.fromJust . C.readInt

run _ _ _ _ [] = "NO"
run sl sr tl tr (r:rs) | sl == sr = "YES"
    | sl > sr && even (sl - sr) && ((sl - sr) `div` 2) `S.member` tl = "YES"
    | sl < sr && even (sr - sl) && ((sr - sl) `div` 2) `S.member` tr = "YES"
    | otherwise = run (sl + r) (sr - r) (r `S.insert` tl) (r `S.delete` tr) rs
runx xs = run 0 (sum xs) S.empty (S.fromList xs) xs

main = B.getLine >> B.getLine >>= putStrLn . runx . map readInt . C.words

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import qualified Data.Map.Lazy as M

main = do
  n <- fmap readInt B.getLine
  xs <- fmap readInts B.getLine
  putStrLn $ if solve n xs then "YES" else "NO"

solve n xs
  | r /= 0 = False
  | otherwise = any (\(i, s) -> maybe False (> i) $ M.lookup (hs - s) m) $ zip [1..] $ scanl1 (+) xs
  where
    m = M.fromList $ zip xs [1..]
    (hs, r) = sum xs `quotRem` 2

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import qualified Data.Map.Lazy as M
import Data.Int

main = do
  n <- fmap readInt B.getLine
  xs <- fmap readInts B.getLine
  putStrLn $ if solve n xs then "YES" else "NO"

solve n xs
  | r /= 0 = False
  | otherwise = (any (\(i, s) -> s == hs || maybe False (> i) (M.lookup (hs - s) m)) $ zip [1..] $ scanl1 (+) xs')
             || (any (\(i, s) -> maybe False (< i) $ M.lookup (hs - s) m) $ zip [n, n - 1..] $ scanl1 (+) $ reverse xs')
  where
    xs' = 0:xs ++ [0]
    m = M.fromList $ zip xs' [(1 :: Int64)..]
    (hs, r) = sum xs `quotRem` 2 :: (Int64, Int64)

readInt = maybe undefined (fromIntegral . fst) . B.readInteger
readInts = fmap readInt . B.words

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import qualified Data.Map.Lazy as M

main = do
  n <- fmap readInt B.getLine
  xs <- fmap readInts B.getLine
  putStrLn $ if solve n xs then "YES" else "NO"

solve n xs
  | r /= 0 = False
  | otherwise = (any (\(i, s) -> s == hs || maybe False (> i) (M.lookup (hs - s) m)) $ zip [1..] $ scanl1 (+) xs)
             || (any (\(i, s) -> maybe False (< i) $ M.lookup (hs - s) m) $ zip [n, n - 1..] $ scanl1 (+) $ reverse xs)
  where
    m = M.fromList $ zip xs [1..]
    (hs, r) = sum xs `quotRem` 2

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import qualified Data.Map.Lazy as M
import Data.Int

main = do
  n <- fmap readInt B.getLine
  xs <- fmap readInts B.getLine
  putStrLn $ if solve n xs then "YES" else "NO"

solve n xs
  | r /= 0 = False
  | otherwise = (any (\(i, s) -> s == hs || maybe False (> i) (M.lookup (hs - s) m)) $ zip [1..] $ scanl1 (+) xs)
             || (any (\(i, s) -> maybe False (< i) $ M.lookup (hs - s) m) $ zip [n, n - 1..] $ scanl1 (+) $ reverse xs)
  where
    m = M.fromList $ zip xs [(1 :: Int64)..]
    (hs, r) = sum xs `quotRem` 2 :: (Int64, Int64)

readInt = maybe undefined (fromIntegral . fst) . B.readInteger
readInts = fmap readInt . B.words

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import qualified Data.Map.Lazy as M

main = do
  n <- fmap readInt B.getLine
  xs <- fmap readInts B.getLine
  putStrLn $ if solve n xs then "YES" else "NO"

solve n xs
  | r /= 0 = False
  | otherwise = (any (\(i, s) -> maybe False (> i) $ M.lookup (hs - s) m) $ zip [1..] $ scanl1 (+) xs)
             || (any (\(i, s) -> maybe False (< i) $ M.lookup (hs - s) m) $ zip [n, n - 1..] $ scanl1 (+) $ reverse xs)
  where
    m = M.fromList $ zip xs [1..]
    (hs, r) = sum xs `quotRem` 2

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words


import           Control.Monad (replicateM_)

main = do
  q <- read <$> getLine :: IO Int
  replicateM_ q (readQuery >>= ((putStrLn . (\x -> if x then "YES" else "No")) . solve))

readQuery :: IO [Int]
readQuery = do
  n <- read <$> getLine :: IO Int
  map read . words <$> getLine :: IO [Int]

solve :: [Int] -> Bool
solve = findAmount 2048 1
  where
    findAmount required amount xs
      | length (filter (== required) xs) >= amount = True
      | required == 1 = False
      | otherwise = findAmount (required `div` 2) ((amount - length (filter (== required) xs)) * 2) xs

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

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

main = interact solve

solve input =
  let asnums :: [Int]
      asnums = map read $ words input
      (n:xs) = asnums
      testcases :: [[Int]]
      testcases = parseTestCases xs
      answers = map (boolToString.solve') testcases
      boolToString True = "YES"
      boolToString False = "NO"
  in intercalate "\n" answers

parseTestCases :: [Int] -> [[Int]]
parseTestCases [] = []
parseTestCases (n:xs) =
  let (here,next) = splitAt n xs
  in (here:parseTestCases next)

solve' :: [Int] -> Bool
solve' [] = False
solve' inp =
  let baseSet :: MS.Map Int Int
      baseSet = foldl addToMap (MS.empty) inp
      reducedSet = reduceSet baseSet
      addToMap :: MS.Map Int Int -> Int -> MS.Map Int Int
      addToMap map num = MS.insertWith (+) num 1 map
      answer = case (MS.keys reducedSet) of (2048:_) -> True
                                            _ -> False
  in answer

reduceSet :: MS.Map Int Int -> MS.Map Int Int
reduceSet inp
  | isEmpty = MS.empty
  | lowestKey == 2048 = inp
  | lowestCount == 1 = reduceSet $ MS.delete lowestKey inp
  | otherwise = reduceSet $ MS.delete lowestKey $ MS.insertWith (+) (lowestKey*2) (div lowestCount 2) inp
  where
    isEmpty = (MS.size inp) == 0
    lowestKey :: Int
    (lowestKey:_) = MS.keys inp
    lowestCount :: Int
    Just lowestCount = MS.lookup lowestKey inp

{-# OPTIONS_GHC -O3 #-}

import Control.Monad ( replicateM_ )

main = do
  n <- fmap read getLine
  replicateM_ n $ do
    getLine
    s <- fmap (filter (<= 2048) . fmap read . words) getLine
    putStrLn $ if sum s >= 2048 then "yes" else "no"

import           Control.Monad (replicateM_)

main = do
  q <- read <$> getLine :: IO Int
  replicateM_ q (readQuery >>= ((print . (\x -> if x then "YES" else "No")) . solve))

readQuery :: IO [Int]
readQuery = do
  n <- read <$> getLine :: IO Int
  map read . words <$> getLine :: IO [Int]

solve :: [Int] -> Bool
solve = findAmount 2048 1
  where
    findAmount required amount xs
      | length (filter (== required) xs) >= amount = True
      | required == 1 = False
      | otherwise = findAmount (required `div` 2) ((amount - length (filter (== required) xs)) * 2) xs


-- 840A

import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.Binary.Builder as BU
import Data.Maybe (fromJust)
import Control.Monad (forM_)
import Data.List (sortBy)
import Data.Array.ST.Safe
import Data.Array.IArray

main = B.getContents >>= output . program . input
    where input = (map . map) (fst . fromJust . B.readInt)
                . map B.words
                . B.lines
          output = putStrLn . unwords . map show

program :: [[Int]] -> [Int]
program ([n]:a:b:_) = buildArray n $ zip bIndices aSorted
    where aSorted = sortBy (flip compare) a
          bIndices = map fst $
            sortBy (\x y -> compare (snd x) (snd y)) $
              zip ([1..] :: [Int]) b

buildArray :: Int -> [(Int, Int)] -> [Int]
buildArray n pairs = elems $ runSTUArray $ do
  arr <- newArray (1, n) 0
  forM_ pairs $ \(i, v) ->
    writeArray arr i v
  return arr

{-# OPTIONS_GHC -O3 #-}
{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}

import qualified Data.ByteString as B (getLine)
import qualified Data.ByteString.Char8 as C (readInt, words)
import qualified Data.Maybe as M (fromJust)
import qualified Data.List as L (sort, sortBy, intercalate)

readInt = fst . M.fromJust . C.readInt

main = do
    (readInt -> n) <- B.getLine
    (map readInt . C.words -> as) <- B.getLine
    (map readInt . C.words -> bs) <- B.getLine
    let bss = L.sortBy (\a b -> compare (snd a) (snd b)) (zip [1..] bs)
        ass = reverse $ L.sort as
        css = map (\(a, (b, c)) -> (a, b)) (zip ass bss)
        dss = map fst $ L.sortBy (\a b -> compare (snd a) (snd b)) css
    putStrLn $ L.intercalate " " $ map show dss

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.List
import Data.Function
import Data.Array.Unboxed

main = B.getContents >>= putStr . unwords . map show . evalState app . B.words

app = do
  n <- poi
  as <- replicateM n poi
  bs <- replicateM n poi
  return $ solve n as bs
  where
    pop = state $ \(x:xs) -> (x, xs)
    poi = fmap int pop
    int = maybe undefined fst . B.readInt

solve n as bs = (elems :: UArray Int Int -> [Int]) $ array (1, n) $ flip zip (sortBy (flip compare) as) $ map fst $ sortBy (compare `on` snd) $ zip [1..] bs

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.List
import Data.Function
import Data.Array.Unboxed

main = B.getContents >>= B.putStr . B.unwords . map (B.pack . show) . evalState app . B.words

app = do
  n <- poi
  as <- replicateM n poi
  bs <- replicateM n poi
  return $ solve n as bs
  where
    pop = state $ \(x:xs) -> (x, xs)
    poi = fmap int pop
    int = maybe undefined fst . B.readInt

solve n as bs = (elems :: UArray Int Int -> [Int]) $ array (1, n) $ flip zip (sortBy (flip compare) as) $ map fst $ sortBy (compare `on` snd) $ zip [1..] bs

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.List
import Data.Function
import Data.Array.Unboxed

main = B.getContents >>= mapM_ print . evalState app . B.words

app = do
  n <- poi
  as <- replicateM n poi
  bs <- replicateM n poi
  return $ solve n as bs
  where
    pop = state $ \(x:xs) -> (x, xs)
    poi = fmap int pop
    int = maybe undefined fst . B.readInt

solve n as bs = (elems :: UArray Int Int -> [Int]) $ array (1, n) $ flip zip (sortBy (flip compare) as) $ map fst $ sortBy (compare `on` snd) $ zip [1..] bs


import Control.Monad

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    n <- getLine
    as <- words <$> getLine
    putStrLn $ unwords $ reverse $ as

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

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

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

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

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

main = readInt >>= flip replicateM solve

solve = getLine >> readInts >>= printList . reverse

{-# LANGUAGE OverloadedStrings #-}
import Control.Monad
import Control.Applicative
import Data.Maybe
import Data.Functor
import Data.Array.Unboxed as UA
import qualified Data.ByteString.Char8 as B8
import Text.Printf

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

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    forM_ [1..t] $ \_ -> do
        n <- B8.getLine <&> readIntB8
        ps <- B8.getLine <&> B8.words <&> map readIntB8
        let answer = reverse ps
        forM_ answer $ printf "%d "
        printf "\n"


isp n = and $ map ((/=0) . (mod n)) $ takeWhile ((<=n) . (^2)) [2 ..]

gao 0 = []
gao n = gao (p - 1) ++ [n + p - i | i <- [p .. n]] where
	p = until (isp . (+n)) succ 1

main = do getLine >>= putStr . unwords . map show . gao . read

main = do getLine >>= putStr . unwords . map show . (\n -> n:[1..n-1]) . read

import Monad
import List

main = readLn >>= putStrLn.unwords.map show.solve

solve n = [2..n] ++ [1]

main :: IO ()
main = do
    n <- read <$> getLine
    putStrLn . unwords . map show $ n:[1..n-1]

import Control.Applicative

solve n | even n = concatMap (\x->[x+1, x]) [1,3..]
        | otherwise = 1 : (concatMap (\x->[x, x-1])) [3, 5..]

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

import Control.Monad
main = do
n<-getLine>>=return.read
if odd n then do{putStr"1 ";m[2,4..n-1]} else m[1,3..n-1] where m = mapM (\x->putStr(show(x+1)++" "++show x++" "))

import Prelude
import List
import Char

main = interact q

q = func.(read::String->Int)

func::Int->String
func a = solve [1..a]

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

maximum' [] = 0
maximum' a  = maximum a

solve::[Int]->String
solve a = showStr ((tail a) ++ [b])
    where
      b = head a

showStr::[Int]->String
showStr = init. foldr (\a b->(show a)++(' ':b)) ""

main = do
  n <- readLn
  putStrLn $ unwords $ map show [1..n]


{-# OPTIONS_GHC -XStrict -XStrictData #-}
{-# LANGUAGE FlexibleContexts #-}
import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST
import Data.Array.Unboxed
import Data.Bifunctor
import Data.Bits
import Data.Bool
import Data.Char
import Data.Int
import Data.List
import Data.Maybe
import Data.Ord
import Data.Ratio
import Data.Tuple
import qualified Data.IntSet as IS
import qualified Data.Set as Set
import qualified Data.Sequence as Seq
import Data.STRef.Strict
import System.IO
import System.IO.Unsafe

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

deb name s e = seq s unsafePerformIO $! do
    hPutStrLn stderr $ " " ++ name ++ " = " ++ show s
    return e

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

modifyArray f a i = readArray a i >>= \v -> writeArray a i (f v)

solve :: Int64 -> [Int64] -> Int64
solve n xs =
    let ws = [i*(n-i) | i <- [1..n-1]]
        ys = zipWith (-) xs (drop 1 xs)
    in
        sum $ zipWith (\w y -> (w-1)*y) ws ys

main = do
    tn <- parseInt <$> BS.getLine
    replicateM_ tn $ do
        n <- fromIntegral . parseInt <$> BS.getLine
        xs <- map (fromIntegral . parseInt) . BS.words <$> BS.getLine
        print $ solve n (sort xs)

--
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}

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

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

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

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

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

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

-- import Debug.Trace (trace, traceM, traceShowM)
-- debug = flip trace

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
solve n ds = solve' 1 0 0 . tail . sort $ ds
    where
        solve' :: Int64 -> Int64 -> Int64 -> [Int64] -> Int64
        solve' _ _ _ [] = 0
        solve' kDs sDs lDs ds@(d:pDs) = (d - lDs) - kDs * d + sDs + solve' (succ kDs) (sDs + d) d pDs

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

import Control.Monad ( replicateM_ )
import Data.Int ( Int64 )
import Data.List ( sort, tails, zipWith4 )

solve :: IO()
solve = do
    n <- readInt <$> getLine
    as <- sort . map readInt64 . words <$> getLine
    let calc i ai alast slast = slast + (ai - alast) * fromIntegral i
        dp = 0 : zipWith4 calc [1..] (tail as) as dp
    print $ as !! (n - 1) - sum dp

readInt :: String -> Int
readInt = read

readInt64 :: String -> Int64
readInt64 = read

main :: IO()
main = do
    t <- readInt <$> getLine
    replicateM_ t solve

--
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}

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

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

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

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

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

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

-- import Debug.Trace (trace, traceM, traceShowM)
-- debug = flip trace

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
solve n ds = solve' 1 0 0 $ tail ds
    where
        solve' :: Int64 -> Int64 -> Int64 -> [Int64] -> Int64
        solve' _ _ _ [] = 0
        solve' kDs sDs lDs ds@(d:pDs) = (d - lDs) - kDs * d + sDs + solve' (succ kDs) (sDs + d) d pDs

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


{-# LANGUAGE TypeApplications #-}
main = interact $ unlines . map (show . solve . read @Integer) . tail . lines
solve n = go n 0 where
  go 1 a = a
  go n a | (q,0) <- n `divMod` 5 = go q $! a+3
         | (q,0) <- n `divMod` 3 = go q $! a+2
         | (q,0) <- n `divMod` 2 = go q $! a+1
         | otherwise = -1

-- https://github.com/minoki/my-atcoder-solutions
{-# LANGUAGE BangPatterns #-}
import Data.Int
import Control.Monad

solve :: Int64 -> Int
solve 0 = error "invalid input"
solve n = let (e2, n') = factorMultiplicity 2 n
              (e3, n'') = factorMultiplicity 3 n'
              (e5, n''') = factorMultiplicity 5 n''
          in if n''' == 1
             then e2 + 2 * e3 + 3 * e5
             else -1
  where
    factorMultiplicity :: Int64 -> Int64 -> (Int, Int64)
    factorMultiplicity !p = loop 0
      where loop !k !n = case n `quotRem` p of
                           (q,0) -> loop (k + 1) q
                           _ -> (k, n)

main = do
  q <- readLn
  replicateM_ q (solve <$> readLn >>= print)

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

process n a | a==1 = n
            | mod a 5 ==0 = process (n+1) (div (a*4) 5)
	    | mod a 3 ==0 = process (n+1) (div (a*2) 3)
	    | mod a 2 ==0 = process (n+1) (div a 2)
	    | otherwise = -1

process1 = do
		a<- read <$> getLine ::IO Integer
		print $ process 0 a

main = do
		n<-read <$> getLine ::IO Int
		replicateM_ n process1

countFactor :: Integer -> Integer -> (Integer, Integer)
countFactor d n = (fromIntegral (length c),n')
    where (c,n':_) = span ((==0).(`mod` d)) $ iterate (`div` d) n

--process :: Integer -> Integer
process n
    | n' == 1 = sum $ zipWith (*) [1,2,3] $ fst $ unzip xs
    | otherwise = -1
    where
        xs@((_,n'):_) = scanr f (0,n) [2,3,5]
        f = \x (_,t) -> countFactor x t

readInt :: String -> Integer
readInt = read

main :: IO ()
main = do
    q <- fmap readInt getLine
    ns <- fmap (map readInt.words) getContents
    mapM_ print $ map process ns

subN' :: Integer -> Int -> Int
subN' x c
    | x == 1 = c
    | mod x 5 == 0 = subN' (div (x*4) 5) (c+1)
    | mod x 3 == 0 = subN' (div (x*2) 3) (c+1)
    | mod x 2 == 0 = subN' (div x 2) (c+1)
    | otherwise = -1

subN :: Integer -> Int
subN x = subN' x 0

solve :: [Integer] -> [Int]
solve xs = map subN xs

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

subN' :: Integer -> Int -> Int
subN' x c
    | x == 1 = c
    | mod x 5 == 0 = subN' (div (x*4) 5) (c+1)
    | mod x 3 == 0 = subN' (div (x*2) 3) (c+1)
    | mod x 2 == 0 = subN' (div x 2) (c+1)
    | otherwise = -1

subN :: Integer -> Int
subN x = subN' x 0

solve :: [Integer] -> [Int]
solve xs = map subN xs

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


import Data.List
import Data.Array
import Data.Maybe
import qualified Data.Map.Strict as M

main = do
    n <- read `fmap` getLine :: IO Int
    flats <- getLine
    let flatAry = listArray (1, length flats) flats
    let numPoke = (length . group . sort) flats
    print $ solve numPoke flatAry

type Book = M.Map Char Int
type Solution = (Book, Int, Int) -- (currSet, beginIx, endIx)

solve numPoke flats = f (M.empty, 1, 1) 100000 where
    f :: Solution -> Int -> Int
    f curr best = case walk numPoke flats curr of
        Nothing -> best
        Just next -> f (removeHead next flats) (min best (cost next))
    cost (_, b, e) = e - b

removeHead (book, b, e) flats = (book', b+1, e) where
    x = flats ! b
    book' = if book M.! x == 1 then M.delete x book else M.adjust (\y->y-1) x book

walk :: Int -> Array Int Char -> Solution -> Maybe Solution
walk num flats (book, b, e) = f book e where
    (ary1, aryN) = bounds flats
    len = aryN - ary1 + 1
    f book e
        | e > len && M.size book >= num = Just (book, b, e)
        | e > len && M.size book < num = Nothing
        | M.size book == num = Just (book, b, e)
        | otherwise = f (M.insertWith (+) (flats ! e) 1 book) (e + 1)

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

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

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

main = do
  getLine
  s <- getLine

  let m = length $ filter (/= 0) $ elems $ accumArray (+) 0 (chr 0, chr 127) $ zip s (repeat 1)

  cs :: IOUArray Char Int <- newArray (chr 0, chr 127) 0

  let
    scan0 :: String -> Int -> Int -> IO (String, Int)
    scan0 s d k
      | k == m = return (s, d)
      | otherwise = do
        v <- readArray cs c
        writeArray cs c (v+1)
        scan0 (tail s) (d+1) (if v == 0 then k + 1 else k)
      where c = head s

  (r0, d0) <- scan0 s 0 0

  let
    scan :: String -> String -> Int -> Int -> IO Int
    scan l r d m = do
        cnt <- readArray cs c
        writeArray cs c (cnt-1)

        if cnt == 1
          then
            if null r2
               then return m
               else do
                 mapM (\c -> readArray cs c >>= \v -> writeArray cs c (v+1)) $ c:r1
                 scan l' r' d' $ min d' m
          else scan l' r (d-1) $ min (d-1) m
      where
        (c, l') = (head l, tail l)
        (r1, r2) = span (/= c) r
        r' = tail r2
        d' = d + length r1

  m <- scan s r0 d0 d0

  print m

import Data.List

main = do
    n <- read `fmap` getLine :: IO Int
    str <- getLine
    let numPoke = (length . group . sort) str
    print $ minimum [minStep n numPoke (drop i str) | i <- [0..n-numPoke+1]]

minStep n nPoke ps = f ps [] 0 where
    f [] qs step = n
    f (p:ps) qs step
        | length qs == nPoke = step
        | otherwise = f ps qs' (step+1)
        where qs' = if p `elem` qs then qs else (p:qs)

import Data.List

main = do
    n <- read `fmap` getLine :: IO Int
    str <- getLine
    let numPoke = (length . group . sort) str
    print $ minimum [minStep numPoke (drop i str) | i <- [0..n-numPoke]]

minStep nPoke ps = f ps [] 0 where
    f [] qs step = step
    f (p:ps) qs step
        | length qs == nPoke = step
        | otherwise = f ps qs' (step+1)
        where qs' = if p `elem` qs then qs else (p:qs)

import Data.List

main = do
    n <- read `fmap` getLine :: IO Int
    str <- getLine
    let numPoke = (length . group . sort) str
    print $ minimum [minStep numPoke (drop i str) | i <- [0..n-numPoke+1]]

minStep n ps = f ps [] 0 where
    f [] qs step = n + 1
    f (p:ps) qs step
        | length qs == n = step
        | otherwise = f ps qs' (step+1)
        where qs' = if p `elem` qs then qs else (p:qs)

import Data.List

main = do
    n <- read `fmap` getLine :: IO Int
    str <- getLine
    let numPoke = (length . group . sort) str
    print $ minimum [minStep numPoke (drop i str) | i <- [0..n-numPoke+1]]

minStep n ps = f ps [] 0 where
    f [] qs step = n
    f (p:ps) qs step
        | length qs == n = step
        | otherwise = f ps qs' (step+1)
        where qs' = if p `elem` qs then qs else (p:qs)

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

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

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

main = do
  getLine
  s <- getLine

  let m = length $ filter (/= 0) $ elems $ accumArray (+) 0 (chr 0, chr 127) $ zip s (repeat 1)

  cs :: IOUArray Char Int <- newArray (chr 0, chr 127) 0

  let
    scan0 :: String -> Int -> Int -> IO (String, Int)
    scan0 s d k
      | k == m = return (s, d)
      | otherwise = do
        v <- readArray cs c
        writeArray cs c (v+1)
        scan0 (tail s) (d+1) (if v == 0 then k + 1 else k)
      where c = head s

  (r0, d0) <- scan0 s 0 0

  let
    scan :: String -> String -> Int -> Int -> IO Int
    scan _ [] _ m = return m
    scan l r d m = do
        cnt <- readArray cs c
        writeArray cs c (cnt-1)

        if cnt == 1
          then
            if null r2
               then return m
               else scan l' r' d' $ min d' m
          else scan l' r (d-1) $ min (d-1) m
      where
        (c, l') = (head l, tail l)
        (r1, r2) = span (/= c) r
        r' = tail r2
        d' = d + length r1

  m <- scan s r0 d0 d0

  print m

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

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

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

main = do
  getLine
  s <- getLine

  let m = length $ filter (/= 0) $ elems $ accumArray (+) 0 (chr 0, chr 127) $ zip s (repeat 1)

  cs :: IOUArray Char Int <- newArray (chr 0, chr 127) 0

  let
    scan0 :: String -> Int -> Int -> IO (String, Int)
    scan0 s d k
      | k == m = return (s, d)
      | otherwise = do
        v <- readArray cs c
        writeArray cs c (v+1)
        scan0 (tail s) (d+1) (if v == 0 then k + 1 else k)
      where c = head s

  (r0, d0) <- scan0 s 0 0
  print (r0, d0)

  let
    scan :: String -> String -> Int -> Int -> IO Int
    scan _ [] _ m = return m
    scan l r d m = do
        cnt <- readArray cs c
        writeArray cs c (cnt-1)

        if cnt == 1
          then
            if null r2
               then return m
               else scan l' r' d' $ min d' m
          else scan l' r (d-1) $ min (d-1) m
      where
        (c, l') = (head l, tail l)
        (r1, r2) = span (/= c) r
        r' = tail r2
        d' = d + length r1

  m <- scan s r0 d0 d0

  print m


import Control.Monad
import Data.List

comparator' :: Int -> String -> String -> Ordering
comparator' _ [] [] = EQ
comparator' 0 (a:as) (b:bs)
  | a<b = LT
  | a==b = comparator' 1 as bs
  | a>b = GT
comparator' 1 (a:as) (b:bs)
  | a<b = GT
  | a==b = comparator' 0 as bs
  | a>b = LT

comparator :: (String,Int) -> (String,Int) -> Ordering
comparator (s1,_) (s2,_) =
  comparator' 0 s1 s2

main = do
  line <- getLine
  let [n,m] = map read $ words line :: [Int]
  lines <- mapM (\_ -> do
           line <- getLine
           return line
           ) [1..n]
  let ans = map (\(_,i) -> i) $ sortBy comparator $ zip lines [1..]
  putStrLn $ intercalate " " $ map show ans

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

import qualified Data.ByteString.Char8 as S
import Data.Array.Unboxed

stableBucketSortOn :: (Int -> Int) -> (Int, Int) -> [Int] -> [[Int]]
stableBucketSortOn fun = \bnds li -> let
  arr :: Array Int ([Int] -> [Int])
  arr = accumArray (\x y -> x . (y :)) id bnds [(fun x, x) | x <- li]
  in  filter (not . null) $ map ($ []) $ elems arr
{-# INLINE stableBucketSortOn #-}

mainFun :: SO
mainFun = do
  ~[n, m] <- getInts 2
  sLi <- getNext n
  let
    s :: Array Int S.ByteString
    s = listArray (1, n) $ map P.toStrict sLi
    compareAtPos x = \y -> if  even x
      then  fromEnum (S.index (s ! y) x)
      else  fromEnum 'A' + fromEnum 'Z' - fromEnum (S.index (s ! y) x)
    step :: [[Int]] -> Int -> [[Int]]
    step lis pos = do
      li <- lis
      stableBucketSortOn (compareAtPos pos) (fromEnum 'A', fromEnum 'Z') li
    ans = foldl step [[1..n]] [0 .. m-1]
  pure $ putInts $ concat ans

type SP = State [P.ByteString]
type SO = SP Builder

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]

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

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


{-# LANGUAGE BangPatterns, Safe #-}
{-# Options_GHC -O2 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)
import Data.Char
import Data.Int
import Data.List

getSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

rl :: C.ByteString -> Int64
rl s = fromInteger r
  where Just (r, _) = C.readInteger s

ceil u v = let (a, b) = divMod u v in a + (if b > 0 then 1 else 0)

test :: Int64 -> Int -> [Int] -> Int64
test !h !n !d
  | h' > 0 && v >= 0 = -1
  | h' <= 0 = succ $ fromIntegral $ length $ takeWhile (\x -> h + x > 0) s
  | otherwise = (o * (fromIntegral n)) + (fromIntegral $ succ $ length $ takeWhile (\x -> h'' + x > 0) s)
  where
    s :: [Int64]
    s = scanl1 (+) $ map fromIntegral d
    u = minimum s
    v = last s
    h' = h + u
    v' = negate v
    o = ceil h' v'
    h'' = h + v * o

solve :: [C.ByteString] -> Int64
solve (sh:sn:a) = test h n d
  where
    h = rl sh
    n = ri sn
    d = take n $ map ri a

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

import Data.List (foldl1', find)
import Data.Maybe (fromJust)
diffs d = scanl1 (+) d

solve :: [Integer] -> Integer -> Integer -> Integer
solve diff hp n =
  let
    dt = zip diff [1..]
    cmpp p1@(d1, i1) p2@(d2, i2)
      | d1 < d2 = p1
      | d1 > d2 = p2
      | otherwise = if i1 < i2 then p1 else p2
    (mind, mini) = foldl1' cmpp dt
    cycled = last diff
  in
    if hp + mind <= 0 then snd . fromJust . (find (\(d, _) -> hp + d <= 0)) $ dt
    else if cycled >= 0 then -1
    else
      let
        cycles1 = (hp + mind) `div` (abs cycled)
        findTime cycles rhp
          | rhp + mind > 0 = findTime (cycles + 1) (rhp + cycled)
          | otherwise  =
              let
                ind = snd . fromJust . (find (\(d, _) -> rhp + d <= 0)) $ dt
              in
                cycles * n + ind
      in
        findTime cycles1 (hp + cycles1 * cycled)

main = do
  [hp, n] <- (map read) . words <$> getLine
  diff <- diffs . (map read) . words <$> getLine
  putStrLn . show $ solve diff hp n

import Data.List (foldl1', find)
import Data.Maybe (fromJust)
diffs d = scanl1 (+) d

solve :: [Integer] -> Integer -> Integer -> Integer
solve diff hp n =
  let
    dt = zip diff [1..]
    cmpp p1@(d1, i1) p2@(d2, i2)
      | d1 < d2 = p1
      | d1 > d2 = p2
      | otherwise = if i1 < i2 then p1 else p2
    (mind, mini) = foldl1' cmpp dt
    cycled = last diff
  in
    if hp + mind <= 0 then snd . fromJust . (find (\(d, _) -> hp + d <= 0)) $ dt
    else if cycled >= 0 then -1
    else
      let
        cycles1 = (hp + mind) `div` (abs cycled)
        findTime cycles rhp
          | rhp + mind > 0 = findTime (cycles + 1) (rhp + cycled)
          | otherwise  =
              let
                ind = snd . fromJust . (find (\(d, _) -> rhp + d <= 0)) $ dt
              in
                cycles * n + ind
      in
        findTime cycles1 (hp + cycles1 * mind)

main = do
  [hp, n] <- (map read) . words <$> getLine
  diff <- diffs . (map read) . words <$> getLine
  putStrLn . show $ solve diff hp n

import Data.List (foldl1', find)
import Data.Maybe (fromJust)
diffs d = scanl1 (+) d

solve :: [Integer] -> Integer -> Integer -> Integer
solve diff hp n =
  let
    dt = zip diff [1..]
    cmpp p1@(d1, i1) p2@(d2, i2)
      | d1 < d2 = p1
      | d1 > d2 = p2
      | otherwise = if i1 < i2 then p1 else p2
    (mind, mini) = foldl1' cmpp dt
    cycled = last diff
  in
    if hp + mind <= 0 then mini
    else if cycled >= 0 then -1
    else
      let
        cycles1 = (hp + mind) `div` (abs cycled)
        findTime cycles rhp
          | rhp + mind > 0 = findTime (cycles + 1) (rhp + cycled)
          | otherwise  =
              let
                ind = snd . fromJust . (find (\(d, _) -> rhp + d <= 0)) $ dt
              in
                cycles * n + ind
      in
        findTime cycles1 (hp + cycles1 * mind)

main = do
  [hp, n] <- (map read) . words <$> getLine
  diff <- diffs . (map read) . words <$> getLine
  putStrLn . show $ solve diff hp n


{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List(transpose,sort)
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)

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

main = do
    [n,m,p] <- readInts
    as <- readInts
    bs <- readInts
    let qs = solve n m p as bs
    print (length qs)
    putStrLn $ unwords $ map show qs

takeBy :: Int -> [Int] -> [[Int]]
takeBy p l = transpose $ go l
    where
    go [] = []
    go l = c:go cs
        where
        (c,cs) = splitAt p l

solve :: Int -> Int -> Int -> [Int] -> [Int] -> [Int]
solve n m p as bs = sort $ do
    (l,i) <- zip (takeBy p as) [1..]
    q <- matchIndices m bs l
    return (q*p + i)

insert :: M.Map Int Int -> Int -> M.Map Int Int
insert s v | not (M.member v s) = M.insert v 1 s
           | s M.! v == -1 = M.delete v s
           | otherwise = M.insertWith (+) v 1 s

delete :: M.Map Int Int -> Int -> M.Map Int Int
delete s v | not (M.member v s) = M.insert v (-1) s
           | s M.! v == 1 = M.delete v s
           | otherwise = M.insertWith (+) v (-1) s

matchIndices :: Int -> [Int] -> [Int] -> [Int]
matchIndices m bs l = go ds l (drop m l) 0
    where
    ds = foldl delete (foldl insert M.empty bs) (take m l)
    go ds _ [] i = if M.null ds then [i] else []
    go ds (b:bs) (c:cs) i | M.null ds = i:go ds' bs cs (i+1)
                          | otherwise = go ds' bs cs (i+1)
        where ds' = delete (insert ds b) c

import Data.List(transpose,sort)
import Data.Maybe
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as B

readInt = fromJust . fmap fst .B.readInt
readInts = fmap (map readInt . B.words) B.getLine

main = do
    [n,m,p] <- readInts
    as <- readInts
    bs <- readInts
    let qs = solve n m p as bs
    print (length qs)
    putStrLn $ unwords $ map show qs

takeBy :: Int -> [Int] -> [[Int]]
takeBy p l = transpose $ go l
    where
    go [] = []
    go l = c:go cs
        where (c,cs) = splitAt p l

solve :: Int -> Int -> Int -> [Int] -> [Int] -> [Int]
solve n m p as bs = sort $ do
    (l,i) <- zip (takeBy p as) [1..]
    q <- matchIndices m bs l
    return (q*p + i)

reduce :: M.Map Int Int -> Int -> M.Map Int Int
reduce s v = if s M.! v == 0 then M.delete v s else s

insert :: M.Map Int Int -> Int -> M.Map Int Int
insert s v = reduce (M.insertWith (+) v 1 s) v

delete :: M.Map Int Int -> Int -> M.Map Int Int
delete s v = reduce (M.insertWith (+) v (-1) s) v

matchIndices :: Int -> [Int] -> [Int] -> [Int]
matchIndices m bs l = go ds l (drop m l) 0
    where
    ds = foldl insert (foldl delete M.empty bs) (take m l)
    go ds _ [] i = if M.null ds then [i] else []
    go ds (b:bs) (c:cs) i | M.null ds = i:go ds' bs cs (i+1)
                          | otherwise = go ds' bs cs (i+1)
        where ds' = insert (delete ds b) c

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List(transpose,sort)
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)

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

main = do
    [n,m,p] <- readInts
    as <- readInts
    bs <- readInts
    let qs = solve n m p as bs
    print (length qs)
    putStrLn $ unwords $ map show qs

takeBy :: Int -> [Int] -> [[Int]]
takeBy p l = transpose $ go l
    where
    go [] = []
    go l = c:go cs
        where
        (c,cs) = splitAt p l

solve :: Int -> Int -> Int -> [Int] -> [Int] -> [Int]
solve n m p as bs = sort $ do
    (l,i) <- zip (takeBy p as) [1..]
    q <- matchIndices m bs l
    return (q*p + i)

insert :: M.Map Int Int -> Int -> M.Map Int Int
insert s v | not (M.member v s) = M.insert v 1 s
           | s M.! v == -1 = M.delete v s
           | otherwise = M.insertWith (+) v 1 s

delete :: M.Map Int Int -> Int -> M.Map Int Int
delete s v | not (M.member v s) = M.insert v (-1) s
           | s M.! v == 1 = M.delete v s
           | otherwise = M.insertWith (+) v (-1) s

matchIndices :: Int -> [Int] -> [Int] -> [Int]
matchIndices m bs l = go ds l (drop m l) 0
    where
    ds = foldl delete (foldl insert M.empty bs) (take m l)
    go ds _ [] i = if M.null ds then [i] else []
    go ds (b:bs) (c:cs) i | M.null ds = i:go ds' bs cs (i+1)
                          | otherwise = go ds' bs cs (i+1)
        where ds' = insert (delete ds b) c


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

import Control.Applicative (liftA2)
import Control.Monad (guard, replicateM)
import Control.Monad.State (State, evalState, get, gets, put)
import Data.Array.Unboxed
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromJust)

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

testCase :: Scanner String
testCase = do
  n <- int
  m <- int
  s <- str
  qs <- m >< pair int int
  return . unlines . map show $ solve s qs

solve :: String -> [(Int, Int)] -> [Int]
solve s = map compute
  where
    compute (l, r) = minimum $ do
      a <- [0 .. 2]
      b <- [0 .. 2]
      guard $ a /= b
      c <- [0 .. 2]
      guard $ c /= a && c /= b
      let matches =
            [ psum (freq !! ai !! mi) l r
              | ai <- [a, b, c]
              | mi <- map (`mod` 3) [l, l + 1, l + 2]
            ]
      return $ r - l + 1 - sum matches

    n = length s

    c2i 'a' = 0
    c2i 'b' = 1
    c2i 'c' = 2

    getFreq :: Int -> Int -> UArray Int Int
    getFreq c m =
      listArray (0, n) . scanl (+) 0 $
        [if c2i c' == c && i `mod` 3 == m then 1 else 0 | (c', i) <- zip s [1 .. n]]

    psum :: UArray Int Int -> Int -> Int -> Int
    psum arr l r
      | l > r = 0
      | otherwise = arr ! r - arr ! (l - 1)

    freq = [[getFreq c m | m <- [0 .. 2]] | c <- [0 .. 2]]

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

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

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

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

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

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

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

(><) = times

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

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

import Control.Monad
import Data.Array
import qualified Data.ByteString.Char8 as C

solve :: IO ()
solve = do
    [n, m] <- readInts
    s <- C.unpack <$> C.getLine
    qs <- replicateM m readInts
    let pats = map cycle ["abc", "acb", "bac", "bca", "cab", "cba"]
        difs = map (listArray (0, n) . scanl (+) 0 . map fromEnum . zipWith (/=) s) pats
        qry [l, r] = minimum $ map (\d -> d!r - d!(l - 1)) difs
    putStr $ unlines $ map (show . qry) qs

parseInt = f . C.readInt where f (Just (i, _)) = i
readInts = map parseInt . C.words <$> C.getLine

main :: IO ()
main = solve


import Control.Applicative
import qualified Data.Set as Set
import Data.List

solve :: [Int] -> Int -> [Int]
solve nums maxIdx =
  solve' unused nums (Set.fromList [])
  where
    unused = Set.toList $ Set.fromList [1..maxIdx] `Set.difference` Set.fromList nums
    solve' :: [Int] -> [Int] -> Set.Set Int -> [Int]
    solve' (u:rstUnused) (a:rstGroups) set | a `Set.member` set || a < 1 || a > maxIdx =
                                             u:solve' rstUnused rstGroups set
    solve' unused (a:rstGroups) set = a:solve' unused rstGroups (Set.insert a set)
    solve' _ [] _ = []

main = do
  maxIdx <- read <$> getLine
  nums <- map read . words <$> getLine
  putStrLn $ unwords $ map show $ solve nums maxIdx

import qualified Data.List as L
import qualified Data.IntSet as S
import qualified Data.IntMap as M

main=interact$ solve. map read. words
solve (n:l) =  L.intercalate " " $ map show $ f 1 d
	where (m,s) = foldl (\(m,s) (x,i)->if S.member x s || x>n then (m,s) else (M.insert i x m, S.insert x s)) (M.empty,S.empty) $ zip l [1..n]
	      d = filter (flip S.notMember s) [1..n]
	      f c l
		|c>n   = []
		|otherwise = let v=M.lookup c m in if v==Nothing then head l : (f (c+1) $ tail l) else let Just v'=v in v': f(c+1) l

import Data.List

main=interact$solve.map read.words

solve (n:l) = (intercalate " " $ map show $  f l'' no 1)
        where l'=map head $ groupBy (\a b->fst a==fst b) $ sort $ filter (\x->fst x <= n) $ zip l [1..n]

              diff a [] = a
              diff [] b = []
              diff (a:as) bss@(b:bs)
                  | a==b = diff as bs
                  | a<b  = a : diff as bss

              no=diff [1..n] $ map fst l'
              l''=sortBy (\a b-> snd a `compare` snd b) l'

              f [] [] _ = []
              f a [] _ =  map fst a
              f [] b _ = b
              f ass@(a:as) bss@(b:bs) c
                  | c==snd a  = fst a: f as bss (c+1)
                  | otherwise = b : f ass bs (c+1)

import System.IO
import qualified Data.Set as S

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

solve :: [Int] -> S.Set Int -> Int -> [Int]
solve [] _ _ = []
solve (x:xs) st len = if S.member x st || x > len then 0 : solve xs st len else x : solve xs ( S.insert x st ) len

complete :: [Int] -> S.Set Int -> Int -> [Int]
complete [] _ _ = []
complete (x:xs) st y =
	if x == 0 then
		if S.member y st then
			complete (x:xs) st (y+1)
		else
			y : complete xs ( S.insert y st ) (y+1)
	else
		 x : complete xs st y

main = do
	ln <- getLine
	let [n] = read_ints ln
	ln <- getLine
	let arr = read_ints ln
	let len = length arr
	let ans = solve arr S.empty len
	putStr $ unwords $ map show $ complete ans (S.fromList arr) 1

import Data.List (intercalate)
import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.ByteString (ByteString)
import Data.Set (Set, delete, member, notMember, fromList)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8

loop :: [Int] -> Set Int -> [Int] -> [Int]
loop [] _ _ = []
loop (a:rest) obs out
    | a `member` obs = a:loop rest (a `delete` obs) out
    | otherwise = (head out):loop rest obs (tail out)

solve :: Int -> [Int] -> [Int]
solve n a = loop a obs out
    where
    obs = fromList . filter (< n + 1) $ a :: Set Int
    out = filter (`notMember` obs) [1..n] :: [Int]

parse :: ByteString -> Maybe [Int]
parse = sequence . fmap (fmap fst . B8.readInt) . B8.words

main = read <$> getLine >>= \n ->
    parse <$> B.getLine >>= \(Just a) ->
        putStrLn . intercalate " " . fmap show $ solve n a

import System.IO
import qualified Data.Set as S

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

solve :: [Int] -> S.Set Int -> Int -> [Int]
solve [] _ _ = []
solve (x:xs) st len =
    if S.member x st || x > len then
        0 : solve xs st len
    else
        x : solve xs (S.insert x st) len

complete :: [Int] -> S.Set Int -> Int -> [Int]
complete [] _ _ = []
complete (x:xs) st y =
    if x == 0 then
        if S.member y st then
            complete (x:xs) st (y+1)
        else
            y : complete xs (S.insert y st) (y+1)
    else
        x : complete xs st y

main = do
    ln <- getLine
    let [n] = read_ints ln
    ln <- getLine
    let arr = read_ints ln
    let len = length arr
    let ans = solve arr S.empty len

    putStr $ unwords $ map show $ complete ans (S.fromList arr) 1

import Data.List (intersperse, groupBy, sortBy, sort)

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

showList' :: Show a => [a] -> String
showList' = concat . intersperse " " . map show

minus :: Ord a => [a] -> [a] -> [a]
minus a [] = a
minus [] _ = []
minus (a : as) (b : bs)
    | a == b = minus as bs
    | a < b = a : minus as (b : bs)
    | a > b = minus (a : as) bs

merge :: Int -> [(Int, Int)] -> [Int] -> [Int]
merge _ [] b = b
merge _ a [] = map snd a
merge p a@((k, v) : as) (b : bs)
    | p == k = v : merge (p + 1) as (b : bs)
    | p < k = b : merge (p + 1) a bs

solve :: [Int] -> [Int]
solve a = let n = length a
              id = filter (\(x, y) -> 1 <= y && y <= n) . zip [1 .. ] $ a
              s = let cmp (_, a) (_, b) = compare a b
                  in sortBy cmp id
              uni = let same (_, a) (_, b) = a == b
                    in map head . groupBy same $ s
              rem = [1 .. n] `minus` (sort . map snd $ uni)
              pos = let cmp (a, _) (b, _) = compare a b
                    in sortBy cmp uni
          in merge 1 pos rem

main :: IO ()
main = do
    getLine
    putStrLn . showList' . solve . parseInts =<< getLine

import qualified Data.List as L
import qualified Data.IntSet as S
import qualified Data.IntMap as M

main=interact$ solve. map read. words
solve (n:l) =  L.intercalate " " $ map show $ f 1 d
	where (m,s) = foldl (\(m,s) (x,i)->if S.member x s then (m,s) else (M.insert i x m, S.insert x s)) (M.empty,S.empty) $ zip l [1..n]
	      d = filter (flip S.notMember s) [1..n]
	      f c l
		|c>n   = []
		|otherwise = let v=M.lookup c m in if v==Nothing then head l : (f (c+1) $ tail l) else let Just v'=v in v': f(c+1) l

import Control.Applicative
import qualified Data.Set as Set
import Data.List

solve :: [Int] -> Int -> [Int]
solve nums maxIdx =
  solve' unused nums (Set.fromList [])
  where
    unused = Set.toList $ Set.fromList [1..maxIdx] `Set.difference` Set.fromList nums
    solve' :: [Int] -> [Int] -> Set.Set Int -> [Int]
    solve' (u:rstUnused) (a:rstGroups) set =
      if a `Set.member` set || a < 1 || a > maxIdx then
        u:solve' rstUnused rstGroups set
      else a:solve' (u:rstUnused) rstGroups (Set.insert a set)
    solve' (u:rstUnused) [] set = u:solve' rstUnused [] set
    solve' [] _ _ = []

main = do
  maxIdx <- read <$> getLine
  nums <- map read . words <$> getLine
  putStrLn $ unwords $ map show $ solve nums maxIdx

import Control.Applicative
import qualified Data.Set as Set
import Data.List

solve :: [Int] -> Int -> [Int]
solve nums maxIdx =
  solve' unused $ group $ filter (\x -> x >= 1 && x <= maxIdx) nums
  where
    unused = Set.toList $ Set.fromList [1..maxIdx] `Set.difference` Set.fromList nums
    solve' :: [Int] -> [[Int]] -> [Int]
    solve' unused ([a]:rst) =
      a:solve' unused rst
    solve' (u:rstUnused) ((a:rstGroup):rstGroups) =
      u:solve' rstUnused (rstGroup:rstGroups)
    solve' (u:rstUnused) [] = u:solve' rstUnused []
    solve' [] _ = []

main = do
  maxIdx <- read <$> getLine
  nums <- map read . words <$> getLine
  putStrLn $ unwords $ map show $ solve nums maxIdx

import System.IO
import qualified Data.Set as S

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

modify :: Int -> S.Set Int -> Int
modify x st = if S.member x st then modify (x+1) st else x

solve :: [Int] -> S.Set Int -> [Int]
solve [] _ = []
solve (x:xs) st = if S.notMember x st then x : solve xs (S.insert x st) else y : solve xs (S.insert y st)
	where y = modify 1 st

main = do
	ln <- getLine
	let [n] = read_ints ln
	ln <- getLine
	let arr = read_ints ln
	putStr $ unwords $ map show $ solve arr S.empty


module Main where

import Control.Monad
import Control.Monad.State
import Data.Array
import Data.Int
import Prelude
import qualified Data.ByteString.Lazy.Char8 as L

type Tokenizer = State [L.ByteString]

nextInt :: Tokenizer Int
nextInt = state $ \(s:ss) -> case L.readInt s of
                                   Just (x, _) -> (x, ss)
                                   Nothing -> error $ "Can't parse Int:" ++ (show s)

nextInteger :: Tokenizer Integer
nextInteger = state $ \(s:ss) -> case L.readInteger s of
                                   Just (x, _) -> (x, ss)
                                   Nothing -> error $ "Can't parse Integer:" ++ (show s)

nextChar :: Tokenizer Char
nextChar = state $ \(s:ss) -> (L.index s 0, ss)

data Piece = Piece { getType :: Char
                   , getX :: Integer
                   , getY :: Integer
                   }

cross :: Integer -> Integer -> Integer -> Integer -> Int64
cross x1 y1 x2 y2 = (fromIntegral x1 :: Int64) * (fromIntegral y2 :: Int64) - (fromIntegral x2 :: Int64) * (fromIntegral y1 :: Int64)

dot :: Integer -> Integer -> Integer -> Integer -> Int64
dot x1 y1 x2 y2 = (fromIntegral x1 :: Int64) * (fromIntegral x2 :: Int64) + (fromIntegral y1 :: Int64) * (fromIntegral y2 :: Int64)

sameDirection :: Integer -> Integer -> Integer -> Integer -> Integer -> Integer -> Bool
sameDirection x1 y1 x2 y2 dx dy = cross vx vy dx dy == 0 && dot vx vy dx dy >= 0
    where vx = x2 - x1
          vy = y2 - y1

check :: Integer -> Integer -> [Piece] -> Bool
check x0 y0 ps = getType best /= 'K'
    where best = foldl (closerPiece x0 y0) (Piece 'K' x0 y0) (map canMove cands)
          cands = [(closest x0 y0 dx dy ps, dx, dy) | dx <- [-1..1], dy <- [-1..1], not (dx == 0 && dy == 0)]

canMove :: (Piece, Integer, Integer) -> Piece
canMove (p, dx, dy) | t == 'B' && dx /= 0 && dy /= 0   = p
                    | t == 'R' && (dx == 0 || dy == 0) = p
                    | t == 'Q'                         = p
                    | otherwise = Piece 'K' 0 0
                    where t = getType p

closer :: Integer -> Integer -> Piece -> Piece -> Bool
closer x0 y0 p1 p2 = t2 == 'K' || (t1 /= 'K' && t2 /= 'K' && dist1 < dist2)
                     where dist1 = abs (x1 - x0) + abs (y1 - y0)
                           dist2 = abs (x2 - x0) + abs (y2 - y0)
                           Piece t1 x1 y1 = p1
                           Piece t2 x2 y2 = p2

closerPiece :: Integer -> Integer -> Piece -> Piece -> Piece
closerPiece x0 y0 p1 p2 | closer x0 y0 p1 p2 = p1
                        | otherwise          = p2

closest :: Integer -> Integer -> Integer -> Integer -> [Piece] -> Piece
closest x0 y0 dx dy [] = Piece 'K' x0 y0
closest x0 y0 dx dy (p:ps) | sameDirection x0 y0 x1 y1 dx dy && closer x0 y0 p best = p
                           | otherwise                                              = best
                           where best = closest x0 y0 dx dy ps
                                 Piece _ x1 y1 = p

solve :: Tokenizer String
solve = do
    n <- nextInt
    x0 <- nextInteger
    y0 <- nextInteger
    p <- replicateM n $ do
        t <- nextChar
        x <- nextInteger
        y <- nextInteger
        return $ Piece t x y
    if (check x0 y0 p) then return "YES"
    else return "NO"

main = do
    contents <- L.getContents
    putStrLn $ evalState solve (L.words contents)

-- Codeforces Round #379 (Div. 2)
-- http://codeforces.com/contest/734

-- ID: 734D (Anton and Chess)
import Control.Monad
import Data.List
import Data.Int
import Data.Maybe
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

type Piece = (String, Int, Int)

getInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]
parseInt = fst . fromJust . BS8.readInt

lessX (_,x1,_) (_,x2,_) = compare x1 x2
lessY (_,_,y1) (_,_,y2) = compare y1 y2

main = do
    n <- read `fmap` getLine :: IO Int
    [kingX, kingY] <- (map read . words) `fmap` getLine :: IO [Int]
    blacks <- replicateM n $ do
        [post, x, y] <- BS8.words `fmap` BS.getLine
        return (BS8.unpack post, parseInt x, parseInt y)
    let king = ("K", kingX, kingY)
    let dirs = [(-1,-1,flip lessX), (0,-1,flip lessY), (1,-1,lessX),
                (-1,0,flip lessX), (1,0,lessX),
                (-1,1,flip lessX), (0,1,lessY), (1,1,lessX)]
    let attackers = map fromJust $ filter isJust $ map (choose king blacks) dirs
    if any (checkmate king) attackers
    then putStrLn "YES"
    else putStrLn "NO"

choose king blacks (dx, dy, sorter) = case (sortBy sorter . filter (attack dx dy king)) blacks of
    [] -> Nothing
    xs -> Just (head xs)
attack dx dy (_, kx, ky) (_, x, y)
    | dx == 0 = diffX == 0 && ry >= 1
    | dy == 0 = diffY == 0 && rx >= 1
    | otherwise = rx >= 1 && rx >= 1 && ry == rx
    where
        diffX = x - kx
        diffY = y - ky
        rx = diffX `div` dx
        ry = diffY `div` dy

checkmate (_, kx, ky) (post, x, y)
    | post == "R" = dx == 0 || dy == 0
    | post == "B" = dy /= 0 && (abs (dx `div` dy) == 1)
    | post == "Q" = True
    where
        dx = x - kx
        dy = y - ky

#!/usr/bin/env stack
{- stack
  --resolver lts-2.22
  runghc
  --package array
  --package base
  --package bytestring
  --package containers
  --package mtl
  --package parsec
  --package vector
  --
  -hide-all-packages
-}
{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}
module Main
( main
) where

import           Prelude hiding (interact, lines, unlines, words, unwords,
                                 sequence, foldr)
import           Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,
                                        unlines, unwords, interact, readInt,
                                        readInteger)
import qualified Data.ByteString.Char8 as BS
import           Data.List (foldl', sort, sortBy, group, groupBy, inits, tails)
import qualified Data.List as L
import qualified Data.IntSet as IS
import           Data.IntSet (IntSet)
import qualified Data.IntMap.Strict as IM
import           Data.IntMap.Strict (IntMap)
import qualified Data.Map.Strict as M
import           Data.Map.Strict (Map)
import qualified Data.Set as S
import           Data.Set (Set)
import qualified Data.Array.IArray as A
import           Data.Array.IArray ((!), Array, listArray, array)
import           Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,
                             catMaybes)
import           Data.Either (either)
import           Control.Applicative (Applicative, pure,
                                      (<$>), (<*>), liftA2, liftA3)
import           Control.Monad (unless, when, void, filterM, ap)
import           Control.Arrow ((***), (&&&), first, second)
import           Data.Traversable (sequence, sequenceA, traverse,
                                   Traversable)
import           Data.Ord (comparing, Down(..))
import           Data.Function (on)
import           Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,
                            bit, shiftR, shiftL, Bits)
import qualified Data.Bits as B
import           Data.Word (Word32)
import           Control.Monad.State (State, get, put, gets, modify,
                                      evalState, execState, runState)
import           Text.Parsec (char, space, parse, Parsec)
import qualified Text.Parsec as P
import           Data.Tuple (swap)
import           Data.Foldable (Foldable, foldr)
import           Data.Monoid ((<>), Monoid, mappend, mempty)

type N = Int
toNum = toInt

data Piece = Queen | Rook | Bishop
data Dir = U | D | L | R | UL | UR | DL | DR
    deriving (Eq, Ord, Show, Read, Enum, Bounded)

toDir (i, j)
  | i > 0 = case compare j 0 of
              GT -> UR
              EQ -> R
              LT -> DR
  | i < 0 = case compare j 0 of
              GT -> UL
              EQ -> L
              LT -> DL
  | otherwise = case compare j 0 of
              GT -> U
              EQ -> error "invalid input"
              LT -> D

answer :: (N, N) -> [(Piece, (N, N))] -> String
answer loc@(x,y) zs = if go (map fixCoord zs) then "YES" else "NO"
  where fixCoord (p, (x', y')) = (p, (x' - x, y' - y))
        go = go' . sortBy (comparing distance) . filter possible
        possible (_, (i, j)) = i == 0 || j == 0 || abs i == abs j
        distance (_, (i, j)) = max (abs i) (abs j)
        go' = go'' S.empty
        go'' _ [] = False
        go'' s ((p, coord):ps) = let d = toDir coord
                                     s' = S.insert d s
                                  in (isAttack p d && d `S.notMember` s)
                                  || go'' s' ps
        isAttack Queen _ = True
        isAttack Rook d = d `elem` [U, D, L, R]
        isAttack Bishop d = d `elem` [UL, UR, DL, DR]

handleInput :: ByteString -> ByteString
handleInput = lines
            & coerceInput answer
            & pack

toInt = readInt & fromJust & fst
toInte = readInteger & fromJust & fst
toX :: Read a => ByteString -> a
toX = unpack & read

coerceInput f (a:b:xs) = f (toTuple b) (map toPiece (take (toInt a) xs))
coerceInput _ _ = error "invalid input"

toTuple = words & map toNum & (\(a:b:xs) -> (a, b))

toPiece xs = case words xs of
               (p:x:y:_) -> (toType (unpack p), (toNum x, toNum y))

toType "B" = Bishop
toType "R" = Rook
toType "Q" = Queen

main :: IO ()
main = interact handleInput

-- Util stuff --
(&) :: (a -> b) -> (b -> c) -> a -> c
(&) = flip (.)
infixl 9 &

{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

--import Debug.Trace

import System.IO
import GHC.Generics
import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Maybe
import Data.Either
import Data.Ord
import Data.Ratio
import qualified Data.Foldable as Foldable
import Data.Char
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.List
import Data.Array.IArray
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA
import qualified Data.Array.ST.Safe as SA
import qualified Data.Array.IO.Safe as IA
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet

getWords  = words <$> getLine :: IO [String]
getInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]
getDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]
getInt    = read <$> getLine :: IO Int
getDouble  = read <$> getLine :: IO Double
printLines :: Show a => [a] -> IO ()
printLines = mapM_ print
printStrs = mapM_ putStrLn :: [String] -> IO ()

---- Answer Code Section ----

type Pos = (Int, Int)
type ChessPiece = (Pos, Piece)
data Piece = Rook | Bishop | Queen | King | None deriving (Eq, Show, Generic)
data Dir = Hori | Vert | DownRight | UpRight deriving (Eq, Show, Enum)
instance NFData Piece
pos = fst
piece = snd

inf = 2*(10^9) :: Int

compDir Hori (x1, y1) (x2, y2) = compare y1 y2 `mappend` compare x1 x2
compDir Vert (x1, y1) (x2, y2) = compare x1 x2 `mappend` compare y1 y2
compDir DownRight p1 p2 = (compare `on` downRight) p1 p2 `mappend` (compare `on` upRight) p1 p2
compDir UpRight   p1 p2 = (compare `on` upRight) p1 p2 `mappend` (compare `on` downRight) p1 p2

checkPos Hori (x1, y1) (x2, y2) = y1 == y2
checkPos Vert (x1, y1) (x2, y2) = x1 == x2
checkPos DownRight p1 p2 = downRight p1 == downRight p2
checkPos UpRight   p1 p2 = upRight p1   == upRight p2

checkPiece Hori p = p == Rook || p == Queen
checkPiece Vert p = p == Rook || p == Queen
checkPiece DownRight p = p == Bishop || p == Queen
checkPiece UpRight   p = p == Bishop || p == Queen

downRight (x, y) = x + y
upRight (x, y) = x - y

findCheck :: ChessPiece -> [ChessPiece] -> (Pos -> Pos -> Ordering) -> (Pos -> Pos -> Bool) -> (Piece -> Bool) -> Bool
findCheck king chessPieces compFn checkPosFn checkPieceFn = isCheck sortedPieces where
    dummyPieces = map (\p -> (p, None)) [(-inf, 0), (inf, 0), (0, -inf), (0, inf)]
    sortedPieces = sortBy (compFn `on` pos) (filter ((checkPosFn `on` pos) king) chessPieces ++ dummyPieces ++ [king])
    check king p = (checkPosFn `on` pos) king p && checkPieceFn (piece p)
    isCheck (prev:curr:next:xs) = if piece curr == King && (check curr prev || check curr next) then True else isCheck (curr:next:xs)
    isCheck _ = False

process :: ChessPiece -> [ChessPiece] -> Bool
process king chessPieces = any (\dir -> findCheck king chessPieces (compDir dir) (checkPos dir) (checkPiece dir)) [Hori .. UpRight]

main = do
    n <- getInt
    kingPos <- readPoint <$> BS.getLine
    chessPieces <- replicateM n (readPiece <$> BS.getLine)
    if process (kingPos, King) chessPieces
    then putStrLn "YES"
    else putStrLn "NO"

readPoint str = (x,y) where x:y:[] = (map (fst . fromJust . BS8.readInt) . BS8.words) str
readPiece str = case BS8.uncons str of
    Just ('R', xs) -> (readPoint $ BS8.tail xs, Rook)
    Just ('B', xs) -> (readPoint $ BS8.tail xs, Bishop)
    Just ('Q', xs) -> (readPoint $ BS8.tail xs, Queen)

#!/usr/bin/env stack
{- stack
  --resolver lts-2.22
  runghc
  --package array
  --package base
  --package bytestring
  --package containers
  --package mtl
  --package parsec
  --package vector
  --
  -hide-all-packages
-}
{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}
module Main
( main
) where

import           Prelude hiding (interact, lines, unlines, words, unwords,
                                 sequence, foldr)
import           Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,
                                        unlines, unwords, interact, readInt,
                                        readInteger)
import qualified Data.ByteString.Char8 as BS
import           Data.List (foldl', sort, sortBy, group, groupBy, inits, tails)
import qualified Data.List as L
import qualified Data.IntSet as IS
import           Data.IntSet (IntSet)
import qualified Data.IntMap.Strict as IM
import           Data.IntMap.Strict (IntMap)
import qualified Data.Map.Strict as M
import           Data.Map.Strict (Map)
import qualified Data.Set as S
import           Data.Set (Set)
import qualified Data.Array.IArray as A
import           Data.Array.IArray ((!), Array, listArray, array)
import           Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,
                             catMaybes)
import           Data.Either (either)
import           Control.Applicative (Applicative, pure,
                                      (<$>), (<*>), liftA2, liftA3)
import           Control.Monad (unless, when, void, filterM, ap)
import           Control.Arrow ((***), (&&&), first, second)
import           Data.Traversable (sequence, sequenceA, traverse,
                                   Traversable)
import           Data.Ord (comparing, Down(..))
import           Data.Function (on)
import           Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,
                            bit, shiftR, shiftL, Bits)
import qualified Data.Bits as B
import           Data.Word (Word32)
import           Control.Monad.State (State, get, put, gets, modify,
                                      evalState, execState, runState)
import           Text.Parsec (char, space, parse, Parsec)
import qualified Text.Parsec as P
import           Data.Tuple (swap)
import           Data.Foldable (Foldable, foldr)
import           Data.Monoid ((<>), Monoid, mappend, mempty)

type N = Int
toNum = toInt

data Piece = Queen | Rook | Bishop
data Dir = U | D | L | R | UL | UR | DL | DR
    deriving (Eq, Ord, Show, Read, Enum, Bounded)

toDir (i, j)
  | i > 0 = case compare j 0 of
              GT -> UR
              EQ -> R
              LT -> DR
  | i < 0 = case compare j 0 of
              GT -> UL
              EQ -> L
              LT -> DL
  | otherwise = case compare j 0 of
              GT -> U
              EQ -> error "invalid input"
              LT -> D

answer :: (N, N) -> [(Piece, (N, N))] -> String
answer loc@(x,y) zs = if go (map fixCoord zs) then "YES" else "NO"
  where fixCoord (p, (x', y')) = (p, (x' - x, y' - y))
        go = go' . sortBy (comparing distance) . filter possible
        possible (_, (i, j)) = i == 0 || j == 0 || abs i == abs j
        distance (_, (i, j)) = abs i + abs j
        go' = go'' S.empty
        go'' _ [] = False
        go'' s ((p, coord):ps) = let d = toDir coord
                                     s' = S.insert d s
                                  in (isAttack p d && d `S.notMember` s)
                                  || go'' s' ps
        isAttack Queen _ = True
        isAttack Rook d = d `elem` [U, D, L, R]
        isAttack Bishop d = d `elem` [UL, UR, DL, DR]

handleInput :: ByteString -> ByteString
handleInput = lines
            & coerceInput answer
            & pack

toInt = readInt & fromJust & fst
toInte = readInteger & fromJust & fst
toX :: Read a => ByteString -> a
toX = unpack & read

coerceInput f (a:b:xs) = f (toTuple b) (map toPiece (take (toNum a) xs))
coerceInput _ _ = error "invalid input"

toTuple = words & map toNum & (\(a:b:xs) -> (a, b))

toPiece xs = case words xs of
               (p:x:y:_) -> (toType (unpack p), (toNum x, toNum y))

toType "B" = Bishop
toType "R" = Rook
toType "Q" = Queen

main :: IO ()
main = interact handleInput

-- Util stuff --
(&) :: (a -> b) -> (b -> c) -> a -> c
(&) = flip (.)
infixl 9 &

module Main where

import Control.Monad
import Control.Monad.State
import Data.Array
import Data.Int
import Prelude
import qualified Data.ByteString.Lazy.Char8 as L

type Tokenizer = State [L.ByteString]

nextInt :: Tokenizer Int
nextInt = state $ \(s:ss) -> case L.readInt s of
                                   Just (x, _) -> (x, ss)
                                   Nothing -> error $ "Can't parse Int:" ++ (show s)

nextChar :: Tokenizer Char
nextChar = state $ \(s:ss) -> (L.index s 0, ss)

data Piece = Piece { getType :: Char
                   , getX :: Int
                   , getY :: Int
                   }

cross :: Int -> Int -> Int -> Int -> Int64
cross x1 y1 x2 y2 = (fromIntegral x1 :: Int64) * (fromIntegral y2 :: Int64) - (fromIntegral x2 :: Int64) * (fromIntegral y1 :: Int64)

dot :: Int -> Int -> Int -> Int -> Int64
dot x1 y1 x2 y2 = (fromIntegral x1 :: Int64) * (fromIntegral x2 :: Int64) + (fromIntegral y1 :: Int64) * (fromIntegral y2 :: Int64)

sameDirection :: Int -> Int -> Int -> Int -> Int -> Int -> Bool
sameDirection x1 y1 x2 y2 dx dy = cross vx vy dx dy == 0 && dot vx vy dx dy >= 0
    where vx = x2 - x1
          vy = y2 - y1

check :: Int -> Int -> [Piece] -> Bool
check x0 y0 ps = getType best /= 'K'
    where best = foldl (closerPiece x0 y0) (Piece 'K' x0 y0) (map canMove cands)
          cands = [(closest x0 y0 dx dy ps, dx, dy) | dx <- [-1..1], dy <- [-1..1], not (dx == 0 && dy == 0)]

canMove :: (Piece, Int, Int) -> Piece
canMove (p, dx, dy) | t == 'B' && dx /= 0 && dy /= 0   = p
                    | t == 'R' && (dx == 0 || dy == 0) = p
                    | t == 'Q'                         = p
                    | otherwise = Piece 'K' 0 0
                    where t = getType p

closer :: Int -> Int -> Piece -> Piece -> Bool
closer x0 y0 p1 p2 = t2 == 'K' || (t1 /= 'K' && t2 /= 'K' && dist1 < dist2)
                     where dist1 = abs (x1 - x0) + abs (y1 - y0)
                           dist2 = abs (x2 - x0) + abs (y2 - y0)
                           Piece t1 x1 y1 = p1
                           Piece t2 x2 y2 = p2

closerPiece :: Int -> Int -> Piece -> Piece -> Piece
closerPiece x0 y0 p1 p2 | closer x0 y0 p1 p2 = p1
                        | otherwise          = p2

closest :: Int -> Int -> Int -> Int -> [Piece] -> Piece
closest x0 y0 dx dy [] = Piece 'K' x0 y0
closest x0 y0 dx dy (p:ps) | sameDirection x0 y0 x1 y1 dx dy && closer x0 y0 p best = p
                           | otherwise                                              = best
                           where best = closest x0 y0 dx dy ps
                                 Piece _ x1 y1 = p

solve :: Tokenizer String
solve = do
    n <- nextInt
    x0 <- nextInt
    y0 <- nextInt
    p <- replicateM n $ do
        t <- nextChar
        x <- nextInt
        y <- nextInt
        return $ Piece t x y
    if (check x0 y0 p) then return "YES"
    else return "NO"

main = do
    contents <- L.getContents
    putStrLn $ evalState solve (L.words contents)

module Main where

import Control.Monad
import Control.Monad.State
import Data.Array
import Data.Int
import Prelude
import qualified Data.ByteString.Lazy.Char8 as L

type Tokenizer = State [L.ByteString]

nextInt :: Tokenizer Int
nextInt = state $ \(s:ss) -> case L.readInt s of
                                   Just (x, _) -> (x, ss)
                                   Nothing -> error $ "Can't parse Int:" ++ (show s)

nextChar :: Tokenizer Char
nextChar = state $ \(s:ss) -> (L.index s 0, ss)

data Piece = Piece { getType :: Char
                   , getX :: Int
                   , getY :: Int
                   }

cross :: Int -> Int -> Int -> Int -> Int64
cross x1 y1 x2 y2 = (fromIntegral x1) * (fromIntegral y2) - (fromIntegral x2) * (fromIntegral y1)

dot :: Int -> Int -> Int -> Int -> Int64
dot x1 y1 x2 y2 = (fromIntegral x1) * (fromIntegral x2) + (fromIntegral y1) * (fromIntegral y2)

sameDirection :: Int -> Int -> Int -> Int -> Int -> Int -> Bool
sameDirection x1 y1 x2 y2 dx dy = cross vx vy dx dy == 0 && dot vx vy dx dy >= 0
    where vx = x2 - x1
          vy = y2 - y1

check :: Int -> Int -> [Piece] -> Bool
check x0 y0 ps = getType best /= 'K'
    where best = foldl (closerPiece x0 y0) (Piece 'K' x0 y0) (map canMove cands)
          cands = [(closest x0 y0 dx dy ps, dx, dy) | dx <- [-1..1], dy <- [-1..1], not (dx == 0 && dy == 0)]

canMove :: (Piece, Int, Int) -> Piece
canMove (p, dx, dy) | t == 'B' && dx /= 0 && dy /= 0   = p
                    | t == 'R' && (dx == 0 || dy == 0) = p
                    | t == 'Q'                         = p
                    | otherwise = Piece 'K' 0 0
                    where t = getType p

closer :: Int -> Int -> Piece -> Piece -> Bool
closer x0 y0 p1 p2 = t2 == 'K' || (t1 /= 'K' && t2 /= 'K' && dist1 < dist2)
                     where dist1 = abs (x1 - x0) + abs (y1 - y0)
                           dist2 = abs (x2 - x0) + abs (y2 - y0)
                           Piece t1 x1 y1 = p1
                           Piece t2 x2 y2 = p2

closerPiece :: Int -> Int -> Piece -> Piece -> Piece
closerPiece x0 y0 p1 p2 | closer x0 y0 p1 p2 = p1
                        | otherwise          = p2

closest :: Int -> Int -> Int -> Int -> [Piece] -> Piece
closest x0 y0 dx dy [] = Piece 'K' x0 y0
closest x0 y0 dx dy (p:ps) | sameDirection x0 y0 x1 y1 dx dy && closer x0 y0 p best = p
                           | otherwise                                              = best
                           where best = closest x0 y0 dx dy ps
                                 Piece _ x1 y1 = p

solve :: Tokenizer String
solve = do
    n <- nextInt
    x0 <- nextInt
    y0 <- nextInt
    p <- replicateM n $ do
        t <- nextChar
        x <- nextInt
        y <- nextInt
        return $ Piece t x y
    if (check x0 y0 p) then return "YES"
    else return "NO"

main = do
    contents <- L.getContents
    putStrLn $ evalState solve (L.words contents)