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

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

{-# options_ghc -O3                              #-}

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

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

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

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

toInt c = ord c - ord '0'

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

showDigs = concatMap show

solve digs = ans
  where
    ans = L.sort . snd . foldl prevD (9+1,[]) . reverse . map toInt $ digs

prevD (minDig, digs) dig = (min minDig dig, fixedDig : digs)
  where
    fixedDig | (dig == 9)      = dig
             | (dig > minDig)  = dig + 1
             | otherwise       = dig

import Data.Bifunctor (second)
import Data.Char (chr, ord)
import Data.List (sort)

(>$>) = flip ($)
(>>>) = flip (.)
infixl 0 >$>

main :: IO ()
main = interact $ lines >>> tail >>> map solve >>> unlines

solve :: String -> String
solve = pick 0 >>> second (sort >>> map (ord >>> (1 +) >>> min (ord '9') >>> chr)) >>> uncurry merge

merge :: Ord a => [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge (x : xs) (y : ys)
  | x <= y = x : merge xs (y : ys)
  | otherwise = y : merge (x : xs) ys

pick :: Int -> String -> (String, String)
pick 10 s = ("", s)
pick d s = (filter (== c) lt ++ lt', filter (/= c) lt ++ rt')
  where
    c = head $ show d
    lt = s >$> reverse >>> dropWhile (/= c)
    (lt', rt') = s >$> reverse >>> takeWhile (/= c) >>> reverse >>> pick (d + 1)

import Data.Char (chr, ord)
import Data.List (sort)
import Debug.Trace (trace)

(>$>) = flip ($)

(>>>) = flip (.)

infixl 0 >$>

main :: IO ()
main = interact $ lines >>> tail >>> map solve >>> unlines

solve :: String -> String
solve s = merge lt rt'
  where
    (lt, rt) = pick 0 s
    rt' = rt >$> sort >>> map (ord >>> (1 +) >>> min (ord '9') >>> chr)

merge :: Ord a => [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys)
  | x <= y = x : merge xs (y:ys)
  | otherwise = y : merge (x:xs) ys

pick :: Int -> String -> (String, String)
pick 10 s = ("", s)
pick d s = (filter (== c) lt ++ lt', filter (/= c) lt ++ rt')
  where
    c = head $ show d
    lt = s >$> reverse >>> dropWhile (/= c)
    (lt', rt') = s >$> reverse >>> takeWhile (/= c) >>> reverse >>> pick (d + 1)

debug :: Show a => a -> a
debug a = trace (show a) a

import Data.Char (chr, ord)
import Data.List (sort, partition)
import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase = getLine >>= putStrLn . minStr

inc :: Char -> Char
inc c | c < '9' = chr (1+ord c)
      | c == '9'= '9'

minStr :: String -> String
minStr s = let (ms, rest) = minSubSeq s
           in
             sort (ms ++ map inc rest)

-- WRONG ANSWER for case: 32454 - expected 24445 - got 24556
-- find the lexicographically smallest subsequence in a given string
minSubSeq :: String -> (String, String)
minSubSeq s = let mlss [] (stack, trash) = (reverse stack, trash)
                  mlss s (stack, trash) = let (i, c, count) = minCharCount s in
                                            mlss (drop i s) (replicate count c ++ stack, filter (/=c) (take i s) ++ trash)
              in
                mlss s ([], [])

minCharCount s = foldl f (1, head s, 1) (zip [2..] (tail s))
  where
    f (i, c, count) (ii, cc) = case compare c cc of
                                 EQ -> (ii, c, count+1)
                                 GT -> (ii, cc, 1)
                                 LT -> (i, c, count)

import Data.Char (chr, ord)
import Data.List (sort, partition)
import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase = getLine >>= putStrLn . minStr

minStr :: String -> String
minStr s = let (ms, rest) = minSubSeq s
               inc c | c < '9' = chr (1+ord c)
                     | c == '9'= '9'
           in
             ms ++ map inc (sort rest)

-- find the lexicographically smallest subsequence in a given string
minSubSeq :: String -> (String, String)
minSubSeq s = let mlss [] (stack, []) = (reverse stack, [])
                  mlss [] (stack, trash) = let mt = minimum trash
                                               (s1, t1) = partition (<mt) stack
                                           in
                                             (reverse s1, t1++trash)
                  mlss s (stack, trash) = let (i, c, count) = minCharCount s in
                                            mlss (drop i s) (replicate count c ++ stack, filter (/=c) (take i s) ++ trash)
              in
                mlss s ([], [])

minCharCount s = foldl f (1, head s, 1) (zip [2..] (tail s))
  where
    f (i, c, count) (ii, cc) = case compare c cc of
                                 EQ -> (ii, c, count+1)
                                 GT -> (ii, cc, 1)
                                 LT -> (i, c, count)


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

import qualified Data.Array as A

import Data.Bits(xor)

import Data.Map((!))

solve :: Integer -> [Char] -> Bool
solve _ list
	| numT /= 2*numM = False
	| otherwise = (snd $ test list) && (snd $ test $ reverse list)
	where
		test [] = (0, True)
		test ('M':xs)
			| n == 0 = (0, False)
			| otherwise = (n-1, b)
			where (n, b) = test xs
		test ('T':xs) = (n+1, b)
			where (n, b) = test xs
		numM = sum [1|x<-list, x=='M']
		numT = sum [1|x<-list, x=='T']

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

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 $ showResult $ solve n a
		loop $ t - 1
	loop t

{-# LANGUAGE ViewPatterns #-}
import Control.Monad ( replicateM_ )
import Data.Bool ( bool )

solve :: Int -> String -> Bool
solve ((`div` 3) -> k) str = valid && t == k
    where
    (t, valid) = foldr loop (0, True) str

    loop x (upd x -> t, valid) = (t, valid && 0<=t && t<=k)

    upd 'T' = succ
    upd 'M' = pred

getInt = read <$> getLine
main = do
    n <- getInt
    replicateM_ n (solve <$> getInt <*> getLine  >>=  putStrLn . bool "NO" "YES")

{-# LANGUAGE ViewPatterns #-}
import Control.Monad ( replicateM_ )
import Data.Bool ( bool )

solve :: Int -> String -> Bool
solve n str = valid && t == 2 * m
    where
    ((m, t), valid) = foldr validate ((0, 0), True) str

    validate ch (incr ch -> (m, t), valid) =
        ((m, t), valid && (m <= t) && (t - m) <= div n 3)

    incr 'M' (m, t) = (m+1, t)
    incr 'T' (m, t) = (m, t+1)

main = do
    let getInt = read <$> getLine
    n <- getInt
    replicateM_ n $ (solve <$> getInt <*> getLine) >>= putStrLn . bool "NO" "YES"

import Control.Monad
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as C

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

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    [n] <- getInts
    s <- C.filter (not . isSpace) <$> C.getLine
    let acc Nothing _ = Nothing
        acc (Just x) 'T' = Just (x + 1)
        acc (Just x) _
          | x == 0 = Nothing
          | otherwise = Just (x - 1)
        check = maybe False (== n `div` 3) . C.foldl' acc (Just 0)
    C.putStrLn $ C.pack $ if check s && check (C.reverse s) then "YES" else "NO"

import Control.Monad
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as C
import qualified Data.Sequence as Seq

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

type State = Maybe (Int, Seq.Seq Char)
acc :: State -> Char -> State
acc Nothing _ = Nothing
acc (Just (ls, rs)) 'M'
  | Seq.null bs = Nothing
  | otherwise = Just (ls + Seq.length as, Seq.drop 1 bs Seq.|> 'M')
  where (as, bs) = Seq.spanl (== 'M') rs
acc (Just (ls, rs)) 'T' = Just (ls, rs Seq.|> 'T')
acc o _ = o

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    _ <- C.getLine
    s <- C.getLine
    let
        result = maybe False func $ C.foldl' acc (Just (0, Seq.empty)) s
        func (ms, str) =
          case foldl' acc (Just ms) str of
            Nothing -> False
            Just 0 -> True
            _ -> False
          where acc Nothing _ = Nothing
                acc (Just ms) 'T' = if ms <= 0 then Nothing else Just (ms - 1)
                acc (Just ms) 'M' = Just (ms + 1)
                acc o _ = o
    C.putStrLn $ C.pack $ if result then "YES" else "NO"

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

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

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    _ <- C.getLine
    s <- C.getLine
    let work str
          | isNothing result = False
          | otherwise = let Just (x, y) = result in x == y
          where
          acc Nothing _ = Nothing
          acc (Just (x, y)) 'M' = if y <= 0 then Nothing else Just (x + 1, y - 1)
          acc (Just (x, y)) _ = Just (x, y + 1 :: Int)
          result = C.foldl' acc (Just (0, 0)) str
        result = if work s && work (C.reverse s) then "YES" else "NO"
    C.putStrLn $ C.pack result

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

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

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    _ <- C.getLine
    s <- C.getLine
    let acc Nothing _ = Nothing
        acc (Just (x, y)) 'M' = if y <= 0 then Nothing else Just (x + 1, y - 1)
        acc (Just (x, y)) _ = Just (x, y + 1 :: Int)
        result = C.foldl' acc (Just (0, 0)) s
    C.putStrLn $ C.pack $ case result of
      Nothing -> "NO"
      Just (x, y) -> if x == y then "YES"  else "NO"

import Control.Monad ( replicateM_ )
import Data.Bool ( bool )

solve :: Int -> String -> Bool
solve n str = mod n 3 == 0 && all validate (tail $ scanl count (0, 0) str) where
    validate (m, t) = (m <= t) && (t - m) <= div n 3
    count (m, t) 'M' = (m+1, t)
    count (m, t) 'T' = (m, t+1)

main = do
    n <- read <$> getLine
    replicateM_ n $ solve <$> (read <$> getLine) <*> getLine >>= putStrLn . bool "NO" "YES"

import Control.Monad ( replicateM_ )
import Data.Bool ( bool )

solve :: Int -> String -> Bool
solve n str = mod n 3 == 0 && all validate (scanl count (0, 0) str) where
    validate (m, t) = (m <= t) && (t - m) <= div n 3
    count (m, t) 'M' = (m+1, t)
    count (m, t) 'T' = (m, t+1)

main = do
    n <- read <$> getLine
    replicateM_ n $ solve <$> (read <$> getLine) <*> getLine >>= putStrLn . bool "NO" "YES"


module Main (formBestBFromA, main) where

import Control.Arrow ((&&&))
import qualified Data.ByteString.Char8 as B
import qualified Data.Char as Char
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Set as Set

-- 0 0 2 1 1 1 0 0 1 1
-- [], {}

-- 0 2 1 1 1 0 0 1 1
-- [1], {}

-- 2 1 1 1 0 0 1 1
-- [1, 1], {}

-- 1 1 1 0 0 1 1
-- [1, 1, 0], {2}

-- 1 1 0 0 1 1
-- [2], {2}
-- [3], {}

-- 1 0 0 1 1
-- [3, 0], {1}

-- 0 0 1 1
-- [3, 0, 0], {1}

-- 0 1 1
-- [3, 1], {1}
-- [3, 2], {}

-- 1 1
-- [3, 2, 1], {}

-- 1
-- [3, 2, 2], {}

--
-- [3, 2, 2, 0], {1}

formBestBFromA :: [Integer] -> [Integer]
formBestBFromA = concat . map (\ (k, n) -> replicate (fromIntegral n) k) . Map.toDescList . fst . List.foldl' updateState (Map.empty, Set.empty)
    where
        updateState (current_bs, unused_elements) new_element
            | Map.member new_element current_bs
                = considerUnusedElements (updateBsWithMex (new_element + 1) current_bs, unused_elements)
            | new_element == 0 = (addOne 1 current_bs, unused_elements)
            | otherwise = (addOne 0 current_bs, Set.insert new_element unused_elements)

        addOne k = Map.insertWith (+) k 1
        minKey = fst . Map.findMin

        dropKeysLower x = until (\ m -> Map.null m || minKey m >= x) Map.deleteMin
        takeKeysHigher x = until (\ m -> Map.null m || minKey m > x) Map.deleteMin
        takeElementsHigher x = until (\ s -> Set.null s || Set.findMin s > x) Set.deleteMin

        updateBsWithMex new_mex = addOne new_mex . dropKeysLower new_mex

        considerUnusedElements (current_b, unused_elements)
            | not (null current_b) && Set.member lastB unused_elements
                = updateState (current_b, new_unused_elements) lastB
            | otherwise = (current_b, new_unused_elements)
            where
                lastB = minKey current_b
                new_unused_elements
                    | null current_b = Set.empty
                    | otherwise = takeElementsHigher lastB unused_elements

-- IO Section --

main :: IO ()
main = B.interact processInput

processInput :: B.ByteString -> B.ByteString
processInput = B.concat . map processTest . takeEverySnd . drop 1 . B.lines

takeEverySnd :: [a] -> [a]
takeEverySnd (x1:x2:xs) = x2 : takeEverySnd xs
takeEverySnd xs = []

processTest :: B.ByteString -> B.ByteString
processTest = outputFromB . formBestBFromA . readIntegers
    where
        outputFromB = B.unlines . pairToList . ((bshow . List.genericLength) &&& (B.unwords . map bshow))
        bshow = B.pack . show
        pairToList (a, b) = [a, b]

readIntegers :: B.ByteString -> [Integer]
readIntegers = List.unfoldr (B.readInteger . B.dropWhile Char.isSpace)

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

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

mainFun :: SP Builder
mainFun = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    n <- getInt
    aLi <- replicateM n getInt
    let
      occs = reverse <$> accumArray (flip (:)) [] (0, n) (zip aLi [1 .. n])
      step :: (Int, Array Int [Int]) -> Maybe (Int, (Int, Array Int [Int]))
      step (j, arr) = if  j == n
        then  Nothing
        else  let
        mex = head [i | (i, []) <- assocs arr]
        j' = foldl' max (j + 1) [head $ arr ! i | i <- [0 .. mex - 1]]
        newArr
          = array (0, mex) [(i, dropWhile (<= j') $ arr ! i) | i <- [0 .. mex]]
        in  Just (mex, (j', newArr))
      ans = unfoldr step (0, occs)
    pure $ putInts [length ans] <> putInts ans

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

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

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

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

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

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

module Main (fromBestBFromA, main) where

import qualified Data.ByteString.Char8 as B

import Data.Char (isSpace)
import Data.List (foldl', unfoldr)
import qualified Data.Map as Map
import qualified Data.Set as Set

-- 0 0 2 1 1 1 0 0 1 1
-- [], {}

-- 0 2 1 1 1 0 0 1 1
-- [1], {}

-- 2 1 1 1 0 0 1 1
-- [1, 1], {}

-- 1 1 1 0 0 1 1
-- [1, 1, 0], {2}

-- 1 1 0 0 1 1
-- [2], {2}
-- [3], {}

-- 1 0 0 1 1
-- [3, 0], {1}

-- 0 0 1 1
-- [3, 0, 0], {1}

-- 0 1 1
-- [3, 1], {1}
-- [3, 2], {}

-- 1 1
-- [3, 2, 1], {}

-- 1
-- [3, 2, 2], {}

--
-- [3, 2, 2, 0], {1}

fromBestBFromA :: [Integer] -> [Integer]
fromBestBFromA = concat . map (\ (k, n) -> replicate (fromIntegral n) k) . Map.toDescList . fst . foldl' updateState (Map.empty, Set.empty)
    where
        updateState (current_bs, unused_elements) new_element
            | Map.member new_element current_bs
                = considerUnusedElements (updateBsWithMex (new_element + 1) current_bs, unused_elements)
            | new_element == 0 = (addOne 1 current_bs, unused_elements)
            | otherwise = (addOne 0 current_bs, Set.insert new_element unused_elements)

        addOne k = Map.insertWith (+) k 1
        minKey = fst . Map.findMin

        dropKeysLower x = until (\ m -> Map.null m || minKey m >= x) Map.deleteMin
        takeKeysHigher x = until (\ m -> Map.null m || minKey m > x) Map.deleteMin
        takeElementsHigher x = until (\ s -> Set.null s || Set.findMin s > x) Set.deleteMin

        updateBsWithMex new_mex = addOne new_mex . dropKeysLower new_mex

        considerUnusedElements (current_b, unused_elements)
            | not (null current_b) && Set.member lastB unused_elements
                = updateState (current_b, new_unused_elements) lastB
            | otherwise = (current_b, new_unused_elements)
            where
                lastB = minKey current_b
                new_unused_elements
                    | null current_b = Set.empty
                    | otherwise = takeElementsHigher lastB unused_elements

-- IO Section --

main :: IO ()
main = B.interact processInput

processInput :: B.ByteString -> B.ByteString
processInput = B.unlines . map processTest . takeEverySnd . drop 1 . B.lines

takeEverySnd :: [a] -> [a]
takeEverySnd (x1:x2:xs) = x2 : takeEverySnd xs
takeEverySnd xs = []

processTest :: B.ByteString -> B.ByteString
processTest = B.unwords . map bshow . fromBestBFromA . readIntegers
    where
        bshow = B.pack . show

readIntegers :: B.ByteString -> [Integer]
readIntegers = unfoldr (B.readInteger . B.dropWhile isSpace)

readInteger :: B.ByteString -> Integer
readInteger s = r
    where [r] = readIntegers s

readInt :: B.ByteString -> Int
readInt = fromInteger . readInteger


import qualified Data.Map as M
import Data.Maybe

chars = ['a'..'z']
main = do
    s <- getLine
    bits <- getLine
    k <- getLine
    let good = [(chars !! i, (if (bits !! i) == '1' then 1 else 0)) | i <- [0..25]]
    let ans = solve s good (read k)
    putStrLn $ show ans

data TrieNode = TrieNode
    { cnt:: Int
    , trans :: M.Map Char TrieNode
    } deriving Show

solve :: String -> [(Char, Int)] -> Int -> Int
solve s good k = solve' s good k (TrieNode 0 M.empty)

solve' :: String -> [(Char, Int)] -> Int -> TrieNode -> Int
solve' [] _ _ _ = 0
solve' s@(c:s') good k p =
        solveSingle s good k p' + solve' s' good k p'
    where p' = insert p s

solveSingle :: String -> [(Char, Int)] -> Int -> TrieNode -> Int
solveSingle s good k p = ans
    where
        (ans, bad, p') = foldl func (0, 0, p) s
        func (ans, bad, p) c = let
            bad' = bad + 1 - (fromJust $ lookup c good)
            ans' = ans + (if bad' <= k && cnt p' == 1 then 1 else 0)
            p' = fromJust $ M.lookup c (trans p)
            in (ans', bad', p')

insert :: TrieNode -> String -> TrieNode
insert p [] = p
insert p (c:s') = p { trans = M.insert c p' (trans p) }
    where
        p' = case M.lookup c (trans p) of
                Nothing -> insert (TrieNode 1 M.empty) s'
                Just pc -> insert (pc { cnt = (cnt pc) + 1 }) s'

import Data.List
import Data.Char (digitToInt)

main = do
    s <- getLine
    t <- getLine
    k <- readLn
    print $ solve (map ((1-) . digitToInt) t) k s

pairwise l@(_:ht) = zip l ht
common pre post = length $ (takeWhile eq) $ zip pre post
    where eq (k1, k2) = k1 == k2

solve t k = sum . (map pair) . pairwise . sort . tails
    where
        bad ch = t !! (fromEnum ch - 97)
        pair (pre, post) = length $ takeWhile (<= k) $ tail accum
            where
                delta = (common pre post)
                stop = sum $ map bad $ take delta post
                accum = scanl (+) stop $ map bad $ drop delta post

{-# OPTIONS_GHC -O2  -funbox-strict-fields #-}

import Data.Array.Base
import qualified Data.Map as M
import Data.List

main = do
  cs <- getLine
  isGood <- fmap(listArray('a','z').map('1'==))getLine
  k <- readLn
  print $ solve k cs isGood

data Trie = Node !Int !(M.Map Char Trie)

solve :: Int -> String -> UArray Char Bool -> Int
solve k cs arr = pred.cnt $ foldl' (flip ins) (Node 0 M.empty) $ tails cs
   where
     isGood c = unsafeAt arr $ fromEnum c - 97

     ins :: String -> Trie -> Trie
     ins (c:cs) (Node cnt f)
       | Just trie <- M.lookup c f = Node cnt (M.insert c (ins cs trie) f)
       | isGood c = Node cnt (M.insert c (ins cs (Node cnt     M.empty)) f)
       | cnt < k  = Node cnt (M.insert c (ins cs (Node (cnt+1) M.empty)) f)
     ins _ trie = trie

     cnt :: Trie -> Int
     cnt (Node _ f) = M.foldr' ((+).cnt) 1 f

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

import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Bits
import qualified Data.ByteString as B
import Data.STRef
import Data.Word

#if __GLASGOW_HASKELL__ < 706
modifySTRef' :: STRef s a -> (a -> a) -> ST s ()
modifySTRef' r f=do x<-readSTRef r;writeSTRef r$!f x
{-# INLINE modifySTRef' #-}
#endif

type Hash = Word32

base1,base2 :: Hash
base1 = 1000000007
base2 =  999999937

mask :: Hash
mask = 0x3fffffff

main = do
  cs <- fmap (map $ fromIntegral.fromEnum) getLine
  isBad <- fmap(listArray('a','z').map(fromEnum.('0'==)))getLine
  k <- readLn
  print $ solve k cs isBad

solve :: Int -> [Hash] -> UArray Char Int -> Int
solve k cs isBad = runST $ do
  res <- newSTRef 0 :: ST s (STRef s Int)
  hashtable1 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)
  hashtable2 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)
  let f ccs@(_:cs) = g 0 0 0 ccs >> f cs
      f [] = readSTRef res
      g !hash1 !hash2 !cnt (c:cs) = do
        let cnt' = (cnt+).unsafeAt isBad $ fromIntegral c - 97
        when (cnt'<=k) $ do
          let !h1 = (hash1 * base1 + c) .&. mask
              !h2 = (hash2 * base2 + c) .&. mask
          flg1 <- unsafeRead hashtable1 $ fromIntegral h1
          flg2 <- unsafeRead hashtable2 $ fromIntegral h2
          unless (flg1 && flg2) $ do
            modifySTRef' res (1+)
            unsafeWrite hashtable1 (fromIntegral h1) True
            unsafeWrite hashtable2 (fromIntegral h2) True
          g h1 h2 cnt' cs
      g _ _ _ _ = return ()
  f cs

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

import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Bits
import qualified Data.ByteString as B
import Data.STRef
import Data.Word

#if __GLASGOW_HASKELL__ < 706
modifySTRef' :: STRef s a -> (a -> a) -> ST s ()
modifySTRef' r f=do x<-readSTRef r;writeSTRef r$!f x
{-# INLINE modifySTRef' #-}
#endif

type Hash = Word32

base1,base2 :: Hash
base1 = 1000000007
base2 = 99991

mask :: Hash
mask = 0x3fffffff

main = do
  cs <- fmap (map $ fromIntegral.fromEnum) getLine
  isBad <- fmap(listArray('a','z').map(fromEnum.('0'==)))getLine
  k <- readLn
  print $ solve k cs isBad

solve :: Int -> [Hash] -> UArray Char Int -> Int
solve k cs isBad = runST $ do
  res <- newSTRef 0 :: ST s (STRef s Int)
  hashtable1 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)
  hashtable2 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)
  let f ccs@(_:cs) = g 0 0 0 ccs >> f cs
      f [] = readSTRef res
      g !hash1 !hash2 !cnt (c:cs) = do
        let cnt' = (cnt+).unsafeAt isBad $ fromIntegral c - 97
        when (cnt'<=k) $ do
          let !h1 = (hash1 * base1 + c) .&. mask
              !h2 = (hash2 * base2 + c) .&. mask
          flg1 <- unsafeRead hashtable1 $ fromIntegral h1
          flg2 <- unsafeRead hashtable2 $ fromIntegral h2
          unless (flg1 && flg2) $ do
            modifySTRef' res (1+)
            unsafeWrite hashtable1 (fromIntegral h1) True
            unsafeWrite hashtable2 (fromIntegral h2) True
          g h1 h2 cnt' cs
      g _ _ _ _ = return ()
  f cs

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

import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Bits
import qualified Data.ByteString as B
import Data.STRef
import Data.Word

#if __GLASGOW_HASKELL__ < 706
modifySTRef' :: STRef s a -> (a -> a) -> ST s ()
modifySTRef' r f=do x<-readSTRef r;writeSTRef r$!f x
{-# INLINE modifySTRef' #-}
#endif

type Hash = Word32

base1,base2 :: Hash
base1 = 1000000007
base2 = 997

mask :: Hash
mask = 0x3fffffff

main = do
  cs <- fmap (map $ fromIntegral.fromEnum) getLine
  isBad <- fmap(listArray('a','z').map(fromEnum.('0'==)))getLine
  k <- readLn
  print $ solve k cs isBad

solve :: Int -> [Hash] -> UArray Char Int -> Int
solve k cs isBad = runST $ do
  res <- newSTRef 0 :: ST s (STRef s Int)
  hashtable1 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)
  hashtable2 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)
  let f ccs@(_:cs) = g 0 0 0 ccs >> f cs
      f [] = readSTRef res
      g !hash1 !hash2 !cnt (c:cs) = do
        let cnt' = (cnt+).unsafeAt isBad $ fromIntegral c - 97
        when (cnt'<=k) $ do
          let !h1 = (hash1 * base1 + c) .&. mask
              !h2 = (hash2 * base2 + c) .&. mask
          flg1 <- unsafeRead hashtable1 $ fromIntegral h1
          flg2 <- unsafeRead hashtable2 $ fromIntegral h2
          unless (flg1 && flg2) $ do
            modifySTRef' res (1+)
            unsafeWrite hashtable1 (fromIntegral h1) True
            unsafeWrite hashtable2 (fromIntegral h2) True
          g h1 h2 cnt' cs
      g _ _ _ _ = return ()
  f cs

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

import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Bits
import qualified Data.ByteString as B
import Data.STRef
import Data.Word

#if __GLASGOW_HASKELL__ < 706
modifySTRef' :: STRef s a -> (a -> a) -> ST s ()
modifySTRef' r f=do x<-readSTRef r;writeSTRef r$!f x
{-# INLINE modifySTRef' #-}
#endif

type Hash = Word32

base1,base2 :: Hash
base1 = 1000000007
base2 = 1000000009

mask :: Hash
mask = 0x1fffffff

main = do
  cs <- fmap (map $ fromIntegral.fromEnum) getLine
  isBad <- fmap(listArray('a','z').map(fromEnum.('0'==)))getLine
  k <- readLn
  print $ solve k cs isBad

solve :: Int -> [Hash] -> UArray Char Int -> Int
solve k cs isBad = runST $ do
  res <- newSTRef 0 :: ST s (STRef s Int)
  hashtable1 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)
  hashtable2 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)
  let f ccs@(_:cs) = g 0 0 0 ccs >> f cs
      f [] = readSTRef res
      g !hash1 !hash2 !cnt (c:cs) = do
        let cnt' = (cnt+).unsafeAt isBad $ fromIntegral c - 97
        when (cnt'<=k) $ do
          let !h1 = (hash1 * base1 + c) .&. mask
              !h2 = (hash2 * base2 + c) .&. mask
          flg1 <- unsafeRead hashtable1 $ fromIntegral h1
          flg2 <- unsafeRead hashtable2 $ fromIntegral h2
          unless (flg1 && flg2) $ do
            modifySTRef' res (1+)
            unsafeWrite hashtable1 (fromIntegral h1) True
            unsafeWrite hashtable2 (fromIntegral h2) True
          g h1 h2 cnt' cs
      g _ _ _ _ = return ()
  f cs

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

import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Bits
import qualified Data.ByteString as B
import Data.STRef
import Data.Word

#if __GLASGOW_HASKELL__ < 706
modifySTRef' :: STRef s a -> (a -> a) -> ST s ()
modifySTRef' r f=do x<-readSTRef r;writeSTRef r$!f x
{-# INLINE modifySTRef' #-}
#endif

type Hash = Word32

base1,base2 :: Hash
base1 = 1000000007
base2 = 100000007

mask :: Hash
mask = 0x3fffffff

main = do
  cs <- fmap (map $ fromIntegral.fromEnum) getLine
  isBad <- fmap(listArray('a','z').map(fromEnum.('0'==)))getLine
  k <- readLn
  print $ solve k cs isBad

solve :: Int -> [Hash] -> UArray Char Int -> Int
solve k cs isBad = runST $ do
  res <- newSTRef 0 :: ST s (STRef s Int)
  hashtable1 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)
  hashtable2 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)
  let f ccs@(_:cs) = g 0 0 0 ccs >> f cs
      f [] = readSTRef res
      g !hash1 !hash2 !cnt (c:cs) = do
        let cnt' = (cnt+).unsafeAt isBad $ fromIntegral c - 97
        when (cnt'<=k) $ do
          let !h1 = (hash1 * base1 + c) .&. mask
              !h2 = (hash2 * base2 + c) .&. mask
          flg1 <- unsafeRead hashtable1 $ fromIntegral h1
          flg2 <- unsafeRead hashtable2 $ fromIntegral h2
          unless (flg1 && flg2) $ do
            modifySTRef' res (1+)
            unsafeWrite hashtable1 (fromIntegral h1) True
            unsafeWrite hashtable2 (fromIntegral h2) True
          g h1 h2 cnt' cs
      g _ _ _ _ = return ()
  f cs


import Control.Arrow ((***))

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

solve :: [[Int]] -> Int
solve [[n], ds, [s, t]] | s == t = 0
                        | otherwise = uncurry min $ (sum *** sum) $ splitAt (max s t - min s t)
                                    $ take n $ drop (min s t - 1) $ ds ++ ds
solve _ = undefined

import Control.Arrow ((***))

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

solve :: [[Int]] -> Int
solve [[n], ds, [s, t]]
  | s == t = 0
  | otherwise = uncurry min $ (sum *** sum) $ splitAt (max s t - min s t)
              $ take n $ drop (min s t - 1) $ cycle ds
solve _ = undefined

main = do
    getLine
    d <- fmap (map read . words) getLine
    [s, t] <- fmap (map read . words) getLine
    print $ solve d s t
solve d s t | s == t = 0
            | s > t = solve d t s
            | s < t = min fwdWay $ sum d - fwdWay
            where fwdWay = forward d s t
forward d s t = sum . take (t-s) . drop (s-1) $ d

import Data.List
main=interact$show.f.map read.words
f(n:tmp) = min d $ sum ds - d
   where
     (ds,st) = splitAt n tmp
     [s,t] = sort st
     d = sum.take(t-s)$drop(s-1)ds

module Main where

import Data.List

main = do
     distances <- getLine >> getLine >>= (return . map read . words) :: IO [Int]
     [s1, s2] <- getLine >>= (return . sort . map read . words) :: IO [Int]
     let total = sum distances
         dist = sum $ drop (s1 - 1) $ take (s2 - 1) distances
     print $ min dist (total - dist)

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

main= do
	getLine
	t<- map read. words <$> getLine::IO [Int]
	x<- map read.words <$> getLine::IO [Int]
	let s= minimum x
	let e = maximum x
	let ans1 = sum $ take (e-s) $ drop (s-1) t
	let ans2 = (sum t)- ans1
	print $ min ans1 ans2

import Control.Monad
import Data.List

main = getLine >>  replicateM 2 getLine
               >>= return . map (map read . words)
               >>= putStrLn . show . solve

solve :: [[Int]] -> Int
solve [ds, (a:b:ot)] = min ar $ foldl1 (+) ds - ar
            where ar = foldl (+) 0 $ clip (pred a) (pred b) ds

clip :: Int -> Int -> [a] -> [a]
clip a b = drop from . take to
  where from = min a b
        to   = max a b

main = do
	n<-getLine
	ds<-getLine
	st<-getLine
	let [s,t] = map read $ words st
	putStrLn $ show $ solve (read n) (map read (words ds)) s t

solve::Int->[Int]->Int->Int->Int
solve n d s t | s==t = 0
              | otherwise = min (sum $ drop (min s t -1) $ take (max s t-1)  d) (sum $ take (min s t-1) d ++ drop (max s t-1) d)
                where dist = abs (s-t)

import Data.List

main :: IO ()
main = interact $ show . solve . map (map read . words) . lines

solve :: [[Int]] -> Int
solve (_ : ds : st : _) = min a b
  where
  (s : t : _) = sort st
  a = sum $ drop (s - 1) $ take (t - 1) ds
  b = sum ds - a

module Main (
    main
) where

import Data.List

solve nums s t =
    let hs = take s nums in
    let ts = drop t nums in
    let ms = drop s (take t nums) in
    let sum1 = sum hs + sum ts in
    let sum2 = sum ms in
    min sum1 sum2

main = do
    getLine
    numsStr <- getLine
    let nums = map read $ words numsStr
    stStr <- getLine
    let [s,t] = sort $ map read $ words stStr
    print (solve nums (s-1) (t-1))

import Control.Monad (liftM)
import Data.List (nub)
import Prelude hiding (reads)

reads :: Read a => IO [a]
reads  =  liftM (map read . words) getLine

solve :: Int -> Int -> [Int] -> Int
solve s t xs  =  min a b
  where
    a  =  sum $ drop (s - 1) $ take (t - 1) xs
    b  =  sum xs - a

main :: IO ()
main  =  do
    getLine
    xs  <-  reads
    [t, s]  <-  reads
    print $ solve (min t s) (max t s) xs

-- Codeforces 278A

import Data.List

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    path <- fmap (map read . words) getLine :: IO [Int]
    aim <- fmap (map read . words) getLine :: IO [Int]
    print $ solve n (concat $ replicate 2 path) (sort aim) where
        solve n xs [s, t] = min (len s t) (len t (s+n)) where
            len a b = sum $ take (b-a) $ drop (a-1) xs

import Control.Applicative

parseLine = map read . words <$> getLine

main = do
  n <- read <$> getLine
  xs <- parseLine
  [x,y] <- parseLine
  let cyc = cycle xs
      (mn,mx) = (min x y, max x y)
      n1 = sum . take (mx-mn) . drop (mn-1)   $ cyc
      n2 = sum . take (n+mn-mx) . drop (mx-1) $ cyc
  print $ min n1 n2

module Main (
    main
) where

import Data.List

solve nums s t =
    let hs = take s nums in
    let ts = drop t nums in
    let ms = drop s (take t nums) in
    let sum1 = sum hs + sum ts in
    let sum2 = sum ms in
    min sum1 sum2

main = do
    getLine
    numsStr <- getLine
    let nums = map read $ words numsStr
    stStr <- getLine
    let [s,t] = map read $ words stStr
    print (solve nums (s-1) (t-1))

import Control.Arrow ((***))

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

solve :: [[Int]] -> Int
solve [[n], ds, [s, t]] | s == t = 0
                        | otherwise = uncurry min $ (sum *** sum) $ splitAt (max s t - min s t)
                                    $ take (min s t + n - 1) $ drop (min s t - 1) $ ds ++ ds
solve _ = undefined

import Data.List (unfoldr)

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

solve :: [[Int]] -> Int
solve [[n], ds, [s, t]] | s == t = 0
                        | otherwise = minimum $ map sum $ splitN (max s t - 1)
                                    $ take (min s t + n - 1) $ drop (min s t - 1) $ ds ++ ds
solve _ = undefined

splitN :: Int -> [a] -> [[a]]
splitN n = takeWhile (not . null) . unfoldr (Just . splitAt n)

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

main= do
	getLine
	t<- map read. words <$> getLine::IO [Int]
	x<- map read.words <$> getLine::IO [Int]
	let s= minimum x
	let e = maximum x
	let ans1 = sum $ take (e-1) $ drop (s-1) t
	let ans2 = (sum t)- ans1
	print $ min ans1 ans2


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

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

transform :: String -> String -> Int -> (Ordering, Int)
transform "Y" ">=" x = (GT, x-1)
transform "N" ">=" x = (LT, x)
transform "Y" "<=" x = (LT, x+1)
transform "N" "<=" x = (GT, x)
transform "Y" ">" x = (GT, x)
transform "N" ">" x = (LT, x+1)
transform "Y" "<" x = (LT, x)
transform "N" "<" x = (GT, x-1)
transform _ _ _ = undefined

main :: IO ()
main = do
  n <- readInt <$> C.getLine
  array <- replicateM n $ do
    [symbol, x, ans] <- C.words <$> C.getLine
    return $ transform (C.unpack ans) (C.unpack symbol) (readInt x)
  let lt = [y | (x,y) <- array, x == LT]
      gt = [y | (x,y) <- array, x == GT]
      ltmi = minimum lt
      gtmx = maximum gt
  if null lt then print $ gtmx + 1
  else if null gt then print $ ltmi - 1
  else if ltmi - 1 > gtmx then print $ ltmi - 1
  else putStrLn "Impossible"

{-# LANGUAGE MultiWayIf #-}

import Control.Monad

data Compare = LE | GE

data Query = Q Compare Int

apply :: (Int,Int) -> Query -> Maybe (Int,Int)
apply (lo,hi) (Q LE val)
  | val < lo  = Nothing
  | otherwise = Just (lo, min val hi)
apply (lo,hi) (Q GE val)
  | val > hi = Nothing
  | otherwise = Just (max lo val, hi)

complement :: Query -> Query
complement (Q LE v) = Q GE (v+1)
complement (Q GE v) = Q LE (v-1)

readQuery :: String -> Query
readQuery str =
  let (op:vs:bs:_) = words str
      v = read vs
      q1 = if | op == ">=" -> Q GE v
              | op == "<=" -> Q LE v
              | op == ">"  -> Q GE (v+1)
              | op == "<"  -> Q LE (v-1)
      q2 = if bs == "Y" then q1 else complement q1
  in q2

main = do
  n <- fmap read getLine
  queries <- replicateM n $ do fmap readQuery getLine
  let inf = 2*10^9 :: Int
  let loop r []     = Just r
      loop r (q:qs) = case apply r q of
                        Nothing -> Nothing
                        Just r' -> loop r' qs
      r = loop (-inf,inf) queries
  case r of
    Nothing      -> putStrLn "Impossible"
    Just (lo,hi) -> putStrLn $ show hi

import Control.Applicative
import Control.Monad
import Data.Maybe (fromJust)

data InequalitySign = LARGERT | SMALLERT | LTE | STE
                    deriving (Eq)

reverseSign LARGERT = STE
reverseSign SMALLERT = LTE
reverseSign LTE = SMALLERT
reverseSign STE = LARGERT

toInequality ">" = LARGERT
toInequality "<" = SMALLERT
toInequality ">=" = LTE
toInequality "<=" = STE

translate [a,b,c] = if c == "Y" then (i, read b) else (reverseSign i, read b)
  where i = toInequality a

main = do
  n <- readLn
  xs <- replicateM n (translate . words <$> getLine)
  let
    f [] (lb,ub) = if lb < ub then Just (lb, ub) else Nothing
    f ((i,x):ys) (lb,ub)
      | i == LARGERT = if x-1 >= ub
                  then Nothing
                  else f ys (max (x+1) lb, ub)
      | i == SMALLERT = if x <= lb
                  then Nothing
                  else f ys (lb, min x ub)
      | i == LTE = if x >= ub
                   then Nothing
                   else f ys (max x lb, ub)
      | i == STE = if x < lb
                   then Nothing
                   else f ys (lb, min (x+1) ub)
    b = f xs (-1000000010, 1000000010)
    result = if b == Nothing then "Impossible" else show . fst $ fromJust b
    in putStrLn $ result

import Control.Monad
import Data.Maybe

solve :: [String] -> Maybe Int
solve ss = if l > r then Nothing
                    else Just l
    where (l, r) = hlp (-2*10^9, 2*10^9) ss
          hlp :: (Int, Int) -> [String] -> (Int, Int)
          hlp (a, b) [] = (a, b)
          hlp (a, b) (s:ts) =
              if ((sgn == ">=") && (ans == "Y")) || ((sgn == "<") && (ans == "N")) then
                  if n > a then hlp (n, b) ts
                           else hlp (a, b) ts
              else if ((sgn == "<=") && (ans == "Y")) || ((sgn == ">") && (ans == "N")) then
                  if n < b then hlp (a, n) ts
                           else hlp (a, b) ts
              else if ((sgn == "<") && (ans == "Y")) || ((sgn == ">=") && (ans == "N")) then
                  if n-1 < b then hlp (a, n-1) ts
                             else hlp (a, b) ts
              else if ((sgn == ">") && (ans == "Y")) || ((sgn == "<=") && (ans == "N")) then
                  if n+1 > a then hlp (n+1, b) ts
                             else hlp (a, b) ts
              else (a, b)
              where [sgn, n', ans] = words s
                    n = read n'

main = do
    n <- fmap read getLine
    lst <- forM [1..n] (\_ -> getLine)
    let solution = solve lst
    if isNothing solution then putStrLn "Impossible"
                          else print (fromJust solution)

{-# LANGUAGE BangPatterns #-}
main=interact$maybe "Impossible" show.solve.parse.tail.words

solve :: [Either Int Int] -> Maybe Int
solve xs = go (-2000000000) 2000000000 xs
   where
     go !l !r (Left i:xs) = go (max l i) r xs
     go !l !r (Right i:xs) = go l (min r i) xs
     go !l !r []
       | l <= r = Just l
       | otherwise = Nothing

parse :: [String] -> [Either Int Int]
parse (">":i:"Y":cs) = Left (read i+1) : parse cs
parse (">=":i:"Y":cs) = Left (read i) : parse cs
parse ("<":i:"Y":cs) = Right (read i-1) : parse cs
parse ("<=":i:"Y":cs) = Right (read i) : parse cs
parse (">":i:"N":cs) = parse ("<=":i:"Y":cs)
parse (">=":i:"N":cs) = parse ("<":i:"Y":cs)
parse ("<":i:"N":cs) = parse (">=":i:"Y":cs)
parse ("<=":i:"N":cs) = parse (">":i:"Y":cs)
parse _ = []

import Data.Maybe

data Var = Gt

process :: Integer -> Integer -> [[String]] -> Maybe Integer
process a b _ | a > b = Nothing
process a _ [] = Just a
process a b ((sign:x:"N":[]):other_lines) = process a b ((oposite sign:x:"Y":[]):other_lines)

process a b ((">=":x:"Y":[]):other_lines) = process (max a $ read x) b other_lines
process a b ((">":x:"Y":[]):other_lines) = process (max a $ 1 + read x) b other_lines
process a b (("<":x:"Y":[]):other_lines) = process a (min b $ -1 + read x) other_lines
process a b (("<=":x:"Y":[]):other_lines) = process a (min b $ read x) other_lines

oposite ">=" = "<"
oposite "<=" = ">"
oposite "<" = ">="
oposite ">" = "<="

main = do
        n <- read `fmap` getLine
        my_lines <- sequence $ replicate n getLine

        let
            res = process (-2000000000) 2000000000 (map words my_lines)

        putStrLn $ if res == Nothing then "Impossible" else show $ fromJust res

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections, BangPatterns, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
-- hiding clauses are to allow Data.Foldable's generalizations
import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)
import Control.Monad.ST

import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (ByteString)
import Data.Bits
import Data.Char
import Data.Either
import Data.Foldable
import Data.Function
import Data.IORef
import Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Traversable
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
import System.IO
-- }}}
-- silly utilities {{{
-- stolen from lens:
a & f = f a
a <&> f = fmap f a
infixl 1 &, <&>

fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)
-- }}}
-- input and output {{{
bsGetLine :: IO ByteString
bsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine

inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]

ssUnwords :: [ShowS] -> ShowS
ssUnwords [] = id
ssUnwords (x:xs) = x . (' ':) . ssUnwords xs

ssUnlines :: [ShowS] -> ShowS
ssUnlines [] = id
ssUnlines (x:xs) = x . ('\n':) . ssUnlines xs

showMany :: (Show a) => [a] -> String
showMany xs = ssUnwords (map shows xs) ""
showMatrix :: (Show a) => [[a]] -> String
showMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) ""

printMany :: (Show a) => [a] -> IO ()
printMany xs = putStrLn (showMany xs)
printMatrix :: (Show a) => [[a]] -> IO ()
printMatrix xs = putStr (showMatrix xs)
-- }}}

data Answer = Lt !Int | Geq !Int

neg :: Answer -> Answer
neg (Lt a) = Geq a
neg (Geq a) = Lt a

inputAnswer :: IO Answer
inputAnswer = do
	[sign, ns, ts] <- words <$> getLine
	let n :: Int = read ns
	let t = ts == "Y"
	let ans = case sign of
		">=" -> Geq n
		"<" -> Lt n
		">" -> Geq (n + 1)
		"<=" -> Lt (n + 1)
	return $ if t then ans else neg ans

solve :: [Answer] -> Maybe Int
solve = go (-2^30, 2^30)
	where
		go (a,b) [] | a < b = Just a
		go (a,b) (Lt x : xs) = go (a, min b x) xs
		go (a,b) (Geq x : xs) = go (max a x, b) xs
		go _ _ = Nothing

main :: IO ()
main = do
	n <- inputInt
	a <- replicateM n inputAnswer
	case solve a of
		Just x -> print x
		Nothing -> putStrLn "Impossible"

{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as C

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

normalize :: C.ByteString -> C.ByteString -> Int -> (Ordering, Int)
normalize "Y" ">"  x = (GT, x)
normalize "Y" "<"  x = (LT, x)
normalize "Y" ">=" x = (GT, x - 1)
normalize "Y" "<=" x = (LT, x + 1)
normalize "N" ">"  x = (LT, x + 1)
normalize "N" "<"  x = (GT, x - 1)
normalize "N" ">=" x = (LT, x)
normalize "N" "<=" x = (GT, x)
normalize _ _ _ = undefined

main :: IO ()
main = do
  n <- readInt <$> C.getLine
  qna <- replicateM n $ do
    [sign, x, answer] <- C.words <$> C.getLine
    return $ normalize answer sign $ readInt x
  let gt = [j | (i, j) <- qna, i == GT]
      lt = [j | (i, j) <- qna, i == LT]
      gtmax = maximum gt
      ltmin = minimum lt
  if null gt then print $ ltmin - 1
  else if null lt || gtmax + 1 <= ltmin - 1 then print $ gtmax + 1
  else putStrLn "Impossible"

main=interact$maybe "Impossible" show.solve.parse.tail.words

solve :: [Either Int Int] -> Maybe Int
solve xs = go (-2000000000) 2000000000 xs
   where
     go l r (Left i:xs) = go (max l i) r xs
     go l r (Right i:xs) = go l (min r i) xs
     go l r []
       | l <= r = Just l
       | otherwise = Nothing

parse :: [String] -> [Either Int Int]
parse (">":i:"Y":cs) = Left (read i+1) : parse cs
parse (">=":i:"Y":cs) = Left (read i) : parse cs
parse ("<":i:"Y":cs) = Right (read i-1) : parse cs
parse ("<=":i:"Y":cs) = Right (read i) : parse cs
parse (">":i:"N":cs) = parse ("<=":i:"Y":cs)
parse (">=":i:"N":cs) = parse ("<":i:"Y":cs)
parse ("<":i:"N":cs) = parse (">=":i:"Y":cs)
parse ("<=":i:"N":cs) = parse (">":i:"Y":cs)
parse _ = []

{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as C

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

normalize :: C.ByteString -> C.ByteString -> Int -> (Ordering, Int)
normalize "Y" ">"  x = (GT, x)
normalize "Y" "<"  x = (LT, x)
normalize "Y" ">=" x = (GT, x + 1)
normalize "Y" "<=" x = (LT, x - 1)
normalize "N" ">"  x = (LT, x + 1)
normalize "N" "<"  x = (GT, x - 1)
normalize "N" ">=" x = (LT, x)
normalize "N" "<=" x = (GT, x)
normalize _ _ _ = undefined

main :: IO ()
main = do
  n <- readInt <$> C.getLine
  qna <- replicateM n $ do
    [sign, x, answer] <- C.words <$> C.getLine
    return $ normalize answer sign $ readInt x
  let gt = [j | (i, j) <- qna, i == GT]
      lt = [j | (i, j) <- qna, i == LT]
      gtmax = maximum gt
      ltmin = minimum lt
  if null gt then print $ ltmin - 1
  else if null lt || gtmax + 1 <= ltmin - 1 then print $ gtmax + 1
  else putStrLn "Impossible"

{-# LANGUAGE MultiWayIf #-}

import Control.Monad

data Compare = LE | GE

data Query = Q Compare Int

apply :: (Int,Int) -> Query -> Maybe (Int,Int)
apply (lo,hi) (Q LE val)
  | val < lo  = Nothing
  | otherwise = Just (lo, min val hi)
apply (lo,hi) (Q GE val)
  | val > hi = Nothing
  | otherwise = Just (max lo val, hi)

complement :: Query -> Query
complement (Q LE v) = Q GE (v+1)
complement (Q GE v) = Q LE (v-1)

readQuery :: String -> Query
readQuery str =
  let (op:vs:bs:_) = words str
      v = read vs
      q1 = if | op == ">=" -> Q GE v
              | op == "<=" -> Q LE v
              | op == ">"  -> Q GE (v+1)
              | op == "<"  -> Q LE (v-1)
      q2 = if bs == "Y" then q1 else complement q1
  in q2

main = do
  n <- fmap read getLine
  queries <- replicateM n $ do fmap readQuery getLine
  let inf = 10^9 :: Int
  let loop r []     = Just r
      loop r (q:qs) = case apply r q of
                        Nothing -> Nothing
                        Just r' -> loop r' qs
      r = loop (-inf,inf) queries
  case r of
    Nothing      -> putStrLn "Impossible"
    Just (lo,hi) -> putStrLn $ show (min hi 2*10^9)

{-# LANGUAGE MultiWayIf #-}

import Control.Monad

data Compare = LE | GE

data Query = Q Compare Int

apply :: (Int,Int) -> Query -> Maybe (Int,Int)
apply (lo,hi) (Q LE val)
  | val < lo  = Nothing
  | otherwise = Just (lo, min val hi)
apply (lo,hi) (Q GE val)
  | val > hi = Nothing
  | otherwise = Just (max lo val, hi)

complement :: Query -> Query
complement (Q LE v) = Q GE (v+1)
complement (Q GE v) = Q LE (v-1)

readQuery :: String -> Query
readQuery str =
  let (op:vs:bs:_) = words str
      v = read vs
      q1 = if | op == ">=" -> Q GE v
              | op == "<=" -> Q LE v
              | op == ">"  -> Q GE (v+1)
              | op == "<"  -> Q LE (v-1)
      q2 = if bs == "Y" then q1 else complement q1
  in q2

main = do
  n <- fmap read getLine
  queries <- replicateM n $ do fmap readQuery getLine
  let inf = 10^9 :: Int
  let loop r []     = Just r
      loop r (q:qs) = case apply r q of
                        Nothing -> Nothing
                        Just r' -> loop r' qs
      r = loop (-inf,inf) queries
  case r of
    Nothing      -> putStrLn "Impossible"
    Just (lo,hi) -> putStrLn $ show (min hi (2*10^9))

import Control.Applicative
import Control.Monad
import Data.Maybe (fromJust)

data InequalitySign = LARGERT | SMALLERT | LTE | STE
                    deriving (Eq)

reverseSign LARGERT = STE
reverseSign SMALLERT = LTE
reverseSign LTE = SMALLERT
reverseSign STE = LARGERT

toInequality ">" = LARGERT
toInequality "<" = SMALLERT
toInequality ">=" = LTE
toInequality "<=" = STE

translate [a,b,c] = if c == "Y" then (i, read b) else (reverseSign i, read b)
  where i = toInequality a

main = do
  n <- readLn
  xs <- replicateM n (translate . words <$> getLine)
  let
    f [] bound = Just bound
    f ((i,x):ys) (lb,ub)
      | i == LARGERT = if x-1 >= ub
                  then Nothing
                  else f ys (max (x-1) lb, ub)
      | i == SMALLERT = if x <= lb
                  then Nothing
                  else f ys (lb, min x ub)
      | i == LTE = if x >= ub
                   then Nothing
                   else f ys (max x lb, ub)
      | i == STE = if x < lb
                   then Nothing
                   else f ys (lb, min (x+1) ub)
    b = f xs (-1000000000, 1000000001)
    result = if b == Nothing then "Impossible" else show . fst $ fromJust b
    in putStrLn $ result

import Control.Applicative
import Control.Monad
import Data.Maybe (fromJust)

data InequalitySign = LARGERT | SMALLERT | LTE | STE
                    deriving (Eq)

reverseSign LARGERT = STE
reverseSign SMALLERT = LTE
reverseSign LTE = SMALLERT
reverseSign STE = LARGERT

toInequality ">" = LARGERT
toInequality "<" = SMALLERT
toInequality ">=" = LTE
toInequality "<=" = STE

translate [a,b,c] = if c == "Y" then (i, read b) else (reverseSign i, read b)
  where i = toInequality a

main = do
  n <- readLn
  xs <- replicateM n (translate . words <$> getLine)
  let
    f [] bound = Just bound
    f ((i,x):ys) (lb,ub)
      | i == LARGERT = if x-1 >= ub
                  then Nothing
                  else f ys (max (x+1) lb, ub)
      | i == SMALLERT = if x <= lb
                  then Nothing
                  else f ys (lb, min x ub)
      | i == LTE = if x >= ub
                   then Nothing
                   else f ys (max x lb, ub)
      | i == STE = if x < lb
                   then Nothing
                   else f ys (lb, min (x+1) ub)
    b = f xs (-1000000000, 1000000001)
    result = if b == Nothing then "Impossible" else show . fst $ fromJust b
    in putStrLn $ result

import Control.Applicative
import Control.Monad
import Data.Maybe (fromJust)

data InequalitySign = LARGERT | SMALLERT | LTE | STE
                    deriving (Eq)

reverseSign LARGERT = STE
reverseSign SMALLERT = LTE
reverseSign LTE = SMALLERT
reverseSign STE = LARGERT

toInequality ">" = LARGERT
toInequality "<" = SMALLERT
toInequality ">=" = LTE
toInequality "<=" = STE

translate [a,b,c] = if c == "Y" then (i, read b) else (reverseSign i, read b)
  where i = toInequality a

main = do
  n <- readLn
  xs <- replicateM n (translate . words <$> getLine)
  let
    f [] bound = Just bound
    f ((i,x):ys) (lb,ub)
      | i == LARGERT = if x-1 >= ub
                  then Nothing
                  else f ys (max (x+1) lb, ub)
      | i == SMALLERT = if x <= lb
                  then Nothing
                  else f ys (lb, min x ub)
      | i == LTE = if x >= ub
                   then Nothing
                   else f ys (max x lb, ub)
      | i == STE = if x < lb
                   then Nothing
                   else f ys (lb, min (x+1) ub)
    b = f xs (-1000000010, 1000000010)
    result = if b == Nothing then "Impossible" else show . fst $ fromJust b
    in putStrLn $ result

import Control.Monad
import Data.Maybe

solve :: [String] -> Maybe Int
solve ss = if l > r then Nothing
                    else Just l
    where (l, r) = hlp (-10^9, 10^9) ss
          hlp :: (Int, Int) -> [String] -> (Int, Int)
          hlp (a, b) [] = (a, b)
          hlp (a, b) (s:ts) =
              if ((sgn == ">=") && (ans == "Y")) || ((sgn == "<") && (ans == "N")) then
                  if n > a then hlp (n, b) ts
                           else hlp (a, b) ts
              else if ((sgn == "<=") && (ans == "Y")) || ((sgn == ">") && (ans == "N")) then
                  if n < b then hlp (a, n) ts
                           else hlp (a, b) ts
              else if ((sgn == "<") && (ans == "Y")) || ((sgn == ">=") && (ans == "N")) then
                  if n-1 < b then hlp (a, n-1) ts
                             else hlp (a, b) ts
              else if ((sgn == ">") && (ans == "Y")) || ((sgn == "<=") && (ans == "N")) then
                  if n+1 > a then hlp (n+1, b) ts
                             else hlp (a, b) ts
              else (a, b)
              where [sgn, n', ans] = words s
                    n = read n'

main = do
    n <- fmap read getLine
    lst <- forM [1..n] (\_ -> getLine)
    let solution = solve lst
    if isNothing solution then putStrLn "Impossible"
                          else print (fromJust solution)

import Control.Monad
import Data.Maybe

solve :: [String] -> Maybe Int
solve ss = if l > r then Nothing
                    else Just l
    where (l, r) = hlp (-10^9, 10^9) ss
          hlp :: (Int, Int) -> [String] -> (Int, Int)
          hlp (a, b) [] = (a, b)
          hlp (a, b) (s:ts) =
              if ((sgn == ">=") && (ans == "Y")) || ((sgn == "<") && (ans == "N")) then
                  if n > a then hlp (n, b) ts
                           else hlp (a, b) ts
              else if ((sgn == "<=") && (ans == "Y")) || ((sgn == ">") && (ans == "N")) then
                  if n < b then hlp (a, n) ts
                           else hlp (a, b) ts
              else if ((sgn == "<") && (ans == "Y")) || ((sgn == ">=") && (ans == "N")) then
                  if n-1 < b then hlp (a, n-1) ts
                             else hlp (a, b) ts
              else if ((sgn == ">") && (ans == "Y")) || ((sgn == "<=") && (ans == "N")) then
                  if n-1 > a then hlp (n-1, b) ts
                             else hlp (a, b) ts
              else (a, b)
              where [sgn, n', ans] = words s
                    n = read n'

main = do
    n <- fmap read getLine
    lst <- forM [1..n] (\_ -> getLine)
    let solution = solve lst
    if isNothing solution then putStrLn "Impossible"
                          else print (fromJust solution)

import Data.Maybe

data Var = Gt

process :: Integer -> Integer -> [[String]] -> Maybe Integer
process a b _ | a > b = Nothing
process a _ [] = Just a
process a b ((sign:x:"N":[]):other_lines) = process a b ((oposite sign:x:"Y":[]):other_lines)

process a b ((">=":x:"Y":[]):other_lines) = process (read x) b other_lines
process a b ((">":x:"Y":[]):other_lines) = process (1 + read x) b other_lines
process a b (("<":x:"Y":[]):other_lines) = process a (-1 + read x) other_lines
process a b (("<=":x:"Y":[]):other_lines) = process a (read x) other_lines

oposite ">=" = "<"
oposite "<=" = ">"
oposite "<" = ">="
oposite ">" = "<="

main = do
        n <- read `fmap` getLine
        my_lines <- sequence $ replicate n getLine

        let
            res = process (-2000000000) 2000000000 (map words my_lines)

        putStrLn $ if res == Nothing then "Impossible" else show $ fromJust res

import Data.Maybe

data Var = Gt

process :: Int -> Int -> [[String]] -> Maybe Int
process a b _ | a > b = Nothing
process a _ [] = Just a
process a b ((sign:x:"N":[]):other_lines) = process a b ((oposite sign:x:"Y":[]):other_lines)

process a b ((">=":x:"Y":[]):other_lines) = process (read x) b other_lines
process a b ((">":x:"Y":[]):other_lines) = process (1 + read x) b other_lines
process a b (("<":x:"Y":[]):other_lines) = process a (-1 + read x) other_lines
process a b (("<=":x:"Y":[]):other_lines) = process a (read x) other_lines

oposite ">=" = "<"
oposite "<=" = ">"
oposite "<" = ">="
oposite ">" = "<="

main = do
        n <- read `fmap` getLine
        my_lines <- sequence $ replicate n getLine

        let
            res = process (-2000000000) 2000000000 (map words my_lines)

        putStrLn $ if res == Nothing then "Impossible" else show $ fromJust res

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections, BangPatterns, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
-- hiding clauses are to allow Data.Foldable's generalizations
import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)
import Control.Monad.ST

import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (ByteString)
import Data.Bits
import Data.Char
import Data.Either
import Data.Foldable
import Data.Function
import Data.IORef
import Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Traversable
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
import System.IO
-- }}}
-- silly utilities {{{
-- stolen from lens:
a & f = f a
a <&> f = fmap f a
infixl 1 &, <&>

fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)
-- }}}
-- input and output {{{
bsGetLine :: IO ByteString
bsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine

inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]

ssUnwords :: [ShowS] -> ShowS
ssUnwords [] = id
ssUnwords (x:xs) = x . (' ':) . ssUnwords xs

ssUnlines :: [ShowS] -> ShowS
ssUnlines [] = id
ssUnlines (x:xs) = x . ('\n':) . ssUnlines xs

showMany :: (Show a) => [a] -> String
showMany xs = ssUnwords (map shows xs) ""
showMatrix :: (Show a) => [[a]] -> String
showMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) ""

printMany :: (Show a) => [a] -> IO ()
printMany xs = putStrLn (showMany xs)
printMatrix :: (Show a) => [[a]] -> IO ()
printMatrix xs = putStr (showMatrix xs)
-- }}}

data Answer = Lt !Int | Geq !Int

neg :: Answer -> Answer
neg (Lt a) = Geq a
neg (Geq a) = Lt a

inputAnswer :: IO Answer
inputAnswer = do
	[sign, ns, ts] <- words <$> getLine
	let n :: Int = read ns
	let t = ts == "Y"
	let ans = case sign of
		">=" -> Geq n
		"<" -> Lt n
		">" -> Geq (n + 1)
		"<=" -> Lt (n + 1)
	return $ if t then ans else neg ans

solve :: [Answer] -> Maybe Int
solve = go (-10^9, 10^9)
	where
		go (a,b) [] | a < b = Just a
		go (a,b) (Lt x : xs) = go (a, min b x) xs
		go (a,b) (Geq x : xs) = go (max a x, b) xs
		go _ _ = Nothing

main :: IO ()
main = do
	n <- inputInt
	a <- replicateM n inputAnswer
	case solve a of
		Just x -> print x
		Nothing -> putStrLn "Impossible"

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections, BangPatterns, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
-- hiding clauses are to allow Data.Foldable's generalizations
import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)
import Control.Monad.ST

import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (ByteString)
import Data.Bits
import Data.Char
import Data.Either
import Data.Foldable
import Data.Function
import Data.IORef
import Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Traversable
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
import System.IO
-- }}}
-- silly utilities {{{
-- stolen from lens:
a & f = f a
a <&> f = fmap f a
infixl 1 &, <&>

fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)
-- }}}
-- input and output {{{
bsGetLine :: IO ByteString
bsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine

inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]

ssUnwords :: [ShowS] -> ShowS
ssUnwords [] = id
ssUnwords (x:xs) = x . (' ':) . ssUnwords xs

ssUnlines :: [ShowS] -> ShowS
ssUnlines [] = id
ssUnlines (x:xs) = x . ('\n':) . ssUnlines xs

showMany :: (Show a) => [a] -> String
showMany xs = ssUnwords (map shows xs) ""
showMatrix :: (Show a) => [[a]] -> String
showMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) ""

printMany :: (Show a) => [a] -> IO ()
printMany xs = putStrLn (showMany xs)
printMatrix :: (Show a) => [[a]] -> IO ()
printMatrix xs = putStr (showMatrix xs)
-- }}}

data Answer = Lt !Int | Geq !Int

neg :: Answer -> Answer
neg (Lt a) = Geq a
neg (Geq a) = Lt a

inputAnswer :: IO Answer
inputAnswer = do
	[sign, ns, ts] <- words <$> getLine
	let n :: Int = read ns
	let t = ts == "Y"
	let ans = case sign of
		">=" -> Geq n
		"<" -> Lt n
		">" -> Geq (n + 1)
		"<=" -> Lt (n - 1)
	return $ if t then ans else neg ans

solve :: [Answer] -> Maybe Int
solve = go (-10^9, 10^9)
	where
		go (a,b) [] | a < b = Just a
		go (a,b) (Lt x : xs) = go (a, min b x) xs
		go (a,b) (Geq x : xs) = go (max a x, b) xs
		go _ _ = Nothing

main :: IO ()
main = do
	n <- inputInt
	a <- replicateM n inputAnswer
	case solve a of
		Just x -> print x
		Nothing -> putStrLn "Impossible"


{-# LANGUAGE OverloadedStrings #-}
module Main where

import qualified Data.Set as Set
import qualified Data.Text as T

main :: IO ()
main = do
    input <- getLine
    let input2 = T.pack . drop 1 . take (length input - 1) $ input
        splitted = map T.strip . T.splitOn "," $ input2
        l = Set.fromList . filter (not . T.null) $ splitted
    putStrLn . show $ Set.size l
    pure ()

{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Data.Array.IO
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8 as C
import qualified Data.Foldable         as F
import           Data.Function
import           Data.Functor
import           Data.IORef
import           Data.List
import           Data.Maybe
import           Data.Monoid
import           Data.Traversable
import           Text.Printf           (printf)

import qualified Data.Set as S
import Data.Char

-- I/O

readInts :: C.ByteString -> [Int]
readInts = map fst . mapMaybe C.readInt . C.words

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

readNums :: Num a => C.ByteString -> [a]
readNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words

getNums :: Num a => IO [a]
getNums = readNums <$> C.getLine

cast :: (Integral a, Integral b) => a -> b
cast = fromIntegral

-----

main :: IO ()
main = do
  s <- getLine
  print $ length $ S.toList $ S.fromList $ words $ map (\c -> if isAlpha c then c else ' ') s

import Data.List (nub)

main :: IO()
main  =  getLine >>= print . length . nub . filter (not . flip elem "{}, ")

import Data.Char
import Data.List
main=interact$show.length.nub.filter(isLetter)

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}

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

lstrip :: String -> String
lstrip = dropWhile Char.isSpace
rstrip = reverse . lstrip . reverse
strip  = lstrip . rstrip

splitWhen :: (a -> Bool) -> [a] -> [[a]]
splitWhen p l = splitWhenAux l []
  where
    splitWhenAux []    []            = []
    splitWhenAux []    b@(_:_)       = [b]
    splitWhenAux (h:t) b | (p h)     = (reverse b) : (splitWhenAux t [])
                         | otherwise = splitWhenAux t (h:b)

splitOn :: Eq a => a -> [a] -> [[a]]
splitOn n l = splitWhen (n ==) l

parse :: String -> [String]
parse s = map strip $ splitOn ',' $ (init . tail) s

solve :: String -> Int
solve = length . List.nub . parse

main :: IO ()
main = do
  s <- getLine
  putStrLn $ (show . solve) s

import Data.List (nub)
import Data.Char (isAlpha)

main = interact $ show . length . nub . filter isAlpha

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

solve :: String -> Int
solve = length . nub . filter (`notElem` "{, }")

main :: IO ()
main = do
    s <- getLine
    print $ solve s

import Control.Applicative
import Data.Char (isAlpha)
import Data.List (group, sort)

main = do
  s <- getLine
  putStrLn . show $ length . group . sort $ filter isAlpha s

import Data.List
import Data.Char

main = interact entry
    where entry input = show cnt
            where cnt = (length . nub) (filter isAlpha input)

import Control.Applicative
import Data.List
import Data.Char

main=do
   a<-show <$> length  <$> group <$> sort <$> filter (isLower) <$> init <$> tail <$> getLine
   putStrLn a

import Data.Char (isAlpha)
import Data.List (group, sort)

main :: IO ()
main = getLine >>= print . solve . filter isAlpha

solve :: String -> Int
solve = length . group . sort

import Data.Char
import Data.List
main = print . length . nub . filter isLetter =<< getContents

import qualified Data.Set as Set

main :: IO()
main = do
  xs <- getLine
  print $ Set.size $ foldl (\acc el -> Set.insert el acc) Set.empty $ trim $ xs
      where
          trim [] = []
          trim (x:xs)
              | x >= 'a' && x <= 'z' = x : trim xs
              | otherwise = trim xs

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

import Data.List

solve :: String -> Int
solve = length . nub . filter (`notElem` "{, }")

main :: IO ()
main = do
    s <- getLine
    print $ solve s

import Data.List

process :: String -> Int
process [] = 0
process xs = length $ nub $ filter (\x -> x >= 'a' && x <= 'z') xs

main = do
	str <- getLine
	putStrLn $ show $ process str

import Data.Char
import Data.List
main :: IO ()
main = fmap (length . nub . filter isAlpha) getLine >>= print

import Data.List

main = getLine >>= print.length.(flip (\\) "{, }").nub

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

repl '{' = ' '
repl '}' = ' '
repl ',' = ' '
repl x = x

main= do
	a<- getLine
	print $ length $ S.toList $ S.fromList $ words $ map repl a

import           Data.Char
import           Data.Set as S  (fromList)
main :: IO ()
main = print =<< length . S.fromList . filter isAlpha <$> getLine

getUnique :: [String] -> [Char] -> Int
getUnique [] _ = 0
getUnique (x:xs) letList
    | not $ curLet `elem` letList = 1 + getUnique xs (curLet:letList)
    | otherwise = getUnique xs letList
    where curLet = head x

main = do
    ln <- getLine
    let lets = words $ tail (init ln)
    putStrLn . show $ getUnique lets []

import Data.Char (isLetter)
import Data.List (nub)

main = interact $ show . length . nub . filter isLetter

import Data.List

main = getLine >>= print . length . nub . solve

solve "}"  = ""
solve ('{':ls) = solve ls
solve (',':ls) = solve ls
solve (' ':ls) = solve ls
solve (l:ls)   = l:(solve ls)

import qualified Data.Text as T
import Data.List

process :: [String] -> Int
process = length.nub

parse :: String -> [String]
parse "{}" = []
parse xs = map T.unpack $ T.splitOn (T.pack ", ") (T.pack.tail.init$xs)

main = do
    xs <- getLine
    print $ process $ parse xs

import Data.List
main = do interact $ show . length . nub . del
    where   del [] = []
            del (x:xs)
                | 'a' <= x && x <= 'z' = x : del xs
                | otherwise            = del xs

import Data.List.Split
import Data.List

solve :: String -> String
solve = show . length . nub .
            split ((dropBlanks. dropDelims .oneOf) "}{, \n")

main :: IO ()
main= interact $ solve

import Data.List
import Data.Char

solve :: String -> String
solve = show . length . nub . filter isLetter

main :: IO ()
main= interact $ solve

module Main where

import Data.Set (toList, fromList)

uniquify = toList . fromList

main = do
	s <- getLine
	putStr $ show $ uniqueNumber s

uniqueNumber :: String -> Int
uniqueNumber = length . uniquify . words . cleanString where
	cleanString = filter (not . (`elem` ",{}"))

import Data.List
f str = filter (\x->not (elem x "{, }\n")) str
main = interact $ show . length .  nub . f

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

parse :: Char -> Char
parse c
  | c == '{' = ' '
  | c == '}' = ' '
  | c == ',' = ' '
  | otherwise = c

solve :: String -> Int
solve s =
  let input = (words . map parse) s
      noDuplicates = Set.fromList input
      ans = Set.toList noDuplicates
  in length ans

main = do
  input <- getLine
  print $ solve input

module Main where

import Data.List (nub)

main :: IO ()
main = do
	ln <- getLine
	print $ process ln

process :: String ->  Int
process = length . nub . readLetters

readLetters :: String -> [Char]
readLetters (' ' : cs) = readLetters cs
readLetters ('{' : cs) = items cs
items [] = []
items ('}' : cs) = []
items (' ' : cs) = items cs
items (',' : cs) = items cs
items (c : cs) = c : items cs

import Control.Monad
import Control.Applicative
import Data.List (nub)

genAns [] = 0
genAns [x] = 1
genAns xs = max 0 $ (length $ nub xs) - 2

main = do
  aa <- getLine
  let ls = tail $ take (length aa - 1) aa
  print $ genAns ls

import Data.Char
import Data.List
f s = show $ length $ nub $ filter isLetter s
main = interact f

import Data.List
main = do
    s <- getLine
    putStrLn $ show $ length $ func s

func :: String -> String
func s = nub [x | x <- s, x `elem` ['a'..'z']]

check [] y           = length y
check (x:xs) y
  | not (x `elem` y) = check xs (x:y)
  | otherwise        = check xs y

trim = f . f . filter (/=',') where f = reverse . drop 1

main = getLine >>= return . (flip check) [] . words . trim >>= putStrLn . show

import Data.List

main :: IO()
main = interact $ show . length . nub . filter (\c -> 'a' <= c && c <= 'z')

s l = [x|x<-l,'a'<=x,x<='z']

d l ch k
    |ch == 'z' =(k+t)
    |otherwise = d l (succ ch) (k+t)
    where t = if null [0|x<-l,x==ch] then 0 else 1

n x = d (s x) 'a' 0

main = do
    s <- getLine
    print (n s)

import Data.List
solve s = length $ nub $ concat $ map words$ splitOn ',' $ init $ tail $ s

splitOn::Char->String->[String]
splitOn f [] = []
splitOn f ss = [takeWhile (/=f) ss] ++ splitOn f (stail (dropWhile (/=f) ss))

stail [] = []
stail (s:[]) = []
stail s = tail s

main = do
  s<-getLine
  putStrLn $show$solve s

import Data.Set as Set
import Data.Char

main = interact $ show.f
f x = size (Set.fromList (Prelude.filter isLetter x))

import Data.List
import Data.Function
import Data.Char

main = interact $ show . length . nub . filter (isAlpha)

import Data.List
import Data.List.Split

main = do
  s <- getLine
  let xs = splitOn ", " $ tail $ init s

  print $ length $ group $ filter (not . null) $ sort xs

import Data.List as L
import Data.Char as C
main = interact $ show . length . L.nub . filter C.isLower

import Data.List

main = do
       a <- getLine
       let b = length $ nub $ filter (\c -> c >= 'a' && c <= 'z') a
       putStrLn $ show b

import Data.List (nub)
import Data.Char (isAlpha)
main =
	interact $ show. length. nub. filter isAlpha

import Data.List
import Data.Maybe
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ show.solve. words. (\a->if a=="" then a else a++",").init.tail.head . lines
solve :: [String]->Int
solve xss =  length $ slv1 xss
slv1 []=[]
slv1 (xs:xss) = xs:slv1 [ys|ys<-xss,ys/=xs]

import Data.Char

h :: String -> [Char] -> Int
h "}" a = count a
h ('{':s) a = h s a
h (',':xs) s = h xs s
h (' ':xs) s = h xs s
h (x:xs) s = h xs (s++[x])

count :: [Char] -> Int

count a = length b
 where b = rmdups a

rmdups [] = []
rmdups (x:xs)
 | x `elem` xs = rmdups xs
 | x == '"' = rmdups xs
 | otherwise = x : rmdups xs

main = do
 line <- getLine
 print (h line [])

hi :: String -> [Char] -> [Char]
hi "}" a = a
hi ('{':s) a = hi s a
hi (',':xs) s = hi xs s
hi (' ':xs) s = hi xs s
hi (x:xs) s = hi xs (s++[x])

import qualified Data.Set as S
import Control.Applicative

solve :: String -> Int
solve s = S.size.S.fromList $ filter (not.(`elem` "{, }")) s

main = do
    l <- getLine
    putStrLn . show $ solve l

import Data.List
solve s = length $ nub $ splitOn ',' $ init $ tail $ s

splitOn::Char->String->[String]
splitOn f [] = []
splitOn f ss = [takeWhile (/=f) ss] ++ splitOn f (stail (dropWhile (/=f) ss))

stail [] = []
stail (s:[]) = []
stail s = tail s

main = do
  s<-getLine
  putStrLn $show$solve s

import Data.Set as Set

main = interact $ show.f.tail.init
f x
  | (length x) > 1 = (size (Set.fromList x)) - 3
  | otherwise = (length x) - 1

import Data.Set as Set

main = interact $ show.f.tail.init
f x
  | (length x) > 1 = (size (Set.fromList x)) - 3
  | otherwise = length x

import Data.Set as Set

main = interact $ show.f.tail.init
f x
  | (length x) > 1 = (size (Set.fromList x)) - 2
  | otherwise = length x

import Data.Set as Set

main = interact $ show.f.tail.init
f x
  | (length x) > 1 = (size (Set.fromList x)) - 1
  | otherwise = length x

import Data.List
import Data.List.Split

main = do
  s <- getLine
  let xs = splitOn ", " $ tail $ init s
  print $ length $ group $ sort xs

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}

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

splitWhen :: (a -> Bool) -> [a] -> [[a]]
splitWhen p l = splitWhenAux l []
  where
    splitWhenAux []    []            = []
    splitWhenAux []    b@(_:_)       = [b]
    splitWhenAux (h:t) b | (p h)     = (reverse b) : (splitWhenAux t [])
                         | otherwise = splitWhenAux t (h:b)

splitOn :: Eq a => a -> [a] -> [[a]]
splitOn n l = splitWhen (n ==) l

parse :: String -> [String]
parse s = splitOn ',' $ (init . tail) s

solve :: String -> Int
solve = length . List.nub . parse

main :: IO ()
main = do
  s <- getLine
  putStrLn $ (show . solve) s

import Control.Applicative
import Data.List
import Data.List.Split

main=do
   a<-show <$> length <$> filter (/=[""]) <$> group <$> sort <$> splitOn "," <$> init <$> tail <$> getLine
   putStrLn a

import Control.Applicative
import Data.List
import Data.List.Split

check n | le >1 = snd $ head $ filter (\z-> odd (fst z)) $ zip n [1..]
        | otherwise = snd $ head $ filter (\z-> even (fst z)) $ zip n [1..]
  where le = length $ filter even n

main=do
   a<-show <$> length <$> splitOn "," <$> init <$> tail <$> getLine
   putStrLn a

import Control.Applicative
import Data.List
import Data.List.Split

main=do
   a<-show <$> length <$> group <$> sort <$> splitOn "," <$> init <$> tail <$> getLine
   putStrLn a

import Data.List

main = getLine >>= print.(max 0).(flip (-) 4).length.nub

import Data.List

main = getLine >>= print.(flip (-) 4).length.nub

import Data.List

main = getLine >>= print . length . nub . solve

solve "}"  = ""
solve ('{':ls) = solve ls
solve ('.':ls) = solve ls
solve (' ':ls) = solve ls
solve (l:ls)   = l:(solve ls)

f str = filter (\x->not (elem x "{, }\n")) str
g str = filter (\x-> length(filter (==x) str) ==1 ) str
main = interact $ g . f

f str = filter (\x->not (elem x "{, }\n")) str
g str = filter (\x-> length(filter (==x) str) ==1 ) str
main = interact $ show . length .  g . f


{-# LANGUAGE BangPatterns #-}

import qualified Data.Map.Strict as Map
import Data.Map (Map)
import qualified Data.Array as Ar
import Data.Array (Array)
import qualified Data.List as L
import qualified Data.Maybe as Mb
import Data.Function
import Data.Int

transform :: [Int16] -> [Int16]
transform lst = map (m Map.!) lst
    where
        unique = map head $ L.group $ L.sort lst
        m = Map.fromAscList $ zip unique [0..]

type PrefixSums = Array Int16 (Array Int32 Int32)

makePrefixSum :: (Num a) => [a] -> [a]
makePrefixSum lst = 0 : go 0 lst
    where
        go aux [] = []
        go aux (e:es) = aux+e : go (aux+e) es

makePrefixSums :: [Int16] -> PrefixSums
makePrefixSums lst = Ar.listArray (0,mx) $ map prefixSumMapper [0..mx]
    where
        n = fromIntegral $ length lst
        mx = fromIntegral $ maximum lst
        prefixSumMapper i = Ar.listArray (0, n) $ makePrefixSum $ map mapperF lst
            where
                mapperF j = if j == i then 1 else 0

frequency :: PrefixSums -> Int16 -> (Int32, Int32) -> Int32
frequency vecVec i (start, end) = endSum - startSum
    where
        vec = vecVec Ar.! i
        endSum = vec Ar.! (end+1)
        startSum = vec Ar.! start

makeIndexList :: [Int16] -> [[Int32]]
makeIndexList lst = map (map snd) $ L.groupBy ((==) `on` fst) $ L.sort $ zip lst [0..]

maxValue :: Int16 -> (Int16 -> (Int32, Int32) -> Int32) -> [(Int32, Int32)] -> Int32
maxValue _ _ [] = 0
maxValue mx frequencyGetter indexes = maximum [2*c + frequencyGetter i (start+1,end-1) | (c, (start,end)) <- zip [1..] indexes, i <- [0..mx]]

solve :: [Int16] -> Int32
solve rawLst = maximum $ defaultAns : map (maxValueGetter . makeStartEndPairs) indexList
    where
        !lst = transform rawLst
        mx = maximum lst
        !defaultAns = fromIntegral $ maximum $ map length $ L.group $ L.sort lst
        !indexList = makeIndexList lst
        makeStartEndPairs indexes = take (length indexes `div` 2) $ zip indexes (reverse indexes)
        !frequencyGetter = frequency (makePrefixSums lst)
        !maxValueGetter = maxValue mx frequencyGetter

{-
getCounts :: [Int] -> Map Int Int
getCounts lst = Map.fromList $ map mapper grouping
    where
        grouping = L.group . L.sort $ lst
        mapper as = (head as, length as)

dec :: Int -> Map Int Int -> Map Int Int -> (Map Int Int, Map Int Int)
dec n remaining remainingInv = (newRemaining, newRemainingInv2)
    where
        count = remaining Map.! n
        newRemaining = Map.adjust pred n remaining
        newRemainingInv1 = Map.adjust pred count remainingInv
        newRemainingInv2 = Map.alter (Just . succ . Mb.fromMaybe 0) (count-1) newRemainingInv1

createInvPair :: Map Int Int -> (Map Int Int, Map Int Int)
createInvPair remaining = (remaining, inv)
    where
        values = Map.elems remaining
        inv = getCounts values

solve :: [Int] -> Int
solve lst = maximum $ map mapper lst
    where
        arr = Ar.listArray (0, length lst - 1) lst
        counts = Map.insert 0 0 $ getCounts lst
        helper :: Int -> Int -> Int -> Int -> (Map Int Int, Map Int Int) -> Int
        helper n nCount start end (remaining, remainingInv)
            | start >= end  = counts Map.! n
            | sVal == n && eVal == n
                = max (nCount + 2 + maximum (Map.elems remaining)) (helper n (nCount+2) (start+1) (end-1) (remaining, remainingInv))
            | eVal /= n
                = helper n nCount start (end-1) (dec eVal remaining remainingInv)
            | otherwise
                = helper n nCount (start+1) end (dec sVal remaining remainingInv)
            where
                sVal = arr Ar.! start
                eVal = arr Ar.! end
        mapper n = helper n 0 0 (length lst - 1) (createInvPair $ Map.delete n counts)
-}

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    _ <- readInts
    lst <- readInts16
    print $ solve lst
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- readInts
    testCases t

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

readInts32 :: IO [Int32]
readInts32 = map read . words <$> getLine

readInts16 :: IO [Int16]
readInts16 = map read . words <$> getLine

import qualified Data.Map.Strict as Map
import Data.Map (Map)
import qualified Data.Array as Ar
import Data.Array (Array)
import qualified Data.List as L
import qualified Data.Maybe as Mb
import Data.Function

transform :: [Int] -> [Int]
transform lst = map (m Map.!) lst
    where
        unique = map head $ L.group $ L.sort lst
        m = Map.fromAscList $ zip unique [0..]

type Vector = Array Int

type PrefixSums = Vector (Vector Int)

makePrefixSum :: [Int] -> [Int]
makePrefixSum lst = 0 : go 0 lst
    where
        go aux [] = []
        go aux (e:es) = aux+e : go (aux+e) es

makePrefixSums :: [Int] -> PrefixSums
makePrefixSums lst = Ar.listArray (0,mx) $ map prefixSumMapper [0..mx]
    where
        n = length lst
        mx = maximum lst
        prefixSumMapper i = Ar.listArray (0, n) $ makePrefixSum $ map mapperF lst
            where
                mapperF j = if j == i then 1 else 0

frequency :: PrefixSums -> Int -> (Int, Int) -> Int
frequency vecVec i (start, end) = endSum - startSum
    where
        vec = vecVec Ar.! i
        endSum = vec Ar.! (end+1)
        startSum = vec Ar.! start

makeIndexList :: [Int] -> [[Int]]
makeIndexList lst = map (map snd) $ L.groupBy ((==) `on` fst) $ L.sort $ zip lst [0..]

maxValue :: Int -> (Int -> (Int, Int) -> Int) -> [(Int, Int)] -> Int
maxValue _ _ [] = 0
maxValue mx frequencyGetter indexes = maximum [2*c + frequencyGetter i (start+1,end-1) | (c, (start,end)) <- zip [1..] indexes, i <- [0..mx]]

solve :: [Int] -> Int
solve rawLst = maximum $ defaultAns : map (maxValueGetter . makeStartEndPairs) indexList
    where
        lst = transform rawLst
        mx = maximum lst
        defaultAns = maximum $ map length $ L.group $ L.sort lst
        indexList = makeIndexList lst
        makeStartEndPairs indexes = take (length indexes `div` 2) $ zip indexes (reverse indexes)
        frequencyGetter = frequency (makePrefixSums lst)
        maxValueGetter = maxValue mx frequencyGetter

{-
getCounts :: [Int] -> Map Int Int
getCounts lst = Map.fromList $ map mapper grouping
    where
        grouping = L.group . L.sort $ lst
        mapper as = (head as, length as)

dec :: Int -> Map Int Int -> Map Int Int -> (Map Int Int, Map Int Int)
dec n remaining remainingInv = (newRemaining, newRemainingInv2)
    where
        count = remaining Map.! n
        newRemaining = Map.adjust pred n remaining
        newRemainingInv1 = Map.adjust pred count remainingInv
        newRemainingInv2 = Map.alter (Just . succ . Mb.fromMaybe 0) (count-1) newRemainingInv1

createInvPair :: Map Int Int -> (Map Int Int, Map Int Int)
createInvPair remaining = (remaining, inv)
    where
        values = Map.elems remaining
        inv = getCounts values

solve :: [Int] -> Int
solve lst = maximum $ map mapper lst
    where
        arr = Ar.listArray (0, length lst - 1) lst
        counts = Map.insert 0 0 $ getCounts lst
        helper :: Int -> Int -> Int -> Int -> (Map Int Int, Map Int Int) -> Int
        helper n nCount start end (remaining, remainingInv)
            | start >= end  = counts Map.! n
            | sVal == n && eVal == n
                = max (nCount + 2 + maximum (Map.elems remaining)) (helper n (nCount+2) (start+1) (end-1) (remaining, remainingInv))
            | eVal /= n
                = helper n nCount start (end-1) (dec eVal remaining remainingInv)
            | otherwise
                = helper n nCount (start+1) end (dec sVal remaining remainingInv)
            where
                sVal = arr Ar.! start
                eVal = arr Ar.! end
        mapper n = helper n 0 0 (length lst - 1) (createInvPair $ Map.delete n counts)
-}

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    _ <- readInts
    lst <- readInts
    print $ solve lst
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- readInts
    testCases t

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

import Control.Monad (forM_)
import Data.List (sort)

solve xs = if length ids == 1 then length xs else res where
	sorted = sort xs
	ids = go sorted where
		go (x:xs) = x : go (dropWhile (==x) xs)
		go [] = []

	res = maximum [ solveTwo a b (filter (\k -> k == a || k == b) xs)| a <- ids, b <- ids, a /= b]

	solveTwo a b xs = maximum $ go a b xs (reverse xs) 0 (length $ filter (== b) xs) where
		total_a_count = length $ filter (==a) xs
		go a b xs rxs acount bcount = let
				(b1, xs') = strip xs 0
				(b2, rxs') = strip rxs 0
				acount' = acount + 2
				bcount' = bcount - b1 - b2
			in
				if acount > total_a_count then [total_a_count] else (acount + bcount) : go a b xs' rxs' acount' bcount'

			where
				strip (x:xs) acc
					| x == a = (acc, xs)
					| x == b = strip xs (acc + 1)

main = do
	t <- fmap read getLine
	forM_ [1..t] $ \i -> do
		n <- fmap read getLine :: IO Int
		xs <- fmap (map read.words) getLine :: IO [Int]
		print (solve xs)

import qualified Data.Map.Strict as Map
import Data.Map (Map)
import qualified Data.Array as Ar
import Data.Array (Array)
import qualified Data.List as L

getCounts :: [Int] -> Map Int Int
getCounts lst = Map.fromList $ map mapper grouping
    where
        grouping = L.group . L.sort $ lst
        mapper as = (head as, length as)

solve :: [Int] -> Int
solve lst = maximum $ map mapper lst
    where
        arr = Ar.listArray (0, length lst - 1) lst
        counts = Map.insert 0 0 $ getCounts lst
        helper :: Int -> Int -> Int -> Int -> Map Int Int -> Int
        helper n nCount start end remaining
            | start >= end  = counts Map.! n
            | sVal == n && eVal == n
                = max (nCount + 2 + maximum (Map.elems remaining)) (helper n (nCount+2) (start+1) (end-1) remaining)
            | eVal /= n
                = helper n nCount start (end-1) (Map.adjust pred eVal remaining)
            | otherwise
                = helper n nCount (start+1) end (Map.adjust pred sVal remaining)
            where
                sVal = arr Ar.! start
                eVal = arr Ar.! end
        mapper n = helper n 0 0 (length lst - 1) (Map.delete n counts)

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    _ <- readInts
    lst <- readInts
    print $ solve lst
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- readInts
    testCases t

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

import Control.Monad (forM_)
import Data.List (sort)

solve xs = if length ids == 1 then length xs else res where
	sorted = sort xs
	ids = go sorted where
		go (x:xs) = x : go (dropWhile (==x) xs)
		go [] = []

	res = maximum [ solveTwo a b (filter (\k -> k == a || k == b) xs)| a <- ids, b <- dropWhile (<= a) ids]

	solveTwo a b xs = maximum $ go a b xs (reverse xs) 0 (length $ filter (== b) xs) where
		total_a_count = length $ filter (==a) xs
		go a b xs rxs acount bcount = let
				(b1, xs') = strip xs 0
				(b2, rxs') = strip rxs 0
				acount' = acount + 2
				bcount' = bcount - b1 - b2
			in
				if acount > total_a_count then [total_a_count] else (acount + bcount) : go a b xs' rxs' acount' bcount'

			where
				strip (x:xs) acc
					| x == a = (acc, xs)
					| x == b = strip xs (acc + 1)

main = do
	t <- fmap read getLine
	forM_ [1..t] $ \i -> do
		n <- fmap read getLine :: IO Int
		xs <- fmap (map read.words) getLine :: IO [Int]
		print (solve xs)