{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}

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

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

main :: IO ()
main = do
  [n,m] <- map read . words <$> getLine
  as_ <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine
  as <- A.newListArray (1, n) as_ :: IO (IOUArray Int Int)
  cs_ <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine
  customers <- take m . unfoldr (runStateT $ (,) <$> rInt <*> rInt)
     <$> BSL.getContents
  let cs = A.listArray (1, n) $ map fromIntegral cs_ :: UArray Int Int64
      is = A.listArray (1, n) $ sortBy (compare `on` (cs A.!)) [1..n]
           :: UArray Int Int
  kpres <- newIORef (1::Int)
  let serveDesperately d !acc = do
        k <- readIORef kpres
        go k d acc
      go k d !acc
        | k > n = return 0
        | otherwise = do
            (!val, !d2) <- tryToServe cs as (is A.! k) d
            if d2 <= 0 then return $! acc+val else do
              writeIORef kpres (k+1)
              go (k+1) d2 (acc+val)
  forM_ customers $ \(t,d) -> do
    (!val, !d2) <- tryToServe cs as t d
    tot <- if d2 <= 0 then return val else serveDesperately d2 val
    print tot

tryToServe :: UArray Int Int64 -> IOUArray Int Int -> Int -> Int
  -> IO (Int64,Int)
tryToServe cost rest !t !d = do
  restT <- A.readArray rest t
  if restT >= d then do
    A.writeArray rest t $! (restT-d)
    return (cost A.! t * fromIntegral d,    0)
  else do
    A.writeArray rest t 0
    return (cost A.! t * fromIntegral restT, d-restT)

type Comparison e = e -> e -> Ordering

{-# INLINE sortMArray #-}
sortMArray :: (MArray a e m, Ord e, A.Ix i, Integral i, Bits i)
           => a i e -> m ()
sortMArray = sortMArrayBy compare

{-# INLINE sortMArrayBy #-}
sortMArrayBy :: (MArray a e m, A.Ix i, Integral i, Bits i)
  => Comparison e -> a i e -> m ()
sortMArrayBy cmp = \arr -> A.getBounds arr >>= sortMArrayByBounds cmp arr

-- sort the interval [l,u] of arr.
{-# INLINE sortMArrayByBounds #-}
sortMArrayByBounds :: (MArray a e m, A.Ix i, Integral i, Bits i)
  => Comparison e -> a i e -> (i,i) -> m ()
sortMArrayByBounds cmp = \arr (l,u) -> sortMArrayByBounds_ cmp arr l (u+1)

-- sort the interval [l,u) of arr.
{-# INLINE sortMArrayByBounds_ #-}
sortMArrayByBounds_ :: (MArray a e m, A.Ix i, Integral i, Bits i)
  => Comparison e -> a i e -> i -> i -> m ()
sortMArrayByBounds_ cmp = \arr l u -> do
  let len = u - l
  tmp <- A.newArray_ (0,len `shiftR` 1 - 1)
  mergesort cmp arr tmp l u

mergesort cmp arr tmp l u
  | u - l <= 1 = return ()
  | otherwise  = do mergesort cmp arr tmp l mid
                    mergesort cmp arr tmp mid u
                    merge cmp arr tmp l mid u
    where
      len = u - l
      mid = (u + l) `shiftR` 1

{-# INLINE merge #-}
merge :: (MArray a e m, A.Ix i, Integral i, Bits i)
  => Comparison e -> a i e -> a i e -> i -> i -> i -> m ()
merge cmp arr tmp l mid u = do
  copyMArray arr (l,mid-1) tmp (0,mml-1)
  eLow <- A.readArray tmp 0
  eHigh <- A.readArray arr mid
  loop eLow 0 eHigh mid l
  where
    mml = mid - l
    loop !eLow !iLow !eHigh !iHigh !iIns = case cmp eHigh eLow of
      LT -> do A.writeArray arr iIns eHigh
               wroteHigh eLow iLow (iHigh+1) (iIns+1)
      _  -> do A.writeArray arr iIns eLow
               wroteLow (iLow+1) eHigh iHigh (iIns+1)
    wroteHigh !eLow !iLow !iHigh !iIns
      | iHigh >= u = copyMArray tmp (iLow,mml-1) arr (iIns,u-1)
      | otherwise  = do eHigh <- A.readArray arr iHigh
                        loop eLow iLow eHigh iHigh iIns
    wroteLow !iLow !eHigh !iHigh !iIns
      | iLow >= mml = return ()
      | otherwise   = do eLow <- A.readArray tmp iLow
                         loop eLow iLow eHigh iHigh iIns

{-# INLINE copyMArray #-}
copyMArray :: (MArray a0 e m, A.Ix i0, MArray a1 e m, A.Ix i1)
  => a0 i0 e -> (i0,i0) -> a1 i1 e -> (i1,i1) -> m ()
copyMArray src srcRange dst dstRange =
  forM_ (zip (A.range srcRange) (A.range dstRange))
  $ \(i,j) -> A.writeArray dst j =<< A.readArray src i

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}

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

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

main :: IO ()
main = do
  [n,m] <- map read . words <$> getLine
  as_ <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine
  as <- A.newListArray (1, n) as_ :: IO (IOUArray Int Int)
  cs_ <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine
  customers <- take m . unfoldr (runStateT $ (,) <$> rInt <*> rInt)
     <$> BSL.getContents
  let cs = A.listArray (1, n) $ map fromIntegral cs_ :: UArray Int Int64
      is = runSTUArray $ do
        is <- A.newListArray (1,n) [1..n]
        sortMArrayBy (\i j -> compare (cs A.! i) (cs A.! j)) is
        return is
  kpres <- newIORef (1::Int)
  let serveDesperately d !acc = do
        k <- readIORef kpres
        go k d acc
      go !k !d !acc
        | k > n = return 0
        | otherwise = do
            (!val, !d2) <- tryToServe cs as (is A.! k) d
            if d2 <= 0 then return $! acc+val else do
              writeIORef kpres (k+1)
              go (k+1) d2 (acc+val)
  forM_ customers $ \(!t,!d) -> do
    (!val, !d2) <- tryToServe cs as t d
    tot <- if d2 <= 0 then return val else serveDesperately d2 val
    print tot

tryToServe :: UArray Int Int64 -> IOUArray Int Int -> Int -> Int
  -> IO (Int64,Int)
tryToServe cost rest !t !d = do
  restT <- A.readArray rest t
  if restT >= d then do
    A.writeArray rest t $! (restT-d)
    return (cost A.! t * fromIntegral d,    0)
  else do
    A.writeArray rest t 0
    return (cost A.! t * fromIntegral restT, d-restT)

type Comparison e = e -> e -> Ordering

{-# INLINE sortMArray #-}
sortMArray :: (MArray a e m, Ord e, A.Ix i, Integral i, Bits i)
           => a i e -> m ()
sortMArray = sortMArrayBy compare

{-# INLINE sortMArrayBy #-}
sortMArrayBy :: (MArray a e m, A.Ix i, Integral i, Bits i)
  => Comparison e -> a i e -> m ()
sortMArrayBy cmp = \arr -> A.getBounds arr >>= sortMArrayByBounds cmp arr

-- sort the interval [l,u] of arr.
{-# INLINE sortMArrayByBounds #-}
sortMArrayByBounds :: (MArray a e m, A.Ix i, Integral i, Bits i)
  => Comparison e -> a i e -> (i,i) -> m ()
sortMArrayByBounds cmp = \arr (l,u) -> sortMArrayByBounds_ cmp arr l (u+1)

-- sort the interval [l,u) of arr.
{-# INLINE sortMArrayByBounds_ #-}
sortMArrayByBounds_ :: (MArray a e m, A.Ix i, Integral i, Bits i)
  => Comparison e -> a i e -> i -> i -> m ()
sortMArrayByBounds_ cmp = \arr l u -> do
  let len = u - l
  tmp <- A.newArray_ (0,len `shiftR` 1 - 1)
  mergesort cmp arr tmp l u

mergesort cmp arr tmp l u
  | u - l <= 1 = return ()
  | otherwise  = do mergesort cmp arr tmp l mid
                    mergesort cmp arr tmp mid u
                    merge cmp arr tmp l mid u
    where
      len = u - l
      mid = (u + l) `shiftR` 1

{-# INLINE merge #-}
merge :: (MArray a e m, A.Ix i, Integral i, Bits i)
  => Comparison e -> a i e -> a i e -> i -> i -> i -> m ()
merge cmp arr tmp l mid u = do
  copyMArray arr (l,mid-1) tmp (0,mml-1)
  eLow <- A.readArray tmp 0
  eHigh <- A.readArray arr mid
  loop eLow 0 eHigh mid l
  where
    mml = mid - l
    loop !eLow !iLow !eHigh !iHigh !iIns = case cmp eHigh eLow of
      LT -> do A.writeArray arr iIns eHigh
               wroteHigh eLow iLow (iHigh+1) (iIns+1)
      _  -> do A.writeArray arr iIns eLow
               wroteLow (iLow+1) eHigh iHigh (iIns+1)
    wroteHigh !eLow !iLow !iHigh !iIns
      | iHigh >= u = copyMArray tmp (iLow,mml-1) arr (iIns,u-1)
      | otherwise  = do eHigh <- A.readArray arr iHigh
                        loop eLow iLow eHigh iHigh iIns
    wroteLow !iLow !eHigh !iHigh !iIns
      | iLow >= mml = return ()
      | otherwise   = do eLow <- A.readArray tmp iLow
                         loop eLow iLow eHigh iHigh iIns

{-# INLINE copyMArray #-}
copyMArray :: (MArray a0 e m, A.Ix i0, MArray a1 e m, A.Ix i1)
  => a0 i0 e -> (i0,i0) -> a1 i1 e -> (i1,i1) -> m ()
copyMArray src srcRange dst dstRange =
  forM_ (zip (A.range srcRange) (A.range dstRange))
  $ \(i,j) -> A.writeArray dst j =<< A.readArray src i

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}

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

main :: IO ()
main = do
  [n,m] <- map read . words <$> getLine
  as_ <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine
  as <- A.newListArray (1, n) as_ :: IO (IOUArray Int Int)
  cs_ <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine
  let cs = A.listArray (1, n) cs_ :: UArray Int Int
      is = runSTUArray $ do
        is <- A.newListArray (1,n) [1..n]
        sortMArrayBy (\i j -> compare (cs A.! i) (cs A.! j)) is
        return is
  kpres <- newIORef (1::Int)
  let serveDesperately d !acc = do
        k <- readIORef kpres
        go k d acc
      go k d !acc
        | k > n = return 0
        | otherwise = do
            (val, d2) <- tryToServe cs as (is A.! k) d
            if d2 <= 0 then return $! acc+val else do
              writeIORef kpres (k+1)
              go (k+1) d2 (acc+val)
  replicateM_ m $ do
    [t, d] <- map read . words <$> getLine
    (val, d2) <- tryToServe cs as t d
    tot <- if d2 <= 0 then return val else serveDesperately d2 val
    print tot

tryToServe :: UArray Int Int -> IOUArray Int Int -> Int -> Int -> IO (Int,Int)
tryToServe cost rest t d = do
  restT <- A.readArray rest t
  if restT >= d then do
    A.writeArray rest t (restT-d)
    return (cost A.! t * d,    0)
  else do
    A.writeArray rest t 0
    return (cost A.! t * restT, d-restT)

type Comparison e = e -> e -> Ordering

{-# INLINE sortMArray #-}
sortMArray :: (MArray a e m, Ord e, A.Ix i, Integral i, Bits i)
           => a i e -> m ()
sortMArray = sortMArrayBy compare

{-# INLINE sortMArrayBy #-}
sortMArrayBy :: (MArray a e m, A.Ix i, Integral i, Bits i)
  => Comparison e -> a i e -> m ()
sortMArrayBy cmp = \arr -> A.getBounds arr >>= sortMArrayByBounds cmp arr

-- sort the interval [l,u] of arr.
{-# INLINE sortMArrayByBounds #-}
sortMArrayByBounds :: (MArray a e m, A.Ix i, Integral i, Bits i)
  => Comparison e -> a i e -> (i,i) -> m ()
sortMArrayByBounds cmp = \arr (l,u) -> sortMArrayByBounds_ cmp arr l (u+1)

-- sort the interval [l,u) of arr.
{-# INLINE sortMArrayByBounds_ #-}
sortMArrayByBounds_ :: (MArray a e m, A.Ix i, Integral i, Bits i)
  => Comparison e -> a i e -> i -> i -> m ()
sortMArrayByBounds_ cmp = \arr l u -> do
  let len = u - l
  tmp <- A.newArray_ (0,len `shiftR` 1 - 1)
  mergesort cmp arr tmp l u

mergesort cmp arr tmp l u
  | u - l <= 1 = return ()
  | otherwise  = do mergesort cmp arr tmp l mid
                    mergesort cmp arr tmp mid u
                    merge cmp arr tmp l mid u
    where
      len = u - l
      mid = (u + l) `shiftR` 1

{-# INLINE merge #-}
merge :: (MArray a e m, A.Ix i, Integral i, Bits i)
  => Comparison e -> a i e -> a i e -> i -> i -> i -> m ()
merge cmp arr tmp l mid u = do
  copyMArray arr (l,mid-1) tmp (0,mml-1)
  eLow <- A.readArray tmp 0
  eHigh <- A.readArray arr mid
  loop eLow 0 eHigh mid l
  where
    mml = mid - l
    loop !eLow !iLow !eHigh !iHigh !iIns = case cmp eHigh eLow of
      LT -> do A.writeArray arr iIns eHigh
               wroteHigh eLow iLow (iHigh+1) (iIns+1)
      _  -> do A.writeArray arr iIns eLow
               wroteLow (iLow+1) eHigh iHigh (iIns+1)
    wroteHigh !eLow !iLow !iHigh !iIns
      | iHigh >= u = copyMArray tmp (iLow,mml-1) arr (iIns,u-1)
      | otherwise  = do eHigh <- A.readArray arr iHigh
                        loop eLow iLow eHigh iHigh iIns
    wroteLow !iLow !eHigh !iHigh !iIns
      | iLow >= mml = return ()
      | otherwise   = do eLow <- A.readArray tmp iLow
                         loop eLow iLow eHigh iHigh iIns

{-# INLINE copyMArray #-}
copyMArray :: (MArray a0 e m, A.Ix i0, MArray a1 e m, A.Ix i1)
  => a0 i0 e -> (i0,i0) -> a1 i1 e -> (i1,i1) -> m ()
copyMArray src srcRange dst dstRange =
  forM_ (zip (A.range srcRange) (A.range dstRange))
  $ \(i,j) -> A.writeArray dst j =<< A.readArray src i


import Control.Monad
import Data.List
import Data.Int
import qualified Data.Set as S

calc' :: S.Set (Int,Int) -> Int -> Int64 -> Int -> [Int] -> Int64
calc' _ _  cnt n [] = cnt
calc' tr i cnt n (y:ys) =
  let (left, _) = S.split (y,-1) tr
      (right, _) = S.split (y,n) tr
      leftSize = S.size left
      rightSize = i - (S.size right)
      cnt' = cnt + (fromIntegral (min leftSize rightSize))
      tr' = S.insert (y,i) tr
  in
      calc' tr' (i+1) cnt' n ys

calc :: Int -> [Int] -> Int64
calc = calc' S.empty 0 0

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let n = read line :: Int
    line <- getLine
    let lst = map read $ words line :: [Int]
    print $ calc n lst

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.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
--import Data.List
--import Data.Array.Unboxed
import qualified Data.Set as Set
import Data.Int

mainFun :: SO
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    p <- getInts n
    let
      p2 = zip p [1..n]
      initVals = Set.fromList p2
      solve :: Set.Set (Int, Int) -> [(Int, Int)] -> Int64 -> Int64
      solve _nil [] cont = cont
      solve vals ((x, kx) : xs) cont = cont `seq` let
        (vl, _) = Set.split (x, minBound) vals
        (_, vr) = Set.split (x, maxBound) vals
        in  solve (Set.delete (x, kx) vals) xs
            $ cont + fromIntegral (min (Set.size vl) (Set.size vr))
    pure $ putInt64s [solve initVals (reverse p2) 0]

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]

putInt64s :: [Int64] -> Builder
putInt64s vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.int64Dec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> int64Dec 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

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

calc' :: S.Set (Int,Int) -> Int -> Int -> Int -> [Int] -> Int
calc' _ _  cnt n [] = cnt
calc' tr i cnt n (y:ys) =
  let (left, _) = S.split (y,-1) tr
      (right, _) = S.split (y,n) tr
      leftSize = S.size left
      rightSize = i - (S.size right)
      cnt' = cnt + (min leftSize rightSize)
      tr' = S.insert (y,i) tr
  in
      calc' tr' (i+1) cnt' n ys

calc :: Int -> [Int] -> Int
calc = calc' S.empty 0 0

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let n = read line :: Int
    line <- getLine
    let lst = map read $ words line :: [Int]
    print $ calc n lst


-- Codeforces 1060 C

import Data.List
import Control.Monad

sumUp :: [Integer] -> [Integer]
sumUp = scanl (+) 0

-- Find min sum of a list with n elements
findMinSum :: Int -> [Integer] -> Integer
findMinSum n list = minimum $ zipWith (-) (drop n list) list

-- Find sums possible with different n consecutive elements added
findSums :: [Integer] -> [(Int, Integer)]
findSums list = map (\n -> (n, findMinSum n $ sumUp list)) [1..length list]

findCombination :: [(Int, Integer)] -> [(Int, Integer)] -> Integer -> Int
findCombination aList bList val = case combinations of
    [] -> 0
    _  -> maximum combinations
    where combinations = do
            (an, ax) <- aList
            (bn, bx) <- bList
            guard $ ax * bx <= val
            return $ an * bn

main :: IO ()
main = do
    firstLine <- getLine
    aList <- getLine >>=
            return.(\list -> map (read::String -> Integer) (words list))
    bList <- getLine >>=
            return.(\list -> map (read::String -> Integer) (words list))
    x     <- getLine >>= return.read
    putStrLn.show $ findCombination (findSums aList) (findSums bList) x

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

main = sol <$> get <*> get <*> get <*> readLn >>= print

--get = fmap fst . mapMaybe C.readInt . C.words <$> C.getLine
get = fmap read . words <$> getLine

sol [n,m] as bs x = if null ps then 0 else maximum ps
    where
    mx = 2*10^9
    sa = listArray (0,n) $ scanl (+) 0 as
    sb = listArray (0,m) $ scanl (+) 0 bs
    da = accumArray min mx (1,n) [(j-i+1, sa!j-sa!(i-1)) | i <- [1..n], j <- [i..n]]
    db = accumArray min mx (1,m) [(j-i+1, sb!j-sb!(i-1)) | i <- [1..m], j <- [i..m]]
    ps = [i*j | i <- [1..n], j <- [1..m], da!i*db!j <= x]

--mx = maxBound :: Int
mx = 2*10^9
--sa = listArray (0,n) $ scanl' (+) 0 as
--sb = listArray (0,m) $ scanl' (+) 0 bs
sa = listArray (0,n) $ scanl (+) 0 as
sb = listArray (0,m) $ scanl (+) 0 bs
da = accumArray min mx (1,n) [(j-i+1, sa!j-sa!(i-1)) | i <- [1..n], j <- [i..n]]
db = accumArray min mx (1,m) [(j-i+1, sb!j-sb!(i-1)) | i <- [1..m], j <- [i..m]]
ps = [i*j | i <- [1..n], j <- [1..m], da!i*db!j <= x]
f = maximum ps
dbg = [(i*j,i,j) | i <- [1..n], j <- [1..m], da!i*db!j <= x]

--
[n,m]=[3,3]
as=[1,2,3]
bs=[1,2,3]
x=9
{-
[n,m]=[5,1]
as=[5,4,2,4,5]
bs=[2]
x=5
--

[n,m]=[8,8]
as=[2000,2000,2000,2000,2000,2000,2000,2000,2000]
bs=[2000,2000,2000,2000,2000,2000,2000,2000,2000]
x=9*10^9
--Output
--4000000
--Answer
--500

-}

-- Codeforces 1060 C

import Data.List
import Control.Monad

sumUp :: [Int] -> [Int]
sumUp = scanl (+) 0

-- Find min sum of a list with n elements
findMinSum :: Int -> [Int] -> Int
findMinSum n list = minimum $ zipWith (-) (drop n list) list

-- Find sums possible with different n consecutive elements added
findSums :: [Int] -> [(Int, Int)]
findSums list = map (\n -> (n, findMinSum n $ sumUp list)) [1..length list]

findCombination :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int
findCombination aList bList val = maximum $ do
    (an, ax) <- aList
    (bn, bx) <- bList
    guard $ ax * bx <= val
    return $ an * bn

main :: IO ()
main = do
    firstLine <- getLine
    aList <- getLine >>=
            return.(\list -> map (read::String -> Int) (words list))
    bList <- getLine >>=
            return.(\list -> map (read::String -> Int) (words list))
    x     <- getLine >>= return.read
    putStrLn.show $ findCombination (findSums aList) (findSums bList) x

-- Codeforces 1060 C

import Data.List
import Control.Monad

sumUp :: [Int] -> [Int]
sumUp = scanl (+) 0

-- Find min sum of a list with n elements
findMinSum :: Int -> [Int] -> Int
findMinSum n list = minimum $ zipWith (-) (drop n list) list

-- Find sums possible with different n consecutive elements added
findSums :: [Int] -> [(Int, Int)]
findSums list = map (\n -> (n, findMinSum n $ sumUp list)) [1..length list]

findCombination :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int
findCombination aList bList val = case combinations of
    [] -> 0
    _  -> maximum combinations
    where combinations = do
            (an, ax) <- aList
            (bn, bx) <- bList
            guard $ ax * bx <= val
            return $ an * bn

main :: IO ()
main = do
    firstLine <- getLine
    aList <- getLine >>=
            return.(\list -> map (read::String -> Int) (words list))
    bList <- getLine >>=
            return.(\list -> map (read::String -> Int) (words list))
    x     <- getLine >>= return.read
    putStrLn.show $ findCombination (findSums aList) (findSums bList) x

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

main = sol <$> get <*> get <*> get <*> readLn >>= print

get = fmap fst . mapMaybe C.readInt . C.words <$> C.getLine

sol [n,m] as bs x = if null ps then 0 else maximum ps
    where
    mx = maxBound :: Int
    sa = listArray (0,n) $ scanl (+) 0 as
    sb = listArray (0,m) $ scanl (+) 0 bs
    da = accumArray min mx (1,n) [(j-i+1, sa!j-sa!(i-1)) | i <- [1..n], j <- [i..n]]
    db = accumArray min mx (1,m) [(j-i+1, sb!j-sb!(i-1)) | i <- [1..m], j <- [i..m]]
    ps = [i*j| i <- [1..n], j <- [1..m], da!i*db!j <= x]

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

main = sol <$> get <*> get <*> get <*> readLn >>= print

get = fmap fst . mapMaybe C.readInt . C.words <$> C.getLine

sol [n,m] as bs x = if null ps then 0 else maximum ps
    where
    a = listArray (1,n) (sort as)
    b = listArray (1,m) (sort bs)
    c = array ((0,0),(n,m)) $ ((0,0),0):
        [((i,0),0) | i <- [1..n]] ++
        [((0,j),0) | j <- [1..m]] ++
        [((i,j),a!i*b!j + c!(i,j-1) + c!(i-1,j) - c!(i-1,j-1)) | i <- [1..n], j <- [1..m]]
    ps = [i*j | i <- [1..n], j <- [1..m], c!(i,j) <= x]


{-# LANGUAGE OverloadedStrings #-}

import qualified Data.ByteString.Char8 as BS
import Data.ByteString (ByteString)
import Control.Applicative (liftA2)
import Control.Monad (forM_)

-- replicate a string n times
multiply :: Int -> ByteString -> ByteString
multiply 0 _ = ""
multiply 1 bs = bs
multiply n bs =
  let (m,r) = n `divMod` 2
      bs' = multiply m (bs `BS.append` bs)
  in if r == 0 then bs'
               else bs `BS.append` bs'

-- solve the problem using Integers
-- (this is too slow for large problems)
solve1 :: Int -> Int -> Maybe Integer
solve1 x p =
  let b = 10*(fromIntegral x)-1 :: Integer
      tenp = 10^p-1
  in first [ n | d0 <- [1..9], let (n,r) = (d0*tenp) `divMod` b, r == 0,
                 length (show n) == p ]

first :: [a] -> Maybe a
first []    = Nothing
first (a:_) = Just a

liftMin :: Ord a => Maybe a -> Maybe a -> Maybe a
liftMin Nothing b = b
liftMin a Nothing = a
liftMin (Just a) (Just b) = Just $ min a b

-- solve the problem using ByteStrings
solve :: Int -> Int -> Maybe ByteString
solve 1 p = Just "1"
solve 2 p = solve' 2 18 2 p
solve 3 p = solve' 3 28 3 p
solve 4 p = solve' 4  6 4 p

solve 6 p = solve' 6 58 6 p
solve 7 p = solve' 7 22 7 p
solve 8 p = solve' 8 13 8 p
solve 9 p = solve' 9 44 9 p

solve 5 p =
  let n1 = solve' 5  6 7 p
      n2 = solve' 5 42 5 p
  in liftMin n1 n2
solve x p = error $ "huh? " ++ " x: " ++ show x ++ " p: " ++ show p

-- find the basic solution to the problem
--   x  - the multipler
--   m  - length of a basic solution
--   d0 - rightmost digit
--   p  - number of decimal digits
solve' :: Int -> Int -> Int -> Int -> Maybe ByteString
solve' x m d0 p =
  if p `mod` m == 0
     then let n :: Integer
              n = (fromIntegral d0)*(10^m-1) `div` fromIntegral (10*x-1)
           in Just $ BS.pack (show n)
     else Nothing

-- repeat a ByteString to length p
-- (don't know if the special case for length == 1 is necessary)
solutionToBS :: Int -> ByteString -> ByteString
solutionToBS p bs | p `mod` BS.length bs /= 0 = error "ooops!"
solutionToBS p bs | BS.length bs == 1 = BS.replicate p (BS.index bs 0)
solutionToBS p bs = multiply k bs
  where k = p `div` BS.length bs

(-->) = flip fmap

main = do (p:x:_) <- getLine --> words --> map read
          case solve x p of
            Nothing -> putStrLn "Impossible"
            Just bs -> BS.putStrLn $ solutionToBS p bs


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

process [x,y] = x:y:[]
process (a:b:c) = a: (process c)

main = do
		n<- read <$> getLine ::IO Int
		k<-replicateM n getLine
		mapM_ putStrLn $ map process k

solve :: String -> String
solve (a:b:[]) = [a,b]
solve (a:b:xs) = [a,b]++( map snd . filter (even . fst) . zip [1..] . init $ xs) ++ [(last xs)]

solveCase :: Int -> IO()
solveCase 0 = return ()
solveCase t = do
  test <- getLine
  putStrLn . solve  $ test
  solveCase (t-1)

getInt :: IO Int
getInt = fmap read getLine

main :: IO()
main = do
  n <- getInt
  solveCase n

import Control.Monad

getStr :: String -> String
getStr (a:b:[]) = [a, b]
getStr (a:_:l@(c:_)) = a : getStr l
getStr [] = []

main = do
  n <- read <$> getLine
  a <- (replicateM n getLine)
  mapM_ putStrLn (getStr <$> a)

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

main = do
	t <- readInt
	mapM_ putStrLn =<< replicateM t solve

solve = do
	s <- getLine
	let
		s' = map fst $ filter snd $ zip s ( cycle [ True, False ] )
	return $ s' ++ [ last s ]

import Control.Monad

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

routine :: IO ()
routine = do
  s <- getLine
  putStrLn $ solve s

solve :: String -> String
solve s = (head s):z
  where
    z =map fst $ filter (even.snd) $ zip s [1..]

main = do
  inputjar <- getLine
  let n = read inputjar :: Int
  solve n

solve :: Int -> IO ()
solve 0 = putStr ""
solve n = do
  input <- getLine
--   let list = read ("[" ++ map (\x -> if x == ' ' then ',' else x) input ++ "]") :: [Int]
  solveCase input
  solve (n - 1)

solveCase :: [Char] -> IO()
solveCase s = putStrLn $ [s !! i | i <- [0,2..(length s - 1)]] ++ [last s]

-- solveCase :: [Int] -> IO ()
-- solveCase (x : y : n : [])
--   | tmp <= n = print tmp
--   | otherwise = print $ tmp - x
--   where
--     tmp = n - (n `mod` x) + y

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

solve :: String -> String
solve (x:xs) = x : f xs
  where
    f [x] = [x]
    f (x:y:xs) = x : f xs

main = getContents >>= putStrLn . unlines . map f .  tail . lines where
    f [] = ""
    f [x,y] = [x,y]
    f (x:_:xs) = x : f xs

import Control.Monad

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

main :: IO()
main = do
    [t] <- getInts
    replicateM_ t solve

solve :: IO()
solve = do
    b <- getLine
    let c = [head b] ++ b ++ [last b]
    let n = length c
        a = [c !! i | i <- [0,2..(n-1)]]
    putStrLn a

import Control.Monad

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

main :: IO()
main = do
    [t] <- getInts
    replicateM_ t solve

solve :: IO()
solve = do
    b <- getLine
    putChar $ head b
    putStrLn $ map fst $ filter (even.snd) $ zip b [1..]

import Control.Monad

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

main :: IO()
main = do
    [t] <- getInts
    replicateM_ t routine

routine :: IO()
routine = do
    b <- getLine
    putStrLn $ solve b

solve :: String -> String
solve (h:xs) = h : (map fst $ filter (even.snd) $ zip xs [0..])
solve x = x

solve :: String -> String
solve (a:b:[]) = [a,b]
solve (a:b:xs) = [a,b]++( map snd . filter (even . fst) . zip [1..] . init $ xs) ++ [(last xs)]

solveCase :: Int -> IO()
solveCase 0 = return ()
solveCase t = do
  test <- getLine
  putStrLn . show . solve  $ test
  solveCase (t-1)

getInt :: IO Int
getInt = fmap read getLine

main :: IO()
main = do
  n <- getInt
  solveCase n


import qualified Data.ByteString.Char8 as B
import Data.Maybe

num n [x,y] =
    let z = (x-1)*n+(y-1)
        q = (z `div` 2) + 1
        r = ((n*n+(if even n then 0 else 1))`div`2)
    in if even x
        then if odd z
            then q + if odd n then r else 0
            else q + if odd n then 0 else r
        else q + if even z then 0 else r

int = fst . fromJust . B.readInteger
ints = map int . B.words

main = do
     [n,k] <-  ints <$> B.getLine
     B.interact $ B.unlines . map ( B.pack .  show . (num n) . ints ) . B.lines

import qualified Data.ByteString.Char8 as B
import Data.Maybe

num n [x,y] =
    let z = (x-1)*n+(y-1) in
    if even x
        then if odd z
            then if odd n then ((n*n+1)`div`2) + (z `div` 2) + 1  else (z `div` 2) + 1
            else if odd n then (z `div` 2) + 1 else ((n*n+(if even n then 0 else 1))`div`2) + z `div` 2 + 1
        else if even z
            then (z `div` 2) + 1
            else ((n*n+(if even n then 0 else 1))`div`2) + z `div` 2 + 1

int = fst . fromJust . B.readInteger
ints = map int . B.words

main = do
     [n,k] <-  ints <$> B.getLine
     B.interact $ B.unlines . map ( B.pack .  show . (num n) . ints ) . B.lines

import qualified Data.ByteString.Char8 as B
import Data.Maybe

num n [x,y] =
    let z = (x-1)*n+(y-1)
        q = (z `div` 2) + 1
        r = ((n*n+(if even n then 0 else 1))`div`2)
    in if even x
        then q +
            if odd z
                then if odd n then r else 0
                else if odd n then 0 else r
        else q + if odd z then r else 0

int = fst . fromJust . B.readInteger
ints = map int . B.words

main = do
     [n,k] <-  ints <$> B.getLine
     B.interact $ B.unlines . map ( B.pack .  show . (num n) . ints ) . B.lines

import qualified Data.ByteString.Char8 as B
import Data.Maybe

num n [x,y] =
    let z = (x-1)*n+(y-1) in
    if even x
        then if odd z
            then (z `div` 2) + 1
            else (n*n`div`2) + z `div` 2 + 1
        else if even z
            then (z `div` 2) + 1
            else (n*n`div`2) + z `div` 2 + 1

int = fst . fromJust . B.readInt
ints = map int . B.words

main = do
     [n,k] <-  ints <$> B.getLine
     B.interact $ B.unlines . map ( B.pack .  show . (num n) . ints ) . B.lines

{-

4 5
1 1
4 4
4 3
3 2
2 4

-}

import qualified Data.ByteString.Char8 as B
import Data.Maybe

num n [x,y] =
    let z = (x-1)*n+(y-1) in
    if even x
        then if odd z
            then if odd n then ((n*n+1)`div`2) + (z `div` 2) + 1  else (z `div` 2) + 1
            else if odd n then (z `div` 2) + 1 else ((n*n+(if even n then 0 else 1))`div`2) + z `div` 2 + 1
        else if even z
            then (z `div` 2) + 1
            else ((n*n+(if even n then 0 else 1))`div`2) + z `div` 2 + 1

int = fst . fromJust . B.readInt
ints = map int . B.words

main = do
     [n,k] <-  ints <$> B.getLine
     B.interact $ B.unlines . map ( B.pack .  show . (num n) . ints ) . B.lines


module Main where

import Data.List
import Control.Monad (guard, replicateM)

sum2is3 :: [Int] -> Bool
sum2is3 xs =
  f sortedXs || f (reverse sortedXs)
 where
  sortedXs = sort xs
  f sl = sum (take 2 sl) == last sl

maySplit :: [Int] -> Bool
maySplit xs =
  x1 == x2 || x2 == x3
 where
  sxs = sort xs
  (x1, x2, x3) = (sxs !! 0, sxs !! 1, sxs !! 2)

solve :: [Int] -> String
solve xs
  | odd (sum xs) = "NO"
  | sum2is3 xs = "YES"
  | otherwise = if maySplit xs then "YES" else "NO"
 where
  rs = reverse $ sort xs

readLineInts :: IO [Int]
readLineInts = do
  inputs <- words <$> getLine
  pure $ read <$> inputs

getInt = read <$> getLine

main :: IO ()
main = do
  t <- getInt
  ints <- replicateM t readLineInts
  let solutions = solve <$> ints
  mapM_ putStrLn solutions

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

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

readIntegers :: IO [Integer]
readIntegers = map (fst . fromJust . C.readInteger) . C.words <$> C.getLine

possible :: ([Int]->Bool)
possible (a:b:c:[]) = (a==b && c`mod`2==0) || (b-a==c)

main :: IO ()
main = do
    [t] <- readInts
    replicateM_ t $ do
        [a,b,c] <- readInts
        putStrLn $ if any possible (permutations [a,b,c]) then "YES" else "NO"

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

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

readIntegers :: IO [Integer]
readIntegers = map (fst . fromJust . C.readInteger) . C.words <$> C.getLine

possible :: ([Int]->Bool)
possible (a:b:c:[]) = (a==b && c`mod`2==0) || (b-a==c)

main :: IO ()
main = do
    [t] <- readInts
    replicateM_ t $ do
        ar <- readInts
        putStrLn $ if any possible $ permutations ar then "YES" else "NO"

module Main where

import Control.Monad (replicateM)
import Data.List

solve :: [Int] -> String
solve xs
  | sum (tail rs) == head rs = "YES"
  | even (last rs) && rs !! 0 == rs !! 1 = "YES"
  | otherwise = "NO"
 where
  rs = reverse $ sort xs

readLineInts :: IO [Int]
readLineInts = do
  inputs <- words <$> getLine
  pure $ read <$> inputs

getInt = read <$> getLine

main :: IO ()
main = do
  t <- getInt
  ints <- replicateM t readLineInts
  let solutions = solve <$> ints
  mapM_ putStrLn solutions


import Data.List (sort)

main :: IO ()
main = interact processInput

processInput :: String -> String
processInput input = unlines $ processLines $ drop 1 $ lines input

processLines :: [String] -> [String]
processLines (n_line:a_line:b_line:other_lines)
    = processTest (a_line, b_line) : processLines other_lines
processLines _ = []

processTest :: (String, String) -> String
processTest (a_line, b_line) = output
    where
        a_seq = map read $ words a_line
        b_seq = map read $ words b_line
        output = if canMakeEqual a_seq b_seq then "YES" else "NO"

canMakeEqual :: [Integer] -> [Integer] -> Bool
canMakeEqual current_sequence target_sequence = result
    where
        result = all (`elem` [0, 1]) [tx - x | (x, tx) <- zip (sort current_sequence) (sort target_sequence)]

import qualified Control.Monad as CM
import qualified Data.List as DL

solve :: IO ()
solve = do
  getLine
  asu <- readv
  bsu <- readv
  let
    [as,bs] = DL.sort <$> [asu,bsu]
    diffs = zipWith subtract as bs
    ans = if all (\x->x==0||x==1) diffs then "YES" else "NO"
  putStrLn ans

printv :: Show a => [a] -> IO ()
printv xs =  putStrLn $ unwords $ fmap show xs

readv :: Read a => IO [a]
readv = fmap read . words <$> getLine

main :: IO ()
main = do
  ~[n] <- readv
  CM.replicateM_ n solve


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

import qualified Control.Monad as CM
import qualified Data.List as DL
import System.IO

solve :: IO ()
solve = do
  cs <- getLine
  let
    x = DL.minimum cs
    y = DL.delete x cs
  putStrLn $ x:" " ++ y

printv :: Show a => [a] -> IO ()
printv xs =  putStrLn $ unwords $ fmap show xs

readv :: Read a => IO [a]
readv = fmap read . words <$> getLine

main :: IO ()
main = do
  ~[n] <- readv
  CM.replicateM_ n solve

import Control.Monad
import Data.Foldable (traverse_)
import Data.List

pickSmallest :: String -> (Char, String)
pickSmallest s =
    let min_char = minimum s
        remain = delete min_char s
     in (min_char, remain)

output :: (Char, String) -> IO ()
output (c, s) = putStrLn $ [c] ++ " " ++ s

main :: IO ()
main = do
    no_of_input <- getLine
    inputs <- replicateM (read no_of_input) getLine
    let ans = map pickSmallest inputs
    traverse_ (output) ans

import Control.Arrow ((>>>))
import Data.List

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

solve s = let c = minimum s in c : ' ' : delete c s

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

main = do
  n <- read <$> getLine
  forM_ [1 .. n] $ \_ -> do
    line <- getLine
    let x = minimum line
    let xs = let (a, _ : b) = span (/= x) line in a ++ b
    putStrLn $ x : ' ' : xs

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

main = do
  n <- read <$> getLine
  forM_ [1 .. n] $ \_ -> do
    (x : xs) <- sort <$> getLine
    putStrLn $ x : ' ' : xs


module Main where

import Control.Monad
import Data.List

solve :: String -> Integer
solve = solve' []
 where
  solve' have ""
    | null have = 0
    | otherwise = 1
  solve' have (c : cs) =
    let have' = nub $ c : have
     in case length have' of
          4 -> 1 + solve' [] (c : cs)
          _ -> solve' have' cs

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $
    getLine >>= print . solve

--
-- 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-safe                        #-}     -- no warning if inferred as safe
{-# options_ghc -Wno-all-missed-specialisations  #-}     -- "Could not specialise..." when -O1
{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import System.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

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

solve ins = f ins :: Int
  where
    f [] = 0
    f s  = 1 + f rest
      where
        ltrs = take 3 . L.nub $ s
        rest = dropWhile (`elem` ltrs) s

module Main where

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

main = do
  tStr <- getLine
  let t = read tStr :: Int
  input <- getContents
  let sols = map (format . solve . parse) $ take t $ sep $ lines input
  mapM_ putStrLn sols

sep = id

parse = id

format = show

solve :: String -> Int
solve xs = length $ takeWhile (/= "") $ iterate afterOneDay xs

afterOneDay xs = afterOneDay' [] xs

afterOneDay' _ "" = ""
afterOneDay' ys (x:xs)
  | x `elem` ys = afterOneDay' ys xs
  | length ys < 3 = afterOneDay' (x:ys) xs
  | otherwise = x:xs

import Data.Set (Set, empty, insert, member, size)

calcH :: Set Char -> String -> Int
calcH _ [] = 1
calcH s (x: xs) = if (size s == 3) && (not (x `member` s))
  then calcH (insert x empty) xs + 1
  else calcH (insert x s) xs

calc :: String -> Int
calc a = calcH empty a

for :: Int -> IO ()
for 0 = pure ()
for i = do
  a <- getLine
  print $ calc a
  for $ i - 1

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

{- END OF GENERAL -}

solve :: String -> Int
solve str = solve' str []
    where
        solve' :: String -> [Char] -> Int
        solve' [] _ = 1
        solve' s@(c:otherS) memory
            | L.length ([c] `L.union` memory) > 3 = 1 + solve' s []
            | otherwise = solve' otherS $ [c] `L.union` memory

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        s <- B8.getLine <&> head . B8.words
        let answer = solve (B8.unpack s)
        printf "%d\n" answer


{-# OPTIONS_GHC -O2 #-}

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

main = do
  tStr <- getLine
  let t = read tStr :: Int
  input <- getContents
  let sols = map (format . solve . parse) $ take t $ sep $ lines input
  mapM_ putStrLn sols

sep (x:y:xs) = (x,y):(sep xs)

parse (x,y) = (read $ (words x) !! 1, map read $ words y)

format = show

solve (k,as) = base + extra
  where base = sum ds
        (ds, ms) = unzip $ map (`divMod` k) as
        msAsc = sort ms
        msDes = reverse msAsc
        l = length ms
        extra = cnt 0 (l-1) msDes msAsc
        cnt i j _ _
          | i >= j = 0
        cnt i j (x:xs) (y:ys)
          | x + y >= k = 1 + cnt (i+1) (j-1) xs ys
          | otherwise = cnt i (j-1) (x:xs) ys

{-# OPTIONS_GHC -O2 #-}

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

main = do
  tStr <- getLine
  let t = read tStr :: Int
  input <- getContents
  let sols = map (format . solve . parse) $ take t $ sep $ lines input
  mapM_ putStrLn sols

sep (x:y:xs) = (x,y):(sep xs)

parse (x,y) = (read $ (words x) !! 1, map read $ words y)

format = show

solve (k,as) = base + extra
  where base = sum ds
        (ds, ms) = unzip $ map (`divMod` k) as
        msAsc = sort ms
        msDes = reverse msAsc
        l = length ms
        extra = cnt 0 0 (l-1) msDes msAsc
        cnt s i j _ _
          | i >= j = s
        cnt s i j (x:xs) (y:ys)
          | x + y >= k = cnt (s+1) (i+1) (j-1) xs ys
          | otherwise = cnt s i (j-1) (x:xs) ys

module Main where

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

main = do
  tStr <- getLine
  let t = read tStr :: Int
  input <- getContents
  let sols = map (format . solve . parse) $ take t $ sep $ lines input
  mapM_ putStrLn sols

sep (x:y:xs) = (x,y):(sep xs)

parse (x,y) = (read $ (words x) !! 1, map read $ words y)

format = show

solve (k,as) = base + extra
  where base = sum ds
        (ds, ms) = unzip $ map (`divMod` k) as
        msAsc = sort ms
        msDes = reverse msAsc
        l = length ms
        extra = cnt 0 (l-1) msDes msAsc
        cnt i j _ _
          | i >= j = 0
        cnt i j (x:xs) (y:ys)
          | x + y >= k = 1 + cnt (i+1) (j-1) xs ys
          | otherwise = cnt i (j-1) (x:xs) ys


process :: (Int, Int, Int, Int) -> Int
process (x,y,a,b)
    | r == 0 = q
    | otherwise = -1
    where
        d = y-x
        c = a+b
        r = d `mod` c
        q = d `div` c

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    t <- fmap readInt getLine
    ts <- fmap (map (map readInt.words).lines) getContents
    mapM_ print $ map (\[x,y,a,b] -> process (x,y,a,b)) ts

module Main where

main :: IO ()
main = interact $ unlines . map (show . solve . readIntegers) . takeNLines . lines
  where
  takeNLines (l:ls) = take (read l) ls
  readIntegers = map read . words

solve :: [Integer] -> Integer
solve ls =
  case mod diff summ of
    0 -> div diff summ
    _ -> -1
  where
  diff = (ls !! 1 - ls !! 0)
  summ = (ls !! 2 + ls !! 3)

{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
import Data.Ord
import Data.Int
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if s then
                aux s
            else
                return id
        else
            liftM ((.) $ showChar x) $ aux False
    in liftM (flip ($) []) $ aux True

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

class IOInteract a where
    convertEither :: String -> Either String a
    toShowS :: a -> String -> String
    toShow :: a -> String
    toShow x = toShowS x []

instance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where
    convertEither = convertEitherp (undefined :: flag)
    toShowS = toShowSp (undefined :: flag)

type family IOType x where
    IOType String = HString
    IOType [x] = HList
    IOType x = HNormal

class IOInteractp flag a where
    convertEitherp :: flag -> String -> Either String a
    toShowSp :: flag -> a -> String -> String

instance (Show a, Read a) => IOInteractp HNormal a where
    convertEitherp _ x = readEither x
    toShowSp _ x = shows x

instance IOInteractp HString String where
    convertEitherp _ x = Right x
    toShowSp _ x = showString x

instance (IOInteract a) => IOInteractp HList [a] where
    convertEitherp _ x = mapM convertEither $ words x
    toShowSp _ [] = id
    toShowSp _ (x : []) = toShowS x
    toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs

get :: IOInteract a => EIO a
get = ExceptT $ liftM convertEither getToken
put :: IOInteract a => a -> EIO ()
put = lift . putStr . toShow
putln :: IOInteract a => a -> EIO ()
putln = lift . putStrLn . toShow

main :: IO ()
main = do
    o <- runExceptT main_
    case o of
        Right () -> return ()
        Left s -> putStrLn s

main_ :: EIO ()
-- template --
main_ = do
    t <- get :: EIO Int
    replicateM_ t f1

f1 :: EIO ()
f1 = do
    (x, y, a, b) <- liftM4 (,,,) get get get get
    putln $ f2 x y a b

f2 :: Int64 -> Int64 -> Int64 -> Int64 -> Int64
f2 x y a b =    let d = (div (y - x) (a + b)) in
                let r = (mod (y - x) (a + b)) in
                if r /= 0 || d < 0 then -1
                else d

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

process [a,b,c,d] | mod  (b-a) (c+d)>0 = -1
                  | otherwise = div (b-a) (c+d)

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

parse :: String -> String
parse input = show $ solve x y a b
  where [x, y, a, b] = map (\x -> read x :: Integer) $ words input

solve :: Integer -> Integer -> Integer -> Integer -> Integer
solve x y a b
  | mod (y-x) (a+b) == 0 = div (y-x) (a+b)
  | otherwise = -1

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


import Data.Set
import Data.Int

countDup :: Set Int64 -> Int64 -> [Int64] -> Int
countDup _ _ [] = 0
countDup seen last (head:tail)
  | member head seen = 1 + countDup (fromList [last, head]) head tail
  | otherwise = countDup (insert head seen) head tail

solve :: [Int64] -> Int
solve a = countDup (singleton 0) 0 cum
  where cum = scanl1 (+) a

main = do
  _ <- getLine
  sa <- getLine
  let a = [read x :: Int64 | x <- words sa]
  putStrLn $ show $ solve a

import Control.Arrow ((>>>))
import qualified Data.Set as Set

main :: IO ()
main =
  interact $
    lines
      >>> drop 1
      >>> head
      >>> words
      >>> map read
      >>> solve
      >>> show
      >>> (++ "\n")

type SetInt = Set.Set Integer

solve :: [Integer] -> Integer
solve a = compute (Set.singleton 0) 0 a

compute :: SetInt -> Integer -> [Integer] -> Integer
compute _ _ [] = 0
compute pres pre (x : a) =
  if Set.member pre' pres
    then 1 + compute (Set.fromList [x, 0]) x a
    else compute (Set.insert pre' pres) pre' a
  where pre' = pre + x

import Control.Monad
import Data.Set (Set, insert, member, empty)

getList :: (Read t) => IO [t]
getList = getLine >>= return . (map read) . words

getOne :: (Read t) => IO t
getOne = getLine >>= return . read

main :: IO ()
main = do
  -- t <- getOne
  let t = 1
  replicateM_ t solve

solve :: IO ()
solve = do
  n <- getOne :: IO Int
  ls <- getList
  print $ countAns ls

includeZero :: Integral a => Set a
includeZero = 0 `insert` empty

countAns :: (Integral a) => [a] -> a
countAns ls = countZeros includeZero ls 0

countZeros :: (Integral a) => Set a -> [a] -> a -> a
countZeros _ [] _ = 0
countZeros sums all@(x:xs) sum
  | ns `member` sums = 1 + countZeros includeZero all 0
  | otherwise = countZeros (ns `insert` sums) xs ns
  where ns = sum + x

import Data.List ( foldl' )
import Data.Int
import qualified Data.Set as Set

data State = State !Int64 !(Set.Set Int64) !Int

step :: State -> Int64 -> State
step (State currPS activePS count) v = let
  nextPS = v + currPS
  in  if  Set.member nextPS activePS
  then  State v (Set.fromList [0, v]) (count + 1)
  else  State nextPS (Set.insert nextPS activePS) count

solve :: [Int64] -> Int
solve li = let
  State _ _ ct = foldl' step (State 0 (Set.singleton 0) 0) li
  in  ct

main :: IO ()
main = do
  _nStr <- getLine
  a <- map read . words <$> getLine
  print $ solve a

import qualified Data.Set as S

main :: IO ()
main = do
    _ <- getLine
    a <- map read . words <$> getLine
    print $ (\(_, y, _) -> y) $ foldl processElem (S.singleton 0, 0, 0) $ scanl1 (+) a

processElem :: (S.Set Integer, Integer, Integer) -> Integer -> (S.Set Integer, Integer, Integer)
processElem (s, c, p) x
                   | S.member x s = (S.fromList [p, x], c + 1, x)
                   | otherwise = (S.insert x s, c, x)

import Data.Set

countDup :: Set Int -> Int -> [Int] -> Int
countDup _ _ [] = 0
countDup seen last (head:tail)
  | member head seen = 1 + countDup (fromList [last, head]) head tail
  | otherwise = countDup (insert head seen) head tail

solve :: [Int] -> Int
solve a = countDup (singleton 0) 0 cum
  where cum = scanl1 (+) a

main = do
  _ <- getLine
  sa <- getLine
  let a = [read x :: Int | x <- words sa]
  putStrLn $ show $ solve a


import Control.Monad
import Data.Array
import Data.Maybe
import qualified Data.ByteString.Char8 as B

readB s = a
    where Just (a,_) = B.readInt s

main = do
    a <- liftM (map readB . B.words) (B.getLine >> B.getLine) :: IO [Int]
    let b = listArray (0, length a) $ (map snd) $ scanl build (0, ((-1,-1), (-1,-1))) a
    B.getContents >>= putStr . unlines . (map (show.(solve b).(map readB). B.words)).  B.lines

build (i, ((a,ai), (b,bi))) n
    | n==a      = ((i+1), ((a,(i+1)), (b,bi)))
    | otherwise = ((i+1), ((n,(i+1)), (a,ai)))

solve b [l,r,val]
    | x==val = if (yi>=l) then yi else (-1)
    | otherwise = xi
    where
        ((x,xi),(y,yi)) = b!r

import Control.Monad
import Data.Array.Unboxed
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as B
type Vi = UArray Int Int
type Pii = (Int, Int, Int, Int)

readB s = a
    where Just (a,_) = B.readInt s

main = do
    input <- liftM (map readB . B.words) (B.getLine >> B.getLine) :: IO [Int]
    let tuple = unzip4 $ (map snd) $ scanl build (0, (-1,-1, -1,-1)) input
    let [a,ai,b,bi] = ((map (listArray (0, length input))).(\(a,b,c,d)->[a,b,c,d])$tuple) :: [Vi]
    B.getContents >>= putStr . unlines . (map (show.solve a ai b bi.map readB. B.words)).  B.lines

build :: (Int, Pii) -> Int -> (Int, Pii)
build (i, (a,ai,b,bi)) n
    | n==a      = ((i+1), (a,(i+1),b,bi))
    | otherwise = ((i+1), (n,(i+1),a,ai))

solve :: Vi->Vi->Vi->Vi -> [Int] -> Int
solve x xi y yi [l,r,val]
    | (x!r)==val = if ((yi!r)>=l) then (yi!r) else (-1)
    | otherwise = (xi!r)

import Control.Monad
import qualified Data.Map.Strict as Map
import Data.Maybe
import qualified Data.ByteString.Char8 as B

readB s = a
    where Just (a,_) = B.readInt s

main = do
    a <- liftM (map readB . B.words) (B.getLine >> B.getLine) :: IO [Int]
    let b = Map.fromList $ scanl build (0, ((-1,-1), (-1,-1))) a
    B.getContents >>= putStr . unlines . (map (show.(solve b).(map readB). B.words)). B.lines

build (i, ((a,ai), (b,bi))) n
    | n==a      = ((i+1), ((a,(i+1)), (b,bi)))
    | otherwise = ((i+1), ((n,(i+1)), (a,ai)))

solve :: Map.Map Int ((Int,Int),(Int,Int)) -> [Int] -> Int
solve b [l,r,val]
    | x==val = if (yi>=l) then yi else (-1)
    | otherwise = xi
    where
        ((x,xi),(y,yi)) = fromJust $ Map.lookup r b

import Data.Array
import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Control.Monad
import Control.Applicative

main = do
    let b2i = fst . fromJust . B.readInt
    [n, m] <- map b2i . B.words <$> B.getLine
    a <- map b2i . B.words <$> B.getLine
    mls <- forM [1..m] $ const B.getLine
    let lrx = map ((\[l, r, x] -> (l, r, x)) . map b2i . B.words) (mls::[B.ByteString])
    mapM_ (putStrLn . show) $ sol n m a lrx

sol :: Int -> Int -> [Int] -> [(Int, Int, Int)] -> [Int]
sol n m alst lrx = map query lrx
    where
    a = listArray (1, n) alst
    lastDif = listArray (1, n) [dp loc | loc <- [1..n]]
    dp l
      | l == 1 = -1
      | a ! l == a ! (l-1) = lastDif ! (l-1)
      | otherwise = l-1
    query (l, r, x)
        | a ! r /= x = r
        | lastDif ! r >= l = lastDif ! r
        | otherwise = -1

{-# OPTIONS_GHC -O2 #-}

import Control.Applicative ((<$>))
import Data.Array (Array)
import Data.Array.IArray (accumArray, array, listArray, bounds, amap, (!))
import Control.Monad (replicateM)
import Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)
import Data.Maybe (fromJust)
import Prelude hiding (words, lines, getLine, getContents)

readInt' = fst . fromJust . readInt
readInts = map readInt' . words <$> getLine

main = do
  [n, m] <- readInts
  as <- readInts

  qs <- replicateM m readInts :: IO [[Int]]

  let
    ps1 = accumArray (flip (:)) [] (1, 10^6) $ zip as [1..n] :: Array Int [Int]
    ps = amap (compact . reverse) ps1
      where
        compact :: [Int] -> Array Int (Int, Int)
        compact [] = array (1,0) []
        compact (i:is) = listArray (1, length l) l :: Array Int (Int, Int)
          where
            l = f i i is
              where
                f i j [] = [(i,j)]
                f i j (k:is)
                  | k == j+1 = f i k is
                  | otherwise = (i,j):(f k k is)

    ys = map solve qs
      where
        solve [l, r, x]
          | b2 == 0 = l
          | otherwise = f $ lookup 1 b2
          where
            b2 = snd $ bounds rs
            rs = ps ! x

            lookup i j
              | i >= j = if l <= rr && ll <= r then Just m else Nothing
              | l > rr = lookup (m + 1) j
              | ll > r = lookup i m
              | otherwise = Just m
              where
                m = (i+j) `div` 2
                (ll, rr) = rs ! m

            f Nothing = l
            f (Just m)
              | ll <= l && r <= rr = -1
              | r > rr = rr + 1
              | l < ll = ll-1
              where
                (ll, rr) = rs ! m

  putStr $ unlines $ map show ys

import Control.Monad
import Data.Array.Unboxed
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as B
type Vi = UArray Int Int
type Pii = (Int, Int, Int, Int)

readB s = a
    where Just (a,_) = B.readInt s

main = do
    input <- liftM (map read . words) (getLine >> getLine) :: IO [Int]
    let tuple = unzip4 $ (map snd) $ scanl build (0, (-1,-1, -1,-1)) input
    let [a,ai,b,bi] = ((map (listArray (0, length input))).(\(a,b,c,d)->[a,b,c,d])$tuple) :: [Vi]
    B.getContents >>= putStr . unlines . (map (show.solve a ai b bi.map readB. B.words)).  B.lines

build :: (Int, Pii) -> Int -> (Int, Pii)
build (i, (a,ai,b,bi)) n
    | n==a      = ((i+1), (a,(i+1),b,bi))
    | otherwise = ((i+1), (n,(i+1),a,ai))

solve :: Vi->Vi->Vi->Vi -> [Int] -> Int
solve x xi y yi [l,r,val]
    | (x!r)==val = if ((yi!r)>=l) then (y!r) else (-1)
    | otherwise = (xi!r)

import Control.Monad
import qualified Data.Map.Strict as Map
import Data.Maybe

main = do
    a <- liftM (map read . words) (getLine >> getLine) :: IO [Int]
    let b = Map.fromList $ scanl build (1, ((-1,-1), (-1,-1))) a
    getContents >>= putStr . unlines . (map (show.(solve b).(map read).words)).lines

build (i, ((a,ai), (b,bi))) n
    | n==a      = ((i+1), ((a,i), (b,bi)))
    | otherwise = ((i+1), ((n,i), (a,ai)))

solve :: Map.Map Int ((Int,Int),(Int,Int)) -> [Int] -> Int
solve b [l,r,val]
    | x==val = if (yi>=l) then yi else (-1)
    | otherwise = xi
    where
        ((x,xi),(y,yi)) = fromJust $ Map.lookup r b


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

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

{-# options_ghc -O3                              #-}

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

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

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

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

--showB False = "NO"
--showB True  = "YES"

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [n,l,r] <- ri
        return (n,l,r)
    mapM_ (putStr.showAns.solve) tcs

showAns Nothing   = unlines ["NO" ]
showAns (Just xs) = unlines ["YES", unwords . map show $ xs]

solve (n,l,r) | ok         = Just ans
              | otherwise  = Nothing
  where
    rs = map (range (l,r)) [1..n]
    ok = all (uncurry (<=)) rs
    ans = zipWith (*) [1..n] (map fst rs)

range (l,r) x = (   ((l-1)`div`x) + 1,
                    ( r   `div`x)    )

find l i
	| gcd l i == i 		= l
	| otherwise		= ($!) find (l + i -  (l `mod` i)) i

solve n l r
	| maximum a < (r+1) 		= "YES\n" ++ (printArr a) ++ "\n"
	| otherwise 			= "NO\n"
	where
		a =  ($!) map (find l) [1..n]
		printArr [] = " "
		printArr (x:xs) = show x ++ " " ++ printArr xs

exec 0 = pure ()
exec t = do
	(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]
	putStr $ solve n l r
	exec (t-1)

main = do
	t <- read <$> getLine :: IO Int
	exec t

find l i
	| gcd l i == i 		= l
	| otherwise		= find (l + i -  (l `mod` i)) i

solve n l r
	-- | abs (r - l) < n-1	 	= "NO\n"
	| maximum a < (r+1) 		= "YES\n" ++ (printArr a) ++ "\n"
	| otherwise 			= "NO\n"
	where
		a =  map (find l) [1..n]
		printArr [] = " "
		printArr (x:xs) = show x ++ " " ++ printArr xs

exec 0 = pure ()
exec t = do
	(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]
	putStr $ solve n l r
	exec (t-1)

main = do
	t <- read <$> getLine :: IO Int
	exec t

find l i
	| gcd l i == i 		= l
	| otherwise		= find (l + 1) i

solve n l r
	| abs (r - l) < n-1	 	= "NO\n"
	| maximum a < (r+1) 		= "YES\n" ++ (printArr a) ++ "\n"
	| otherwise 			= "NO\n"
	where
		a =  map (find l) [1..n]
		printArr [] = " "
		printArr (x:xs) = show x ++ " " ++ printArr xs

exec 0 = pure ()
exec t = do
	(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]
	putStr $ solve n l r
	exec (t-1)

main = do
	t <- read <$> getLine :: IO Int
	exec t

find l i
	| gcd l i == i 		= l
	| otherwise		= find (l + i -  (l `mod` i)) i

solve n l r
	| abs (r - l) < n-1	 	= "NO\n"
	| maximum a < (r+1) 		= "YES\n" ++ (printArr a) ++ "\n"
	| otherwise 			= "NO\n"
	where
		a =  map (find l) [1..n]
		printArr [] = " "
		printArr (x:xs) = show x ++ " " ++ printArr xs

exec 0 = pure ()
exec t = do
	(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]
	putStr $ solve n l r
	exec (t-1)

main = do
	t <- read <$> getLine :: IO Int
	exec t

find l i
	| gcd l i == i 		= l
	| otherwise		= find (l + i -  (l `mod` i)) i

solve n l r
	| abs (r - l) < n `div` 2 	= "NO\n"
	| maximum a < (r+1) 		= "YES\n" ++ (printArr a) ++ "\n"
	| otherwise 			= "NO\n"
	where
		a =  map (find l) [1..n]
		printArr [] = " "
		printArr (x:xs) = show x ++ " " ++ printArr xs

exec 0 = pure ()
exec t = do
	(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]
	putStr $ solve n l r
	exec (t-1)

main = do
	t <- read <$> getLine :: IO Int
	exec t

find l i
	| gcd l i == i 		= l
	| otherwise		= find (l + i -  (l `mod` i)) i

solve n l r
	| abs (r - l) < n `div` 2 	= "NO1\n"
	| maximum a < (r+1) 		= "YES\n" ++ (printArr a) ++ "\n"
	| otherwise 			= "NO\n"
	where
		a =  map (find l) [1..n]
		printArr [] = " "
		printArr (x:xs) = show x ++ " " ++ printArr xs

exec 0 = pure ()
exec t = do
	(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]
	putStr $ solve n l r
	exec (t-1)

main = do
	t <- read <$> getLine :: IO Int
	exec t


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

co x = div  (x* (x-1)) 2

main= do
	getLine
	s<- map (map (fst.fromJust.C.readInt)). map C.words. C.lines <$> C.getContents :: IO [[Int]]
	let [t1,t2]= transpose s
	let r1=  sum $ map co $ filter (>1) $ map length $group $ sort $ zipWith (+) t1 t2
	let r2=  sum $ map co $ filter (>1) $ map length $group $ sort $ zipWith (-) t1 t2
	print $ r1+r2

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

import qualified Data.ByteString.Char8 as C

findRes :: (Int -> Int -> Int) -> [(Int, Int)] -> Int
findRes f = (map (uncurry f)) >>> sort >>> group >>> (map length) >>> filter (>1) >>> (map (\x -> x * (x-1) `div` 2)) >>> sum

main :: IO ()
main = do
    getLine
    a <- map (\(x:y:ys) -> (x,y)) . map (map (fst.fromJust.C.readInt)). map C.words. C.lines <$> C.getContents :: IO [(Int, Int)]
    print $ ((findRes (+) &&& findRes (-)) >>> uncurry (+)) a

import Control.Monad
import Data.List
import Numeric

pairs x = (x*x-x) `div` 2

iRead s = case readDec s of [(n,_)] -> n

main = do
	line  <- getLine
	let n = iRead line
	lines <- replicateM n getLine
	let bishops = [map iRead (words l) :: [Int] | l <- lines]
	let [x,y] = transpose bishops
	let p = sum (map pairs (map length (group (sort (zipWith (+) x y)))))
	let s = sum (map pairs (map length (group (sort (zipWith (-) x y)))))
	putStrLn $ show (p+s)

import Control.Monad
import Data.List
import Numeric

pairs x = (x*x-x) `div` 2
iRead s = case readDec s of [(n,_)] -> n

main = do
	line  <- getLine
	lines <- replicateM (iRead line) getLine
	let [x,y] = transpose [map iRead (words l) :: [Int] | l <- lines]
	let p = sum (map pairs (map length (group (sort (zipWith (+) x y)))))
	let s = sum (map pairs (map length (group (sort (zipWith (-) x y)))))
	putStrLn $ show (p+s)

import Control.Monad
import Control.Arrow
import Data.List

getMin :: [Integer] -> Integer
getMin [] = 0
getMin xs = ((minimum &&& (length >>> fromIntegral >>> (`mod` 2))) >>> uncurry (*)) xs

findRes :: (Integer -> Integer -> Integer) -> [(Integer, Integer)] -> Int
findRes f = (map (uncurry f)) >>> sort >>> group >>> (map length) >>> filter (>1) >>> (map (\x -> x * (x-1))) >>> sum

main :: IO ()
main = do
    n <- liftM (read::String -> Integer) getLine
    a <- mapM (\_ -> liftM ((\(x:y:ys) -> (x,y)) . map(read::String->Integer) . words) getLine) [1..n]
    print $ ((findRes (+) &&& findRes (-)) >>> uncurry (+)) a


import Control.Monad (forM_)

solve :: (Ord a1, Num a2) => a1 -> a1 -> a2 -> a2 -> a2 -> [a1] -> (a2, a2)
solve max min maxIdx minIdx i [] = (maxIdx, minIdx)
solve max min maxIdx minIdx i (x : xs)
    | x >= max && x <= min = solve x x i i (i + 1) xs
    | x <= min = solve max x maxIdx i (i + 1) xs
    | x >= max = solve x min i minIdx (i + 1) xs
    | otherwise = solve max min maxIdx minIdx (i + 1) xs

main :: IO ()
main = do
    t <- readLn :: IO Int
    forM_ [1 .. t] $ \i -> do
        n <- readLn :: IO Int
        l <- getLine
        let arr = (map read . words) l :: [Int]
        let (a, b) = if n == 1 then (0,0) else solve (-1) (10^9) (-1) (-1) 0 arr
        putStrLn $ show (a + 1) ++ " " ++ show (b + 1)

import Lib
import Data.List
import Control.Monad

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

solvet :: IO ()
solvet = do
    n <- getLine
    xs <- map read . words <$> getLine :: IO [Int]
    let (Just minPos) = succ <$> minimum xs `elemIndex` xs
    let (Just maxPos) = succ <$> maximum xs `elemIndex` xs
    putStrLn (show minPos ++ " " ++ show maxPos)

import Control.Monad (forM_)

solve :: (Ord a1, Num a2) => a1 -> a1 -> a2 -> a2 -> a2 -> [a1] -> (a2, a2)
solve max min maxIdx minIdx i [] = (maxIdx, minIdx)
solve max min maxIdx minIdx i (x : xs)
    | x >= max = solve x min i minIdx (i + 1) xs
    | x <= min = solve max x maxIdx i (i + 1) xs
    | otherwise = solve max min maxIdx minIdx (i + 1) xs

main :: IO ()
main = do
    t <- readLn :: IO Int
    forM_ [1 .. t] $ \i -> do
        n <- readLn :: IO Int
        l <- getLine
        let arr = (map read . words) l :: [Int]
        let (a, b) = if n == 1 then (0,0) else solve (-1) (10^9) (-1) (-1) 0 arr
        putStrLn $ show (a + 1) ++ " " ++ show (b + 1)

import Control.Monad (forM_)

solve :: (Ord a1, Num a2) => a1 -> a1 -> a2 -> a2 -> a2 -> [a1] -> (a2, a2)
solve max min maxIdx minIdx i [] = (maxIdx, minIdx)
solve max min maxIdx minIdx i (x : xs)
    | x <= min = solve max x maxIdx i (i + 1) xs
    | x >= max = solve x min i minIdx (i + 1) xs
    | otherwise = solve max min maxIdx minIdx (i + 1) xs

main :: IO ()
main = do
    t <- readLn :: IO Int
    forM_ [1 .. t] $ \i -> do
        n <- readLn :: IO Int
        l <- getLine
        let arr = (map read . words) l :: [Int]
        let (a, b) = if n == 1 then (0,0) else solve (-1) (10^9) (-1) (-1) 0 arr
        putStrLn $ show (a + 1) ++ " " ++ show (b + 1)

import Control.Monad (forM_)

solve :: (Ord a1, Num a2) => a1 -> a1 -> a2 -> a2 -> a2 -> [a1] -> (a2, a2)
solve max min maxIdx minIdx i [] = (maxIdx, minIdx)
solve max min maxIdx minIdx i (x : xs)
    | x < min = solve max x maxIdx i (i + 1) xs
    | x > max = solve x min i minIdx (i + 1) xs
    | otherwise = solve max min maxIdx minIdx (i + 1) xs

main :: IO ()
main = do
    t <- readLn :: IO Int
    forM_ [1 .. t] $ \i -> do
        n <- readLn :: IO Int
        l <- getLine
        let arr = (map read . words) l :: [Int]
        let (a, b) = if n == 1 then (0,0) else solve (-1) (10^9) (-1) (-1) 0 arr
        putStrLn $ show (a + 1) ++ " " ++ show (b + 1)

import Lib
import Data.List
import Control.Monad

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

solvet :: IO ()
solvet = do
    n <- getLine
    xs <- map read . words <$> getLine :: IO [Int]
    let (Just minPos) = succ <$> minimum xs `elemIndex` xs
    let (Just maxPos) = succ <$> maximum xs `elemIndex` xs
    print (show minPos ++ " " ++ show maxPos)


import Control.Monad

printResult = do
    n <- readLn :: IO Int
    print $ div (n+1) 10

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

import Control.Monad

calc :: Int -> Int
calc n = (n+1) `div` 10

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let n = read line :: Int
    print $ calc n

module Main where
import Data.Char (ord)
main = interact solve

solve inp =
    let
        linp = lines inp
        t = read $ head linp :: Int
        inps = take t . tail $ linp
        logic n | length n == 1 = if n == "9" then 1 else 0
                | otherwise = if last n == '9' then read (init n) + 1 else read (init n) :: Int
    in
        unlines . map (show . logic) $ inps

testcase :: Int -> IO ()
testcase 0 = return ()
testcase i = (readLn :: IO Int) >>= (print . (`div` 10) . (+1)) >> testcase (i - 1)

main :: IO ()
main = (readLn :: IO Int) >>= testcase

import Control.Monad

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

solve :: IO ()
solve = do
  n <- readLn :: IO Int
  print $ ans n

ans x
  | x `mod` 10 == 9 = myAns+1
  | otherwise = myAns
  where myAns = x `div` 10

main = interact $ unlines . map show . map(\x -> x `div` 10) . map (+1) . map read . tail . words

import Control.Monad (replicateM_)

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    n <- readLn
    print $ (n + 1) `div` 10

module Main where

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

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

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

printList :: (Show a) => [a] -> IO ()
printList = putStrLn . list2Str

list2Str :: (Show a) => [a] -> String
list2Str = concat . intersperse " " . fmap show

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

tCase :: IO () -> IO ()
tCase x = do
    t <- readLn
    replicateM_ t $ x

main :: IO ()
main = tCase process

--------------------------------------------------------------------------------

process :: IO ()
process = do
    n <- readLn
    print $ (n + 1) `div` 10

import Control.Arrow ((>>>))

main :: IO ()
main = interact $ words >>> drop 1 >>> map (read >>> solve >>> show) >>> unlines

solve :: Int -> Int
solve n = (n + 1) `div` 10

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

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

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n] <- readInts
    putInts [div (n + 1) 10]

type SIO = StateT P.ByteString IO

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

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

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


module Main where

import Control.Monad

import Data.Int
import Data.Ratio

main :: IO ()
main = do
    n <- ((read :: String -> Int) <$> getLine)
    replicateM_ n action

action = getLine >>= putStrLn . answer . guess . read

guess :: Int64 -> Bool
guess x = any (\a -> let r = x - a^3 in r > 0 && (round $ (fromIntegral r)**(1/3))^3 == r) [1..9999]

answer True = "yes"
answer False = "no"

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

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

------

type Hopper r = State [r]

type HopperT r = StateT [r]

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

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

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

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

type MonadHopper r m = MonadState [r] m

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

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

------

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

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

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

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

------

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

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

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

------

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

run1 = bool "NO" "YES" . solve <$> popInteger

solve x = any test $ takeWhile (\a -> 2 * a ^ 3 <= x) [1..]
  where
    test a = Set.member (x - a ^ 3) cubes

    cubes = Set.fromList $ takeWhile (<= x) $ map (^ 3) [1..]

--prewritten code: https://github.com/antma/algo
{-# 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

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

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

p3 :: Int64 -> Int64
p3 x = x * x * x

f :: Int64 -> Int64 -> Bool
f x y
  | xxx < y = f (succ x) y
  | xxx == y = True
  | otherwise = False
  where xxx = p3 x

cube :: Int64 -> Bool
cube x = f xxx x
  where
    xxx :: Int64
    xxx = fromIntegral $ floor $ exp $ ((log $ fromIntegral x) / 3.0)

yes = byteString $ C.pack "YES\n"
no = byteString $ C.pack "NO\n"

test :: Int64 -> Builder
test n = if x then yes else no
  where x = any (\(_, bbb) -> cube bbb) $ takeWhile (\(u, v) -> u <= v) $ [(aaa, bbb) | a <- [1 ..], let aaa = p3 a, let bbb = n - aaa]

solve :: [Int64] -> Builder
solve (n:l) = mconcat $ map test l'
  where
    l' = take (fromIntegral n) l

main :: IO ()
main = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents

import qualified Data.ByteString.Lazy.Char8 as P

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class

import Data.Int

cbrt :: Int64 -> Int64
cbrt x = let
  cr :: Double
  cr = fromIntegral x ** (1 / 3)
  cr32 :: Int
  cr32 = floor cr -- may be too small by 1 if perfect cube, but that's OK
  in  fromIntegral cr32

solve :: Int64 -> Bool
solve n = let
  incrs = map (\i -> i*i*i) [1..]
  decrs = map (\i -> i*i*i) $ takeWhile (> 0) $ iterate (subtract 1) $ cbrt n
  go _ [] = False
  go xs@(x:txs) ys@(y:tys) = case  compare (x + y) n  of
    LT -> go txs ys
    EQ -> True
    GT -> go xs tys
  go [] _ = error "solve.go: overflow?"
  in  go incrs decrs

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [x] <- readInts
    lift $ P.putStr $ case  solve x  of
      True  -> P.pack "YES\n"
      False -> P.pack "NO\n"

type SIO = StateT P.ByteString IO

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

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

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

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class

import Data.Int

isCube :: Int64 -> Bool
isCube x = let
  cr :: Int
  -- Seriously?  (floor :: Double -> Int64)?
  -- THAT's where the majority of my runtime was spent?
  cr = floor $ 0.5 + fromIntegral x ** (1 / 3.0 :: Double)
  cr64 = fromIntegral cr
  in  cr64 * cr64 * cr64 == x

solve :: Int64 -> Bool
solve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do
  [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  t <- readInt
  answers <- replicateM t $ solve <$> readInt
  putBools answers

type SIO = StateT P.ByteString IO

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

readInt :: Num t => SIO t
readInt = do
  currLine <- readLine
  let  [Just (x, _)] = map P.readInteger $ P.words currLine
  pure $ fromInteger x

putBools :: [Bool] -> SIO ()
putBools = let
  res True = B.byteString $ S.pack "YES\n"
  res False = B.byteString $ S.pack "NO\n"
  in  lift . B.hPutBuilder stdout . mconcat . map res

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

import Data.Int
import Data.Char

isCube :: Int64 -> Bool
isCube x = let
  cr = floor $ 0.5 + exp (log (fromIntegral x) / (3.0 :: Double))
  in  cr*cr*cr == x

solve :: Int64 -> Bool -- these should get inlined anyway, right?
solve v = any (\(_, y) -> isCube y) $ takeWhile (\(x, y) -> x <= y) $ do
  [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]

zeroVal :: Int64
zeroVal = fromIntegral $ ord '0' -- 48

-- Is this THAT much faster than P.readInteger?
parseUInt64 :: P.ByteString -> Int64
parseUInt64 = L.foldl' (\x y -> x * 10 + fromIntegral y - zeroVal) 0

main :: IO ()
main = do
  inp <- P.getContents
  let  vals = tail $ map parseUInt64 $ P.words inp
  putBools $ map solve vals

putBools :: [Bool] -> IO ()
putBools = let
  res True = B.byteString $ S.pack "YES\n"
  res False = B.byteString $ S.pack "NO\n"
  in  B.hPutBuilder stdout . mconcat . map res

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

import Data.Int
import Data.Char

isCube :: Int64 -> Bool
isCube x = let
  cr = floor $ 0.5 + exp (log (fromIntegral x) / (3.0 :: Double))
  in  cr*cr*cr == x

solve :: Int64 -> Bool
solve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do
  [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]

zeroVal :: Int64
zeroVal = fromIntegral $ ord '0' -- 48

-- Is this THAT much faster than P.readInteger?
parseUInt64 :: S.ByteString -> Int64
parseUInt64 = SR.foldl' (\x y -> x * 10 + fromIntegral y - zeroVal) 0

main :: IO ()
main = do
  inp <- S.getContents
  let  vals = tail $ map parseUInt64 $ S.words inp
  putBools $ map solve vals

putBools :: [Bool] -> IO ()
putBools = let
  res True = B.byteString $ S.pack "YES\n"
  res False = B.byteString $ S.pack "NO\n"
  in  B.hPutBuilder stdout . mconcat . map res

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

import Data.Int
import Data.Char

isCube :: Int64 -> Bool
isCube x = let
  cr = floor $ 0.5 + exp (log (fromIntegral x) / (3.0 :: Double))
  in  cr*cr*cr == x

solve :: Int64 -> Bool
solve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do
  [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]

zeroVal :: Int64
zeroVal = fromIntegral $ ord '0' -- 48

-- Is this THAT much faster than P.readInteger?
parseUInt64 :: P.ByteString -> Int64
parseUInt64 = L.foldl' (\x y -> x * 10 + fromIntegral y - zeroVal) 0

main :: IO ()
main = do
  inp <- P.getContents
  let  vals = tail $ map parseUInt64 $ P.words inp
  putBools $ map solve vals

putBools :: [Bool] -> IO ()
putBools = let
  res True = B.byteString $ S.pack "YES\n"
  res False = B.byteString $ S.pack "NO\n"
  in  B.hPutBuilder stdout . mconcat . map res

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

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class

import Data.Int

isCube :: Int64 -> Bool
isCube x = let -- OK, it's very stable.
  cr = floor $ 0.5 + exp (log (fromIntegral x) / (3.0 :: Double)) -- is (**) slow?
  in  cr*cr*cr == x

solve :: Int64 -> Bool
solve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do
  [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  t <- readInt -- overflow in input reading, silly me
  answers <- replicateM t $ solve <$> readInt
  putBools answers -- try faster output?

type SIO = StateT P.ByteString IO

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

readInt :: Num t => SIO t
readInt = do
  currLine <- readLine
  let  [Just (x, _)] = map P.readInteger $ P.words currLine
  pure $ fromInteger x

putBools :: [Bool] -> SIO ()
putBools = let
  res True = B.byteString $ S.pack "YES\n"
  res False = B.byteString $ S.pack "NO\n"
  in  lift . B.hPutBuilder stdout . mconcat . map res

import qualified Data.ByteString.Lazy.Char8 as P

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class

import Data.Int

isCube :: Int64 -> Bool
isCube x = let -- OK, it's very stable.
  cr = floor $ 0.5 + exp (log (fromIntegral x) / (3.0 :: Double)) -- is (**) slow?
  in  cr*cr*cr == x

solve :: Int64 -> Bool
solve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do
  [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  t <- readInt -- overflow in input reading, silly me
  replicateM_ t $ do
    x <- readInt
    lift $ P.putStrLn $ case  solve x  of
      True  -> P.pack "YES"
      False -> P.pack "NO"

type SIO = StateT P.ByteString IO

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

readInt :: Num t => SIO t
readInt = do
  currLine <- readLine
  let  [Just (x, _)] = map P.readInteger $ P.words currLine
  pure $ fromInteger x

import qualified Data.ByteString.Lazy.Char8 as P

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class

import Data.Int

isCube :: Int64 -> Bool
isCube x = let -- OK, it's very stable.
  cr = floor $ 0.5 + fromIntegral x ** (1 / 3 :: Double)
  in  cr*cr*cr == x -- is it (^3) that is slow?

solve :: Int64 -> Bool -- I doubt this is more than 30% faster...
solve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do
  [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  t <- readInt -- overflow in input reading, silly me
  replicateM_ t $ do
    x <- readInt
    lift $ P.putStrLn $ case  solve x  of
      True  -> P.pack "YES"
      False -> P.pack "NO"

type SIO = StateT P.ByteString IO

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

readInt :: Num t => SIO t
readInt = do
  currLine <- readLine
  let  [Just (x, _)] = map P.readInteger $ P.words currLine
  pure $ fromInteger x

import qualified Data.ByteString.Lazy.Char8 as P

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class

import Data.Int

isCube :: Int64 -> Bool
isCube x = let -- OK, it's very stable.
  cr = round $ fromIntegral x ** (1 / 3 :: Double)
  in  cr*cr*cr == x -- is it (^3) that is slow?

solve :: Int64 -> Bool -- I doubt this is more than 30% faster...
solve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do
  [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  t <- readInt -- overflow in input reading, silly me
  replicateM_ t $ do
    x <- readInt
    lift $ P.putStrLn $ case  solve x  of
      True  -> P.pack "YES"
      False -> P.pack "NO"

type SIO = StateT P.ByteString IO

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

readInt :: Num t => SIO t
readInt = do
  currLine <- readLine
  let  [Just (x, _)] = map P.readInteger $ P.words currLine
  pure $ fromInteger x

import qualified Data.ByteString.Lazy.Char8 as P

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class

import Data.Int

isCube :: Int64 -> Bool
isCube x = let -- OK, it's very stable.
  cr = fromIntegral x ** (1 / 3 :: Double)
  in  round cr ^ (3 :: Int) == x

solve :: Int64 -> Bool -- I doubt this is more than 30% faster...
solve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do
  [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  t <- readInt -- overflow in input reading, silly me
  replicateM_ t $ do
    x <- readInt
    lift $ P.putStrLn $ case  solve x  of
      True  -> P.pack "YES"
      False -> P.pack "NO"

type SIO = StateT P.ByteString IO

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

readInt :: Num t => SIO t
readInt = do
  currLine <- readLine
  let  [Just (x, _)] = map P.readInteger $ P.words currLine
  pure $ fromInteger x

import qualified Data.ByteString.Lazy.Char8 as P

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class

import Data.Int

isCube :: Int64 -> Bool
isCube x = let -- OK, it's very stable.
  cr = fromIntegral x ** (1 / 3 :: Double)
  in  round cr ^ (3 :: Int) == x

solve :: Int64 -> Bool
solve x = any isCube $ [v | i <- [1..10000], let v = x - i*i*i, v > 0]

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  t <- readInt -- overflow in input reading, silly me
  replicateM_ t $ do
    x <- readInt
    lift $ P.putStrLn $ case  solve x  of
      True  -> P.pack "YES"
      False -> P.pack "NO"

type SIO = StateT P.ByteString IO

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

readInt :: Num t => SIO t
readInt = do
  currLine <- readLine
  let  [Just (x, _)] = map P.readInteger $ P.words currLine
  pure $ fromInteger x

-- import Debug.Trace

type InType  = Integer
type OutType = Bool

bruteLim = 10 ^ 4 + 10
cube x = x * x * x

binSearch l r x
    | l >= r     = cube l == x
    | cube m>= x = binSearch l       m x
    | otherwise  = binSearch (m + 1) r x
    where m = (l + r) `div` 2

isCube = binSearch 1 bruteLim

solve n = any (\x -> isCube (n - cube x)) [1 .. bruteLim]

receive [s] = read s

main = interact (unlines . map (showBool . solve . receive . pure) . tail . lines)
    where showBool True = "YES"
          showBool False = "NO"

-- import Debug.Trace

type InType  = Integer
type OutType = Bool

inpLines = 1

bruteLim = 10 ^ 4 + 10

chunksOf _ [] = []
chunksOf x l  = take x l : chunksOf x (drop x l)

cube x = x * x * x

binSearch l r x
    | l >= r     = cube l == x
    | cube m>= x = binSearch l       m x
    | otherwise  = binSearch (m + 1) r x
    where m = (l + r) `div` 2

isCube = binSearch 1 bruteLim

solve n = any (\x -> isCube (n - cube x)) [1 .. bruteLim]

receive [s] = read s

main = interact (unlines . map (showBool . solve . receive) . chunksOf inpLines . tail . lines)
    where showBool True = "YES"
          showBool False = "NO"

-- import Debug.Trace

type InType  = Integer
type OutType = Bool

inpLines :: Int
inpLines = 1

bruteLim = 10 ^ 4 + 10

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf x l  = take x l : chunksOf x (drop x l)

toArr :: Read a => String -> [a]
toArr = map read . words

cube :: Integer -> Integer
cube x = x * x * x

binSearch :: Integer -> Integer -> Integer -> Bool
binSearch l r x
    | l >= r     = cube l == x
    | cube m>= x = binSearch l       m x
    | otherwise  = binSearch (m + 1) r x
    where m = (l + r) `div` 2

isCube :: Integer -> Bool
isCube = binSearch 1 bruteLim

solve :: InType -> OutType
solve n = any (\x -> isCube (n - cube x)) [1 .. bruteLim]

receive :: [String] -> InType
receive [s] = read s

main :: IO ()
main = interact (unlines . map (showBool . solve . receive) . chunksOf inpLines . tail . lines)
    where showBool True = "YES"
          showBool False = "NO"

cubes :: [Integer]
cubes = [r^3 | r <- [1..10^4]]

isCube :: Integer -> Bool
isCube x = any isRoot [candidate - 1, candidate, candidate + 1]
    where isRoot r = r^3 == x
          candidate = round $ fromIntegral x ** (1/3)

isSumOfCubes :: Integer -> Bool
isSumOfCubes x = any isHalf possibleHalves
    where possibleHalves = takeWhile (<x) cubes
          isHalf cube = isCube (x - cube)

solveTest :: Integer -> String
solveTest x = if isSumOfCubes x then "YES" else "NO"

solve :: String -> String
solve = unlines . map (solveTest . read) . drop 1 . lines

main :: IO ()
main = interact solve

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

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

import Data.Int

isCube :: Int64 -> Bool
isCube x = let
  cr = fromIntegral x ** (1 / 3 :: Double)
  in  round cr ^ (3 :: Int) == x

solve :: Int64 -> Bool
solve x = any isCube $ [v | i <- [1..10000], let v = x - i*i*i, v > 0]

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [x] <- map fromIntegral <$> readInts
    lift $ P.putStrLn $ case  solve x  of
      True  -> P.pack "YES"
      False -> P.pack "NO"

type SIO = StateT P.ByteString IO

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

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

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

-- import Debug.Trace

type InType  = Int
type OutType = Bool

inpLines :: Int
inpLines = 1

bruteLim = 10 ^ 4 + 10

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf x l  = take x l : chunksOf x (drop x l)

toArr :: Read a => String -> [a]
toArr = map read . words

cube :: Int -> Int
cube x = x * x * x

binSearch :: Int -> Int -> Int -> Bool
binSearch l r x
    | l >= r     = cube l == x
    | cube m>= x = binSearch l       m x
    | otherwise  = binSearch (m + 1) r x
    where m = (l + r) `div` 2

isCube :: Int -> Bool
isCube = binSearch 1 bruteLim

solve :: InType -> OutType
solve n = any (\x -> isCube (n - cube x)) [1 .. bruteLim]

receive :: [String] -> InType
receive [s] = read s

main :: IO ()
main = interact (unlines . map (showBool . solve . receive) . chunksOf inpLines . tail . lines)
    where showBool True = "YES"
          showBool False = "NO"