parse :: String -> [Int]
parse = (map read) . words

solve :: [Int] -> [(Int, Int)]
solve [n, m] = (allWithFirst n) ++ (reverseAll $ drop 1 (allWithFirst m))
        where
            allWithFirst x = [(y, 1) | y <- [1 .. x]]
            reverseAll = map (\(x, y) -> (y, x))

output :: [(Int, Int)] -> String
output x = (show $ length x) ++ "\n" ++ outputPairs x

outputPairs [] = "\n"
outputPairs (x:xs) = (show $ fst x) ++ " " ++ (show $ snd x) ++ "\n" ++ outputPairs xs

main = interact $ output . solve . parse

main = do
   [n, m] <- fmap (map read . words) getLine
   let pairs = solve n m
   print $ length pairs
   mapM (\(x, y) -> putStrLn $ show x ++ " " ++ show y) pairs

solve :: Int -> Int -> [(Int, Int)]
solve boys girls = (map (\x -> (1, x)) [1..girls]) ++ (map (\x -> (x, 1)) [2..boys])

main = do
   l <- getContents
   let [n, m] = map read (words l) :: [Int]
   putStrLn $ show (m + n - 1)
   let answer = zip [1,1..] [1..m] ++ zip [2..n] [1,1..]
   sequence_ (map printTuple answer)

   where
      printTuple (a, b) = putStrLn $ (show a) ++ " " ++ (show b)

gen :: Int -> Int -> [(Int, Int)]
gen a b = [(i, j) | i <- [1..a], j <- [1..b], i == 1 || j == 1]

fmt :: (Int, Int) -> String
fmt (i,j) = ((show i)++ " " ++ (show j) ++ "\n")

solve :: String -> String
solve input = (show $ length res) ++ "\n" ++ (concat (map fmt res))
  where (a:b:xs) = map read (words input)
        res = gen a b
main = do
  interact solve

import Control.Applicative
import Data.List

del x (a:as) 	| x==a = as
		| otherwise = a: (del x as)

main= do
	[a,b]<- map read. words <$> getLine::IO [Int]
	print $ a+b-1
	putStr $ unlines $ map (\x->  ( show x) ++ " 1" )   [1..a]
	putStrLn $ unlines $ map (\x->  ( show a) ++ " " ++ show x )   [2..b]

import Control.Monad

main :: IO ()
main = do
  m:n:_ <- liftM (map read . words) getLine
  print (m + n - 1)
  mapM_ putStrLn $ (map ((++) "1 " . show) [1..n]) ++ (map (flip (++) " 1" . show) [2..m])

import Data.List

solve n m = xs ++ ys where
    xs = ["1 " ++ show j | j <- [1..m]]
    ys = [show i ++ " " ++ show 1 | i <- [2..n]]

main = do
    line <- getLine
    let [n, m] = map read $ words line :: [Int]
    let xs = solve n m
    print $ length xs
    putStrLn $ intercalate "\n" xs

{-# OPTIONS_GHC -O2 -Wall -fno-warn-missing-signatures -fno-warn-type-defaults #-}

main = interact $ sv. head. lines
sv str = unlines $ show (length ls): ls
  where ls = pair ((map read.words) str)
pair [n,m] = let f=zipWith (\x y->show x++" "++show y) in f (repeat 1) [1..m] ++ f [2..n] (repeat m)

readArr :: (Read t) => IO [t]
readArr = fmap ((fmap read) . words) getLine

front2 :: [t] -> (t, t)
front2 (x:y:_) = (x, y)

plprint :: (Show a, Show b) => [(a, b)] -> IO ()
plprint = sequence_ . (fmap (\(a, b) -> putStrLn $ show a ++ " " ++ show b))

psort :: (Ord t) => (t, t) -> (t, t)
psort (x, y)
    | x > y = (y, x)
    | otherwise = (x, y)

main = do
    (n, m) <- (fmap front2) (readArr :: IO [Int])
    let li = [(1, a) | a <- [1..m]] ++ [(a, 1) | a <- [2..n]]
    print $ length li
    plprint li

import Control.Monad (liftM)

solve :: [Int] -> [(Int, Int)]
solve [a, b]  =  [(1, i) | i <- [1..b]] ++ [(i, 1) | i <- [2..a]]

print' :: [(Int, Int)] -> IO ()
print' xs  =  print (length xs) >> mapM_ print'' xs
  where
    print'' (x, y)  =  putStrLn $ concat [show x, " ", show y]

main :: IO ()
main  =  liftM (map read . words) getLine >>= print' . solve

import Control.Applicative

solve :: Int -> Int -> [[Int]]
solve n m =
  [[1, j] | j <- [1..m]] ++ [[i, m] | i <- [2..n]]

main :: IO ()
main = do
  [n, m] <- map read . words <$> getLine
  let solns = solve n m
  putStrLn $ show $ length solns
  putStrLn $ unlines $ map (unwords . map show) $ solns

main=getContents>>=(\[n,m]->(print(n+m-1)>>mapM_(putStrLn.unwords.map show)(f n m))).map read.words
f n m=[[1,k]|k<-[1..m]]++[[k,1]|k<-[2..n]]

main :: IO ()
main = getContents >>= (\[n, m] -> (print (n + m - 1) >> mapM_ (putStrLn . unwords . map show) (solve n m))) . map read . words

solve :: Integer -> Integer -> [[Integer]]
solve n m = [ [ 1, k ] | k <- [1..m] ] ++ [ [ k, m ] | k <- [2..n] ]

readArr :: (Read t) => IO [t]
readArr = fmap ((fmap read) . words) getLine

front2 :: [t] -> (t, t)
front2 (x:y:_) = (x, y)

plprint :: (Show a, Show b) => [(a, b)] -> IO ()
plprint = sequence_ . (fmap (\(a, b) -> putStrLn $ show a ++ " " ++ show b))

psort :: (Ord t) => (t, t) -> (t, t)
psort (x, y)
    | x > y = (y, x)
    | otherwise = (x, y)

main = do
    (n, m) <- (fmap front2) (readArr :: IO [Int])
    let li = [(1, a) | a <- [1..n]] ++ [(b, b) | b <- [2..m]]
    print $ length li
    plprint li

readArr :: (Read t) => IO [t]
readArr = fmap ((fmap read) . words) getLine

front2 :: [t] -> (t, t)
front2 (x:y:_) = (x, y)

plprint :: (Show a, Show b) => [(a, b)] -> IO ()
plprint = sequence_ . (fmap (\(a, b) -> putStrLn $ show a ++ " " ++ show b))

psort :: (Ord t) => (t, t) -> (t, t)
psort (x, y)
    | x > y = (y, x)
    | otherwise = (x, y)

main = do
    (n, m) <- (fmap (psort . front2)) (readArr :: IO [Int])
    let li = [(x, y) | x <- [1..n], y <- [1..m], y >= x]
    print $ length li
    plprint li

readArr :: (Read t) => IO [t]
readArr = fmap ((fmap read) . words) getLine

front2 :: [t] -> (t, t)
front2 (x:y:_) = (x, y)

plprint :: (Show a, Show b) => [(a, b)] -> IO ()
plprint = sequence_ . (fmap (\(a, b) -> putStrLn $ show a ++ " " ++ show b))

psort :: (Ord t) => (t, t) -> (t, t)
psort (x, y)
    | x > y = (y, x)
    | otherwise = (x, y)

main = do
    (n, m) <- (fmap front2) (readArr :: IO [Int])
    let li = (if n <= m then (filter $ (\(a, b) -> a <= b))
                       else (filter $ (\(a, b) -> b <= a)) )
                        [(x, y) | x <- [1..n], y <- [1..m]]
    print $ length li
    plprint li

readArr :: (Read t) => IO [t]
readArr = fmap ((fmap read) . words) getLine

front2 :: [t] -> (t, t)
front2 (x:y:_) = (x, y)

plprint :: (Show a, Show b) => [(a, b)] -> IO ()
plprint = sequence_ . (fmap (\(a, b) -> putStrLn $ show a ++ " " ++ show b))

main = do
    (n, m) <- (fmap front2) (readArr :: IO [Int])
    let li = [(x, y) | x <- [1..n], y <- [1..m], y >= x]
    print $ length li
    plprint li

import Control.Monad (liftM)

solve :: [Int] -> [(Int, Int)]
solve [1, 1]  =  [(1, 1)]
solve [a, b]
  | a > b  =  [(div (i+1) 2, div i 2) | i <- [2 .. 2*b + 1]]
  | a < b  =  [(div i 2, div (i+1) 2) | i <- [2 .. 2*a + 1]]
  | a == b  =  [(div i 2, div (i+1) 2) | i <- [2 .. 2*a]]

print' :: [(Int, Int)] -> IO ()
print'  =  mapM_ print''
  where
    print'' (x, y)  =  putStrLn $ concat [show x, " ", show y]

main :: IO ()
main  =  liftM (map read . words) getLine >>= print' . solve

import Control.Monad (liftM)

solve :: [Int] -> [(Int, Int)]
solve [1, 1]  =  [(1, 1)]
solve [a, b]
  | a > b  =  [(div (i+1) 2, div i 2) | i <- [2 .. 2*b + 1]]
  | a < b  =  [(div i 2, div (i+1) 2) | i <- [2 .. 2*a + 1]]
  | a == b  =  [(div i 2, div (i+1) 2) | i <- [2 .. 2*a]]

print' :: [(Int, Int)] -> IO ()
print' xs  =  print (length xs) >> mapM_ print'' xs
  where
    print'' (x, y)  =  putStrLn $ concat [show x, " ", show y]

main :: IO ()
main  =  liftM (map read . words) getLine >>= print' . solve

main :: IO ()
main = getContents >>= (\[n, m] -> (print (n + m - 1) >> mapM_ (putStrLn . unwords . map show) (solve n m))) . map read . words

solve :: Integer -> Integer -> [[Integer]]
solve n m = zipWith ((.(:[])).(:)) (concatMap (replicate 2) [1..n]) (tail $ concatMap (replicate 2) [1..m])

main = do
   [n, m] <- fmap (map read . words) getLine
   let pairs = solve n m
   print $ length pairs
   mapM (\(x, y) -> putStrLn $ show x ++ " " ++ show y) pairs

solve :: Int -> Int -> [(Int, Int)]
solve boys girls = (map (\x -> (1, x)) [1..girls]) ++ (map (\x -> (x, 2)) [2..boys])

main = do
   [n, m] <- fmap (map read . words) getLine
   let pairs = solve n m
   print $ length pairs
   mapM (\(x, y) -> putStrLn $ show x ++ " " ++ show y) pairs

solve :: Int -> Int -> [(Int, Int)]
solve boys girls = map (\x -> (1, x)) [1..girls] ++ map (\x -> (x, 2)) [2..boys]

import Data.List

solve n m = xs ++ ys where
    xs = ["1 " ++ show j | j <- [1..m]]
    ys = [show i ++ " " ++ show j | (i, j) <- zip [2..n] [1..m]]

main = do
    line <- getLine
    let [n, m] = map read $ words line :: [Int]
    let xs = solve n m
    print $ length xs
    putStrLn $ intercalate "\n" xs


solve :: String -> Bool
solve s = take (length s `div` 2) s == drop (length s `div` 2) s

testcases :: Int -> IO()
testcases 0 = putStr ""
testcases t = do
  current <- getLine
  putStrLn (if solve current then "YES" else "NO")
  testcases ( t - 1 )

main = do
  t <- getLine
  testcases $ read t

import Control.Monad (forM_)

solve str =
    let len = length str
     in if even len && (take (len `div` 2) str == drop (len `div` 2) str) then "YES" else "NO"

main :: IO ()
main = do
    n <- readLn :: IO Int
    forM_ [1 .. n] $ \i -> do
        x <- getLine
        putStrLn $ solve x

import Control.Monad

main :: IO ()
main = do
    t <- readLn :: IO Int
    res <- replicateM t $ do
        s <- getLine
        let len = length s
        if mod len 2 == 1 then return "NO"
        else if take (len `div` 2) s == drop (len `div` 2) s then return "YES" else return "NO"

    putStrLn $ unlines res
    return ()

solve :: String -> Bool
solve s = take (length s `div` 2) s == drop (length s `div` 2) s

testcases :: Int -> IO()
testcases 0 = putStr ""
testcases t = do
  current <- getLine
  print . solve $ current
  testcases ( t - 1 )

main = do
  t <- getLine
  testcases $ read t


import Control.Monad
main = do
    n <- readLn
    ps <- replicateM n $ ((!!1).(map read).words <$> getLine)
    k <- (readLn::IO Int)
    print . length . filter (>=k) $ ps

import Control.Monad (replicateM)

readWordsLn :: Read a => IO [a]
readWordsLn = map read <$> (words <$> getLine)

readHeadLn :: Read a => IO a
readHeadLn = head <$> readWordsLn

readWordsMultiLn :: Read a => Int -> IO [[a]]
readWordsMultiLn n = replicateM n readWordsLn

main :: IO ()
main = do
  n <- readHeadLn :: IO Int
  chapters <- readWordsMultiLn n :: IO [[Int]]
  page <- readHeadLn :: IO Int
  print (n - solve chapters page)

solve :: [[Int]] -> Int -> Int
solve ((_:x:_):xs) p
  | p > x = solve xs p + 1
  | otherwise = 0

module Main where
import Control.Monad
import Data.List

main = do
    n <- (readLn :: IO Int)
    ps <- replicateM n (map (read :: String -> Int) . words <$> getLine)
    let qs = concat $ zipWith (\[a,b] c -> replicate (b-a+1) c) ps [1..]
    k <- (readLn :: IO Int)
    print  $ n - (head $ drop (k-1) qs) + 1

import Control.Monad
main = do
  n <- readLn
  lrs <- replicateM n (map read . words <$> getLine)
  k <- readLn :: IO Int
  print $ length $ dropWhile ((< k) . (!! 1)) lrs

import Control.Monad
import Data.Semigroup

solve :: [[Int]] -> Int -> Int
solve chaps curr = sum $ map (fromEnum . (>= curr) . (!! 1)) chaps

main = do
  numChapters <- read <$> getLine
  bounds <- replicateM numChapters $ do
    fmap read <$> words <$> getLine
  pos <- read <$> getLine
  print $ solve bounds pos
  return ()

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

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

secondLessEq :: Int -> (Int, Int) -> Bool
secondLessEq n (_, r) = n <= r

solve :: [Int] -> Int
solve (chaps:rest) = length . filter (secondLessEq (last rest)) . listIntoPairList . take (2*chaps) $ rest

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

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

ru, ri :: C.ByteString -> Int

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

tuple2 [] = []
tuple2 (x:y:l) = (x, y) : (tuple2 l)

solve :: [Int] -> Int
solve (n:a) = length $ filter (\(i, j) -> k <= j) d
  where
    (b, (k:c)) = splitAt (2 * n) a
    d = tuple2 b

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

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

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

	y<-read <$> getLine ::IO Int
	print $ length $ dropWhile (<y) b

--ghc 7.10

countUnfinished :: Int -> [Int] -> Int
countUnfinished p = length . filter (>=p)

main = do
    nStr <- getLine
    let n = read nStr
    cStrs <- sequence . replicate n $ getLine
    let rs = map (read . last . words) cStrs
    pStr <- getLine
    let p = read pStr
    print $ countUnfinished p rs

import Control.Monad
main = do
    n <- readLn
    ps <- replicateM n $ ((!!1).(map read).words <$> getLine)
    k <- (readLn::IO Int)
    print . length . filter (>k) $ ps


import Data.List( nub)

main = do
    s_ <- getLine
    k_ <- readLn::IO Int
    let
	len = length s_
	uniq = nub s_
	need = k_ - (length uniq)

    if len < k_
	then putStr "impossible"
	else print (need `max` 0)

import Data.List
import Data.Ord

solve x n
	|ll>=n="0"
	|l>=n = show (n-ll)
	|otherwise = "impossible"
	where
		l=length x
		ll=length (nub x)

main=do
	word<-getLine
	n<-getLine
	putStrLn (solve word (read n::Int))

import Data.List

main = do
    str <- getLine
    n <- getLine
    putStrLn $ foo str (read n)

foo :: String -> Int -> String
foo str n =
    let d = length . nub . sort $ str
        tl = length str
    in
        if tl < n
            then "impossible"
            else show $ max 0 $ n - d

import Control.Monad
import Data.List
import Data.Maybe
import Data.Char

import qualified Data.ByteString.Char8 as B
readInt = readLn :: IO Int
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

solve :: String -> Int -> String
solve s n
    | length s < n = "impossible"
    | otherwise    = show (max 0 (n - u))
        where u = (length . map head . group . sort) s

main :: IO ()
main = do
    s <- getLine
    n <- readInt
    putStrLn $ solve s n

import Data.List

solve :: String -> Int -> String
solve xs k
    | length xs < k = "impossible"
    | (length.nub) xs < k = show (k-(length.nub) xs)
    | otherwise = "0"

main = do
    xs <- getLine
    k <- readLn :: IO Int
    (putStrLn.solve xs) k

-- 844A

import Data.Maybe (fromJust)
import Data.List (group, sort)

unique = length . group . sort

program (s:si:_)
  | i > length s = "impossible"
  | otherwise    = show $ max 0 (i - unique s)
  where i = read si

main = interact $ program . lines

import Data.List
import System.IO

nrDistinct_ :: (Ord a, Num b) => [a] -> b
nrDistinct :: (Ord a, Num b) => [a] -> b

nrDistinct_ [] = 0
nrDistinct_ [x] = 1
nrDistinct_ (x:x_:xs) = if x == x_ then r else r + 1
    where r = nrDistinct_ (x_:xs)

nrDistinct = nrDistinct_ . sort

main = do
    str <- getLine
    k   <- readLn :: IO Int
    let delta = max 0 $ k - (nrDistinct str)
    if k <= length str then print delta else putStr "impossible"

import Data.List
import Data.Ord

solve x n
	|l==n = show (n-(length (nub x)))
	|otherwise = "impossible"
	where
		l=length x

main=do
	word<-getLine
	n<-getLine
	putStrLn (solve word (read n::Int))

import Data.List
import Data.Ord

solve x n
	|l>=n = show (n-(length (nub x)))
	|otherwise = "impossible"
	where
		l=length x

main=do
	word<-getLine
	n<-getLine
	putStrLn (solve word (read n::Int))

-- 844A

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

toInt = fst . fromJust . B.readInt
unique = length . B.group . B.sort

program (s:si:_)
  | i > B.length s = "impossible"
  | otherwise      = show $ max 0 (i - unique s)
  where i = toInt si

main = B.interact $ B.pack . program . B.lines


import Control.Monad
import Data.Array
import Data.Int
import Data.List
import Data.Maybe
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

fast_read_Int = fmap (map (fst . fromJust . BS8.readInt) . BS8.words) BS.getLine :: IO [Int]
fast_read_Int64 = fmap (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) BS.getLine :: IO [Int64]

bs :: Array Int64 Int64 -> Int64 -> Int64 -> Int64
bs v n x = go 0 n where
    go st dr
        | st>=dr = dr - 1
        | v ! mid <= x = go (mid+1) dr
        | v ! mid > x = go st mid
        where mid = div (st + dr)  2

main = do
    [n,m,k] <- fast_read_Int64
    [x,s] <- fast_read_Int64
    a <- fmap (listArray (0,m-1)) fast_read_Int64
    b <- fmap (listArray (0,m-1)) fast_read_Int64
    c <- fmap (listArray (0,k-1)) fast_read_Int64
    d <- fmap (listArray (0,k-1)) fast_read_Int64
    let fara_1 = bs d k s
    let initial = if fara_1 >= 0 then (max (n - c ! fara_1) 0) * x else n * x

    let f i = g i where
        g i
            | s < b ! i = maxBound :: Int64
            | otherwise = (max 0 (n - maxp)) * (a ! i)
            where
                maxp = if binary_search >=0 then c ! binary_search else 0
                binary_search = bs d k (s- b ! i)

    let _for_ = minimum $ map f [0..m-1]

    print $ min initial _for_

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

-- ID: 734C (Anton and Making Potions)

import Control.Monad
import Data.Array
import Data.Int
import Data.Maybe
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

getInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]

main = do
    [n, m, k] <- getInt64s
    [x, s] <- getInt64s
    as <- (listArray (0, m-1)) `fmap` getInt64s
    bs <- (listArray (0, m-1)) `fmap` getInt64s
    cs <- (listArray (0, k-1)) `fmap` getInt64s
    ds <- (listArray (0, k-1)) `fmap` getInt64s
    let ub = upperBound ds k s
    let freePotion = cs ! (ub - 1)
    let noFirst = if ub > 0 then (max (n - freePotion) 0) * x else n * x
    let bestUsingFirst = minimum $ map (make as bs cs ds n k s) [0..m-1]
    print $ min noFirst bestUsingFirst

make as bs cs ds n k s i
    | bs ! i > s = maxBound :: Int64
    | otherwise = (max 0 remain) * (as ! i)
    where
        remain = n - (if ub == 0 then 0 else (cs ! (ub - 1)))
        ub = upperBound ds k (s - bs ! i)

upperBound :: Array Int64 Int64 -> Int64 -> Int64 -> Int64
upperBound ary n x = go 0 n where
    go lb ub
        | lb >= ub = ub
        | ary ! mid <= x = go (mid+1) ub
        | ary ! mid > x = go lb mid
        where mid = (lb + ub) `div` 2

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

module Main where

--import Debug.Trace

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

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

---- Answer Code Section ----

type IntArray = UA.UArray Int Int

inf = 10^20 :: Integer

binarySearch f arr start end
    | start >= end = end
    | otherwise = if f (arr ! middle) then firstHalf else secondHalf where
        middle = (start + end) `div` 2
        firstHalf = binarySearch f arr start middle
        secondHalf = binarySearch f arr (middle+1) end

getMaxImmPotion cs ds mana = cs ! spellIndex' where
    (lb, hb) = bounds ds
    spellIndex = binarySearch (> mana) ds lb hb
    spellIndex' = until (\si -> (ds ! si) <= mana) (\si -> si-1) spellIndex

process :: Int -> Int -> [Int] -> [Int] -> IntArray -> IntArray -> Integer
process n s as bs cs ds = minimum [ makePotion a b | (a, b) <- zip as bs ] where
    makePotion a b = if secondSpellMana < 0 then inf else totalTime :: Integer where
        potionTime = a
        secondSpellMana = s - b
        manualPotionCnt = max 0 $ n - getMaxImmPotion cs ds secondSpellMana
        totalTime = (fromIntegral potionTime) * (fromIntegral manualPotionCnt)

main = do
    n:m:k:[] <- getInts
    x:s:[] <- getInts
    as <- ((:) x) <$> getInts
    bs <- ((:) 0) <$> getInts
    cs <- (\l -> UA.listArray (0, k) (0:l)) <$> getInts
    ds <- (\l -> UA.listArray (0, k) (0:l)) <$> getInts
    print $ process n s as bs cs ds

module Main where

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

type Tokenizer = State [L.ByteString]

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

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

f :: Integer -> Integer -> Integer -> Array Int Integer -> Array Int Integer -> Integer
f n x s c d | i < 0     = n * x
            | otherwise = (max 0 (n - c!i)) * x
            where i = bs (-1) ((snd $ bounds c) + 1)
                  bs l r | r - l == 1 = l
                         | d!m <= s  = bs m r
                         | otherwise  = bs l m
                         where m = (l + r) `div` 2

solve :: Integer -> Integer -> Integer -> Array Int Integer -> Array Int Integer -> Array Int Integer -> Array Int Integer -> Integer
solve n x s a b c d = foldl min (f n x s c d) [a!i + f (n - 1) (a!i) (s - b!i) c d | i <- [0..snd $ bounds a], s >= b!i]

doit :: Tokenizer Integer
doit = do
    n <- nextInteger
    m <- nextInt
    k <- nextInt
    x <- nextInteger
    s <- nextInteger
    a <- liftM (listArray (0, m - 1)) $ replicateM m nextInteger
    b <- liftM (listArray (0, m - 1)) $ replicateM m nextInteger
    c <- liftM (listArray (0, k - 1)) $ replicateM k nextInteger
    d <- liftM (listArray (0, k - 1)) $ replicateM k nextInteger
    return $ solve n x s a b c d

main = do
    contents <- L.getContents
    print $ evalState doit (L.words contents)

module Main where

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

type Tokenizer = State [L.ByteString]

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

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

f :: Integer -> Integer -> Integer -> Array Int Integer -> Array Int Integer -> Integer
f n x s c d | i < 0     = n * x
            | otherwise = (max 0 (n - c!i)) * x
            where i = bs (-1) (rightBoundC + 1)
                  (_, rightBoundC) = bounds c
                  bs l r | r - l == 1 = l
                         | d!m <= s  = bs m r
                         | otherwise  = bs l m
                         where m = (l + r) `div` 2

solve :: Integer -> Integer -> Integer -> Array Int Integer -> Array Int Integer -> Array Int Integer -> Array Int Integer -> Integer
solve n x s a b c d = foldl min (f n x s c d) [a!i + f (n - 1) (a!i) (s - b!i) c d | i <- [0..rightBoundA], s >= b!i]
    where (_, rightBoundA) = bounds a

doit :: Tokenizer Integer
doit = do
    n <- nextInteger
    m <- nextInt
    k <- nextInt
    x <- nextInteger
    s <- nextInteger
    aList <- replicateM m nextInteger
    bList <- replicateM m nextInteger
    cList <- replicateM k nextInteger
    dList <- replicateM k nextInteger
    let a = listArray (0, m - 1) aList
    let b = listArray (0, m - 1) bList
    let c = listArray (0, k - 1) cList
    let d = listArray (0, k - 1) dList
    return $ solve n x s a b c d

main = do
    contents <- L.getContents
    print $ evalState doit (L.words contents)

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

module Main where

--import Debug.Trace

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

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

---- Answer Code Section ----

type IntArray = UA.UArray Int Int

inf = 10^20 :: Integer

binarySearch f arr start end
    | start >= end = end
    | otherwise = if f (arr ! middle) then firstHalf else secondHalf where
        middle = (start + end) `div` 2
        firstHalf = binarySearch f arr start middle
        secondHalf = binarySearch f arr (middle+1) end

getMaxImmPotion cs ds mana = cs ! spellIndex' where
    (lb, hb) = bounds ds
    spellIndex = binarySearch (>= mana) ds lb hb
    spellIndex' = if ds ! spellIndex <= mana then spellIndex else spellIndex - 1

process :: Int -> Int -> [Int] -> [Int] -> IntArray -> IntArray -> Integer
process n s as bs cs ds = minimum [ makePotion a b | (a, b) <- zip as bs ] where
    makePotion a b = if secondSpellMana < 0 then inf else totalTime :: Integer where
        potionTime = a
        secondSpellMana = s - b
        manualPotionCnt = max 0 $ n - getMaxImmPotion cs ds secondSpellMana
        totalTime = (fromIntegral potionTime) * (fromIntegral manualPotionCnt)

main = do
    n:m:k:[] <- getInts
    x:s:[] <- getInts
    as <- ((:) x) <$> getInts
    bs <- ((:) 0) <$> getInts
    cs <- (\l -> UA.listArray (0, k) (0:l)) <$> getInts
    ds <- (\l -> UA.listArray (0, k) (0:l)) <$> getInts
    print $ process n s as bs cs ds

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

-- ID: 734C (Anton and Making Potions)

import Control.Monad
import Data.Array
import Data.Int
import Data.Maybe
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

getInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]

main = do
    [n, m, k] <- getInt64s
    [x, s] <- getInt64s
    as <- (listArray (0, m-1)) `fmap` getInt64s
    bs <- (listArray (0, m-1)) `fmap` getInt64s
    cs <- (listArray (0, k-1)) `fmap` getInt64s
    ds <- (listArray (0, k-1)) `fmap` getInt64s
    let ub = upperBound ds k s
    let freePotion = cs ! (ub - 1)
    let noFirst = if ub > 0 then (max (n - freePotion) 0) * x else n * x
    let bestUsingFirst = minimum $ map (make as bs cs ds n k s) [0..m-1]
    print $ min noFirst bestUsingFirst

make as bs cs ds n k s i
    | ub == 0 || bs ! i > s = maxBound :: Int64
    | otherwise = (max 0 remain) * (as ! i)
    where
        remain = n - (cs ! (ub - 1))
        ub = upperBound ds k (s - bs ! i)

upperBound :: Array Int64 Int64 -> Int64 -> Int64 -> Int64
upperBound ary n x = go 0 n where
    go lb ub
        | lb >= ub = ub
        | ary ! mid <= x = go (mid+1) ub
        | ary ! mid > x = go lb mid
        where mid = (lb + ub) `div` 2

import Control.Monad
import Data.Array
import Data.Int
import Data.List
import Data.Maybe
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

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

bs :: Array Int Int -> Int -> Int -> Int
bs v n x = go 0 n where
    go st dr
        | st>=dr = dr - 1
        | v ! mid <= x = go (mid+1) dr
        | v ! mid > x = go st mid
        where mid = div (st + dr)  2

main = do
    [n,m,k] <- fast_read_Int
    [x,s] <- fast_read_Int
    a <- fmap (listArray (0,m-1)) fast_read_Int
    b <- fmap (listArray (0,m-1)) fast_read_Int
    c <- fmap (listArray (0,k-1)) fast_read_Int
    d <- fmap (listArray (0,k-1)) fast_read_Int
    let fara_1 = bs d k s
    let nr_fara_1 = c ! fara_1
    let initial = if fara_1 >= 0 then (max (n - nr_fara_1) 0) * x else n * x

    let f i = g i where
        g i
            | s < b ! i = maxBound :: Int
            | otherwise = (max 0 (n - maxp)) * (a ! i)
            where
                maxp = if binary_search >=0 then c ! binary_search else 0
                binary_search = bs d k (s- b ! i)

    let _for_ = minimum $ map f [0..m-1]

    print $ min initial _for_

import Control.Monad
import Data.Array
import Data.Int
import Data.List
import Data.Maybe
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

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

bs :: Array Int Int -> Int -> Int -> Int
bs v n x = go 0 n where
    go st dr
        | st>=dr = dr - 1
        | v ! mid <= x = go (mid+1) dr
        | v ! mid > x = go st mid
        where mid = div (st + dr)  2

main = do
    [n,m,k] <- fast_read_Int
    [x,s] <- fast_read_Int
    a <- fmap (listArray (0,m-1)) fast_read_Int
    b <- fmap (listArray (0,m-1)) fast_read_Int
    c <- fmap (listArray (0,k-1)) fast_read_Int
    d <- fmap (listArray (0,k-1)) fast_read_Int
    let fara_1 = bs d k s
    let initial = if fara_1 >= 0 then (max (n - c ! fara_1) 0) * x else n * x

    let f i = g i where
        g i
            | s < b ! i = maxBound :: Int
            | otherwise = (max 0 (n - maxp)) * (a ! i)
            where
                maxp = if binary_search >=0 then c ! binary_search else 0
                binary_search = bs d k (s- b ! i)

    let _for_ = minimum $ map f [0..m-1]

    print $ min initial _for_

module Main where

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

type Tokenizer = State [L.ByteString]

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

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

f :: Integer -> Integer -> Integer -> Array Int Integer -> Array Int Integer -> Integer
f n x s c d | i < 0     = n * x
            | otherwise = (max 0 (n - c!i)) * x
            where i = bs (-1) (snd $ bounds c) + 1
                  bs l r | r - l == 1 = l
                         | d!m <= s  = bs m r
                         | otherwise  = bs l m
                         where m = (l + r) `div` 2

solve :: Integer -> Integer -> Integer -> Array Int Integer -> Array Int Integer -> Array Int Integer -> Array Int Integer -> Integer
solve n x s a b c d = foldl min (f n x s c d) [a!i + f (n - 1) (a!i) (s - b!i) c d | i <- [0..snd $ bounds a], s >= b!i]

doit :: Tokenizer Integer
doit = do
    n <- nextInteger
    m <- nextInt
    k <- nextInt
    x <- nextInteger
    s <- nextInteger
    a <- liftM (listArray (0, m - 1)) $ replicateM m nextInteger
    b <- liftM (listArray (0, m - 1)) $ replicateM m nextInteger
    c <- liftM (listArray (0, k - 1)) $ replicateM k nextInteger
    d <- liftM (listArray (0, k - 1)) $ replicateM k nextInteger
    return $ solve n x s a b c d

main = do
    contents <- L.getContents
    print $ evalState doit (L.words contents)


import Data.List
import GHC.Exts
solve [[_, ll,x,y], l] = case (can x, can y, can $ x+y, can $ abs $ x-y) of
   (_:_,_:_,_,_) -> [[0]]
   ([],[],[],[]) -> [[2],[x,y]]
   (_:_,_,_,_) -> [[1],[y]]
   (_,_:_,_,_) -> [[1],[x]]
   (_,_,s:_,_) -> [[1],[s+y]]
   (_,_,_,ss) -> case filter (<=ll) [s+max x y | s<-ss] ++ filter (>=0) [s-min x y | s<-ss] of
                h:_ -> [[1],[h]]
                []  -> [[2],[x,y]]
  where can x = map head $ filter ((>1).length) $ group $ sort $ l  ++ map (subtract x) l

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

import qualified Data.Set as Set
main=interact$solve.map read.words
solve (_:l:x:y:xs)
	| find1<=l && find2<=l = "0"
	| find1<=l = "1\n" ++ show y
	| find2<=l = "1\n" ++ show x
	| find3<=l = "1\n" ++ show (find3+x)
	| find4<=l && find4+y<l = "1\n" ++ show (find4+y)
	| find5<=l && find5>x = "1\n" ++ show (find5-x)
	| otherwise = "2\n"++show x++" "++show y
	where hs=Set.fromList xs
	      find x xs
		| null xs = l+1
		| Set.member (head xs + x) hs = head xs
		| otherwise = find x $ tail xs
	      find1=find x xs
              find2=find y xs
	      find3=find (y+x) xs
	      find4=find (y-x) xs
	      find5=find (y-x) $ reverse xs

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

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

main :: IO ()
main = do
  nlxy <- map read.words <$> getLine
  xs <- map readInt.B.words <$> B.getLine
  case solve nlxy xs of
    ps -> do
      print $ length ps
      putStr.unwords.map show $ ps

solve :: [Int] -> [Int] -> [Int]
solve [n,l,x,y] xs
  | okX && okY = []
  | okX = [y]
  | okY = [x]
  | otherwise = case filter (\k->0<k&&k<l) $ IS.toList cap of
                  [] -> [x,y]
                  (res:_) -> [res]
   where
     !set = IS.fromList xs
     !okX = or [IS.member (v+x) set | v<-xs]
     !okY = or [IS.member (v+y) set | v<-xs]
     !cap = IS.unions
          [IS.intersection (IS.map (subtract x) set) (IS.map (subtract y) set)
          ,IS.intersection (IS.map (subtract x) set) (IS.map (+y) set)
          ,IS.intersection (IS.map (+x) set) (IS.map (subtract y) set)
          ,IS.intersection (IS.map (+x) set) (IS.map (+y) set)
          ]

import qualified Data.Set as Set
main=interact$solve.map read.words
solve (_:l:x:y:xs)
	| find1<=l && find2<=l = "0"
	| find1<=l = "1\n" ++ show (find1+y)
	| find2<=l = "1\n" ++ show (find2+x)
	| find3<=l = "1\n" ++ show (find3+x)
	| find4<=l && find4+y<l = "1\n" ++ show (find4+y)
	| otherwise = "2\n"++show x++" "++show y
	where hs=Set.fromList xs
	      find x xs
		| null xs = l+1
		| Set.member (head xs + x) hs = head xs
		| otherwise = find x $ tail xs
	      find1=find x xs
              find2=find y xs
	      find3=find (y+x) xs
	      find4=find (y-x) xs

import qualified Data.Set as Set
main=interact$solve.map read.words
solve (_:l:x:y:xs)
	| find1<=l && find2<=l = "0"
	| find1<=l = "1\n" ++ show (find1+y)
	| find2<=l = "1\n" ++ show (find2+x)
	| find3<=l = "1\n" ++ show (find3+x)
	| find4<=l && find4+y<l = "1\n" ++ show (find4+y)
	| find5<=l && find5>x = "1\n" ++ show (find5-x)
	| otherwise = "2\n"++show x++" "++show y
	where hs=Set.fromList xs
	      find x xs
		| null xs = l+1
		| Set.member (head xs + x) hs = head xs
		| otherwise = find x $ tail xs
	      find1=find x xs
              find2=find y xs
	      find3=find (y+x) xs
	      find4=find (y-x) xs
	      find5=find (y-x) $ reverse xs

import qualified Data.Set as Set
main=interact$solve.map read.words
solve (_:l:x:y:xs)
	| find1<=l && find2<=l = "0"
	| find1<=l = "1\n" ++ show (find1+x)
	| find2<=l = "1\n" ++ show (find2+y)
	| find3<=l = "1\n" ++ show (find3+x)
	| find4<=l && find4+y<l = "1\n" ++ show (find4+y)
	| otherwise = "2\n"++show x++" "++show y
	where hs=Set.fromList xs
	      find x xs
		| null xs = l+1
		| Set.member (head xs + x) hs = head xs
		| otherwise = find x $ tail xs
	      find1=find x xs
              find2=find y xs
	      find3=find (y+x) xs
	      find4=find (y-x) xs

import Data.List
import GHC.Exts
solve [[_, ll,x,y], l] = case (can x, can y, can $ x+y, can $ abs $ x-y) of
   ([_],[_],_,_) -> [[0]]
   ([],[],[],[]) -> [[2],[x,y]]
   ([_],_,_,_) -> [[1],[y]]
   (_,[_],_,_) -> [[1],[x]]
   (_,_,[s],_) -> [[1],[s+y]]
   (_,_,_,[s]) | s+max x y <= ll -> [[1],[s+max x y]]
               | s-min x y >= 0 -> [[1],[s-min x y]]
               | otherwise       -> [[2],[x,y]]
  where can x = take 1 $ drop 1 $ head $ sortWith (negate.length) $ group $ sort $ l  ++ map (subtract x) l

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

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

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

main :: IO ()
main = do
  nlxy <- map read.words <$> getLine
  xs <- map readInt.B.words <$> B.getLine
  case solve nlxy xs of
    ps -> do
      print $ length ps
      putStr.unwords.map show $ ps

solve :: [Int] -> [Int] -> [Int]
solve [n,l,x,y] xs
  | IS.member x set && IS.member y set = []
  | otherwise = go xs
   where
     !set = IS.fromList xs
     go (v:vs)
       | IS.member (v+x) set && IS.member y set = []
       | IS.member (v+y) set && IS.member x set = []
       | otherwise = go vs
     go []
       | IS.member x set = [y]
       | IS.member y set = [x]
       | otherwise = [x,y]

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

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

main :: IO ()
main = do
  nlxy <- map read.words <$> getLine
  xs <- map readInt.B.words <$> B.getLine
  case solve nlxy xs of
    ps -> do
      print $ length ps
      putStr.unwords.map show $ ps

solve :: [Int] -> [Int] -> [Int]
solve [n,l,x,y] xs
  | IS.member x set && IS.member y set = []
  | otherwise = go xs
   where
     !d = y - x
     !set = IS.fromList xs
     go (v:vs)
       | IS.member (v+d) set = []
       | IS.member (v+x) set && IS.member y set = []
       | IS.member (v+y) set && IS.member x set = []
       | otherwise = go vs
     go []
       | IS.member x set = [y]
       | IS.member y set = [x]
       | otherwise = [x,y]

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

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

main :: IO ()
main = do
  nlxy <- map read.words <$> getLine
  xs <- map readInt.B.words <$> B.getLine
  case solve nlxy xs of
    ps -> do
      print $ length ps
      putStr.unwords.map show $ ps

solve :: [Int] -> [Int] -> [Int]
solve [n,l,x,y] xs
  | okX && okY = []
  | okX = [y]
  | okY = [x]
  | otherwise = case filter (>=0) $ IS.toList cap of
                  [] -> [x,y]
                  (res:_) -> [res]
   where
     !set = IS.fromList xs
     !okX = or [IS.member (v+x) set | v<-0:xs]
     !okY = or [IS.member (v+y) set | v<-0:xs]
     !cap = IS.intersection (IS.map (subtract x) set) (IS.map (subtract y) set)

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

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

main :: IO ()
main = do
  nlxy <- map read.words <$> getLine
  xs <- map readInt.B.words <$> B.getLine
  case solve nlxy xs of
    ps -> do
      print $ length ps
      putStr.unwords.map show $ ps

solve :: [Int] -> [Int] -> [Int]
solve [n,l,x,y] xs
  | okX && okY = []
  | okX = [y]
  | okY = [x]
  | otherwise = case IS.toList cap of
                  [] -> [x,y]
                  (res:_) -> [res]
   where
     !set = IS.fromList xs
     !okX = or [IS.member (v+x) set | v<-0:xs]
     !okY = or [IS.member (v+y) set | v<-0:xs]
     !cap = IS.intersection (IS.map (subtract x) set) (IS.map (subtract y) set)


{-# LANGUAGE LambdaCase #-}
module Main where

import Control.Monad (liftM2, replicateM_, replicateM, foldM, when)
import Data.Char (digitToInt)
import Data.Maybe (fromJust, fromMaybe)
import qualified Data.ByteString.Char8 as C
import Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)
import Data.List (group, sort)
import Data.Set (Set, deleteFindMin, union)
import qualified Data.Set as Set
import qualified Data.Map.Strict as Map
import Data.Function (on)
-- import System.Random
import Data.Array.MArray (newArray, readArray, writeArray, newListArray)
import Data.Array.IO (IOUArray, getElems)
import Debug.Trace
import Data.Bool (bool)
import Data.Foldable (foldlM)

-- road map in reverse, and the number of cities, init pen state
type Domain = (Int,IOUArray Int Int, IOUArray Int Int, IOUArray Int Int, IOUArray Int Int)
type CoDomain = Int
type Solver  = Domain -> IO CoDomain

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

printAns :: CoDomain -> IO ()
printAns = print

parse :: IO Domain
parse = do
  [number] <- readChar8
  lst <- readChar8
  xs <- newListArray (1, number) lst
  dp <- newArray (1, number) maxBound
  pd <- newArray (1, number) minBound
  ans <- newArray (1, number+1) 0
  return (number, xs, dp, pd, ans)

-- showArray ans = print =<< getElems ans

solve :: Solver
solve (size, lst, dp, pd, ans) = do
  result
  where
    result = fmap sum $ mapM go $ reverse [1.. size]
    go :: Int -> IO Int
    go index = do
      sa maxBound minBound index
      s <- readArray ans (index+1)
      writeArray ans index (s+1)
      -- showArray ans
      return (s+1)
    sa :: Int -> Int -> Int -> IO ()
    sa a b i
      | a == minBound && b == maxBound = writeArray ans i 0
      | i == size = return ()
      | otherwise = do
            x <- readArray lst i
            y <- readArray lst (i+1)
            let a1 = if (b < y) then x else minBound
            let a2 = if (x < y) then (max a1 a) else a1
            let b1 = if (a > y) then x else maxBound
            let b2 = if (x > y) then (min b1 b) else b1
            a3 <- readArray dp i
            b3 <- readArray pd i
            when (a3 /= a2 || b3 /= b2)
              (do
                writeArray dp i a2
                writeArray pd i b2
                sa a2 b2 (i+1)
                s <- readArray ans (i+1)
                writeArray ans i (s+1))

main :: IO ()
main = do
  printAns =<< solve =<< parse

{-# LANGUAGE LambdaCase #-}
module Main where

import Control.Monad (liftM2, replicateM_, replicateM, foldM, when)
import Data.Char (digitToInt)
import Data.Maybe (fromJust, fromMaybe)
import qualified Data.ByteString.Char8 as C
import Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)
import Data.List (group, sort)
import Data.Set (Set, deleteFindMin, union)
import qualified Data.Set as Set
import qualified Data.Map.Strict as Map
import Data.Function (on)
-- import System.Random
import Data.Array.MArray (newArray, readArray, writeArray, newListArray)
import Data.Array.IO (IOUArray, getElems)
import Debug.Trace
import Data.Bool (bool)
import Data.Foldable (foldlM, foldrM)

-- road map in reverse, and the number of cities, init pen state
type Domain = (Int,IOUArray Int Int, IOUArray Int Int, IOUArray Int Int, IOUArray Int Int)
type CoDomain = Int
type Solver  = Domain -> IO CoDomain

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

printAns :: CoDomain -> IO ()
printAns = print

parse :: IO Domain
parse = do
  [number] <- readChar8
  lst <- readChar8
  xs <- newListArray (1, number) lst
  dp <- newArray (1, number) maxBound
  pd <- newArray (1, number) minBound
  ans <- newArray (1, number+1) 0
  return (number, xs, dp, pd, ans)

-- showArray ans = print =<< getElems ans

solve :: Solver
solve (size, lst, dp, pd, ans) = do
  result
  where
    result = foldrM go 0 $ [1.. size]
    go :: Int -> Int -> IO Int
    go index x = do
      sa maxBound minBound index
      s <- readArray ans (index+1)
      writeArray ans index (s+1)
      return (x+s+1)
    sa :: Int -> Int -> Int -> IO ()
    sa a b i
      | a == minBound && b == maxBound = writeArray ans i 0
      | i == size = return ()
      | otherwise = do
            x <- readArray lst i
            y <- readArray lst (i+1)
            let a1 = if (b < y) then x else minBound
            let a2 = if (x < y) then (max a1 a) else a1
            let b1 = if (a > y) then x else maxBound
            let b2 = if (x > y) then (min b1 b) else b1
            a3 <- readArray dp i
            b3 <- readArray pd i
            when (a3 /= a2 || b3 /= b2)
              (do
                writeArray dp i a2
                writeArray pd i b2
                sa a2 b2 (i+1)
                s <- readArray ans (i+1)
                writeArray ans i (s+1))

main :: IO ()
main = do
  printAns =<< solve =<< parse

{-# LANGUAGE LambdaCase #-}
module Main where

import Control.Monad (liftM2, replicateM_, replicateM, foldM, when)
import Data.Char (digitToInt)
import Data.Maybe (fromJust, fromMaybe)
import qualified Data.ByteString.Char8 as C
import Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)
import Data.List (group, sort)
import Data.Set (Set, deleteFindMin, union)
import qualified Data.Set as Set
import qualified Data.Map.Strict as Map
import Data.Function (on)
-- import System.Random
import Data.Array.MArray (newArray, readArray, writeArray, newListArray)
import Data.Array.IO (IOUArray, getElems)
import Debug.Trace
import Data.Bool (bool)
import Data.Foldable (foldlM)

-- road map in reverse, and the number of cities, init pen state
type Domain = (Int,IOUArray Int Int, IOUArray Int Int, IOUArray Int Int, IOUArray Int Int)
type CoDomain = Int
type Solver  = Domain -> IO CoDomain

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

printAns :: CoDomain -> IO ()
printAns = print

parse :: IO Domain
parse = do
  [number] <- readChar8
  lst <- readChar8
  xs <- newListArray (1, number) lst
  dp <- newArray (1, number) maxBound
  pd <- newArray (1, number) minBound
  ans <- newArray (1, number+1) 0
  return (number, xs, dp, pd, ans)

-- showArray ans = print =<< getElems ans

solve :: Solver
solve (size, lst, dp, pd, ans) = do
  result
  where
    result = foldM go 0 $ reverse [1.. size]
    go :: Int -> Int -> IO Int
    go x index = do
      sa maxBound minBound index
      s <- readArray ans (index+1)
      writeArray ans index (s+1)
      return (x+s+1)
    sa :: Int -> Int -> Int -> IO ()
    sa a b i
      | a == minBound && b == maxBound = writeArray ans i 0
      | i == size = return ()
      | otherwise = do
            x <- readArray lst i
            y <- readArray lst (i+1)
            let a1 = if (b < y) then x else minBound
            let a2 = if (x < y) then (max a1 a) else a1
            let b1 = if (a > y) then x else maxBound
            let b2 = if (x > y) then (min b1 b) else b1
            a3 <- readArray dp i
            b3 <- readArray pd i
            when (a3 /= a2 || b3 /= b2)
              (do
                writeArray dp i a2
                writeArray pd i b2
                sa a2 b2 (i+1)
                s <- readArray ans (i+1)
                writeArray ans i (s+1))

main :: IO ()
main = do
  printAns =<< solve =<< parse


import           Data.List
import qualified Data.Set as Set

modulo :: Int
modulo = 1000000007

data State = State { left :: Int, right :: Int, fix :: Int }
data PermElement = PermElement { el :: Int, pos :: Int } deriving (Ord, Eq)
data TraverseHelperResult = TraverseHelperResult { multiplier :: Int, addfx :: Int }

traversePermutation :: [PermElement] -> State -> Int
traversePermutation [] state = 1
traversePermutation (head:permelements) (State {left = sleft, right = sright, fix = sfix})
    | pos head < sleft || pos head > sright = (let helperRes = (traverseHelper permelements (State (min sleft $ pos head) (max sright $ pos head) $ sfix + 1)) in (multiplier helperRes) * (traversePermutation permelements (State (min sleft $ pos head) (max sright $ pos head) (addfx helperRes))) `mod` modulo)
    | otherwise = traversePermutation permelements $ State sleft sright sfix

traverseHelper :: [PermElement] -> State -> TraverseHelperResult
traverseHelper [] state = TraverseHelperResult 1 $ fix state
traverseHelper (head:permelements) (State {left = sleft, right = sright, fix = sfix})
    | sleft <= (pos head) && (pos head) <= sright = (let subres = (traverseHelper permelements $ State sleft sright (sfix + 1)) in TraverseHelperResult ((sright - sleft + 1 - sfix) * (multiplier subres) `mod` modulo) (addfx subres))
    | otherwise = TraverseHelperResult 1 sfix

solveCase :: IO ()
solveCase = do
    line_n <- getLine
    let n = read line_n :: Int
    line_arr <- getLine
    let arr = map (\x -> (read x :: Int)) $ words line_arr
    let sarr = sort [PermElement x i | (x, i) <- zip arr [0..n - 1]] in putStrLn $ show $ traversePermutation (tail sarr) (State (pos (head sarr)) (pos (head sarr)) 1)

solve :: Int -> IO ()
solve 0 = do
    return ()
solve cases_left = do
    solveCase
    solve $ cases_left - 1

main = do
    s_testcases <- getLine
    solve $ (read s_testcases :: Int)

--
{-# 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.ST.Strict as ST
import qualified Control.Monad.State.Strict as S

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

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

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

import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import qualified Data.List   as L
import Data.List (
    elemIndices,
    find,
    findIndices,
    intersect,
    isPrefixOf,
    nub,
    sort,
    sortOn,
 )
import qualified Data.Map as M
import qualified Data.Set as S
import 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

m :: Int64
-- m = 998_244_353
m = 10 ^ 9 + 7

newtype M = M { unM :: Int64 }
  deriving (Eq, Ord)

mI :: Int -> M
mI = M . fromIntegral

instance Show M where
    show (M v) = "M" ++ show v

instance Num M where
    fromInteger n = M $ fromInteger (n `mod` fromIntegral m)

    (M a) + (M b) | a + b >= m = M $ a + b - m
    (M a) + (M b) = M $ a + b

    (M a) - (M b) | a - b < 0 = M $ m + a - b
    (M a) - (M b) = M $ a - b

    (M a) * (M b) = M $ (a * b) `mod` m

    abs    = id
    signum = undefined

powM :: M -> Int64 -> M
powM a@(M ma) x
    | x == 0 = M 1
    | x == 1 = a
    | even x = let t = powM a (x `div` 2) in t * t
    | odd x = a * powM a (x - 1)

instance Fractional M where
    recip a = powM a $ m - 2
    fromRational d = (M . fromInteger . R.numerator $ d) * (recip . M . fromInteger . R.denominator $ d)

type GraphA = A.Array Int [Int]

graphFromEdges :: Int -> [(Int, Int)] -> GraphA
graphFromEdges n edges = graph
    where
        graph = STA.runSTArray $ do
            graphA <- MA.newArray (1, n) ([] :: [Int])
            forM_ edges $ \(u, v) -> do
                modifyArray graphA u (v:)
                modifyArray graphA v (u:)
            return graphA

{- END OF GENERAL -}

solve :: Int -> [Int] -> Int64
solve n as = unM $ solve' 0 (n + 1, -1) iAs
    where
        iAs = sort $ zip as [1 .. n]

        solve' :: Int -> (Int, Int) -> [(Int, Int)] -> M
        solve' _ _ [] = M 1
        solve' k is@(minI, maxI) iAs@((a, i):otherIas) =
            if minI <= i && i <= maxI
                then cnt * solve' (k + 1) is otherIas
                else solve' (k + 1) (min minI i, max maxI i) otherIas
            where
                cntPlaces = maxI - minI - k + 1
                cnt = M $ fromIntegral cntPlaces

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

import           Data.List

modulo :: Int
modulo = 1000000007

data State = State { left :: Int, right :: Int, fix :: Int }
data PermElement = PermElement { el :: Int, pos :: Int } deriving (Ord, Eq)
data TraverseHelperResult = TraverseHelperResult { multiplier :: Int, addfx :: Int }

traversePermutation :: [PermElement] -> State -> Int
traversePermutation [] state = 1
traversePermutation (head:permelements) (State {left = sleft, right = sright, fix = sfix})
    | pos head < sleft || pos head > sright = (let helperRes = (traverseHelper permelements (State (min sleft $ pos head) (max sright $ pos head) $ sfix + 1)) in (multiplier helperRes) * (traversePermutation permelements (State (min sleft $ pos head) (max sright $ pos head) (addfx helperRes))) `mod` modulo)
    | otherwise = traversePermutation permelements $ State sleft sright sfix

traverseHelper :: [PermElement] -> State -> TraverseHelperResult
traverseHelper [] state = TraverseHelperResult 1 $ fix state
traverseHelper (head:permelements) (State {left = sleft, right = sright, fix = sfix})
    | sleft <= (pos head) && (pos head) <= sright = (let subres = (traverseHelper permelements $ State sleft sright (sfix + 1)) in TraverseHelperResult ((sright - sleft + 1 - sfix) * (multiplier subres) `mod` modulo) (addfx subres))
    | otherwise = TraverseHelperResult 1 sfix

solveCase :: IO ()
solveCase = do
--    line_n <- getLine
    n <- fmap read getLine :: IO Int
    arr <- fmap (map read . words) getLine :: IO [Int]
    let sarr = sort [PermElement x i | (x, i) <- zip arr [0..n - 1]] in putStrLn $ show $ traversePermutation (tail sarr) (State (pos (head sarr)) (pos (head sarr)) 1)

solve :: Int -> IO ()
solve 0 = do
    return ()
solve cases_left = do
    solveCase
    solve $ cases_left - 1

main = do
    s_testcases <- getLine
    solve $ (read s_testcases :: Int)


import Prelude
import Data.List
import Data.Maybe
import Data.Function
import Data.Char
import Data.Graph
import Data.Tree
import Data.Int
--import qualified Data.HashTable.IO as B
import qualified Data.ByteString.Lazy.Char8 as B

readInts :: IO [Int]
readInts = fmap (map (foldl' (\x y -> 10*x + digitToInt y) 0) . words) getLine

textRepresentation :: Show a => [a] -> String
textRepresentation row = unwords . map show $ row

main :: IO ()
main = do
    n:_ <- readInts
    input <- readInts
    let list = map (\x -> fromIntegral . length . flatten $ x ::Int64) . components $ buildG (1,n) $ zip [1..n] input
    if null $ tail list
        then print $ (head list)^2
        else
            let max1 = maximum list
                list1= list\\[max1]
                max2 = maximum list1
                in print $ (max1+max2)^2 - max2^2 + (foldl' (+) 0 . map (^2) $ list1)

{-main :: IO ()
main = do
    print 3
    where gg=H.fromList-}

module Main where

import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.Graph
import Data.List (sort)
import Data.Tree
import qualified Data.ByteString.Lazy.Char8 as L

data Metro = Metro { next :: [Int] } deriving (Show, Eq)

treeSize :: Tree a -> Int
treeSize node = succ . sum $ map treeSize (subForest node)

getCirclesSizes :: Metro -> [Int]
getCirclesSizes (Metro ps) = map treeSize $ dfs graph [0 .. n - 1]
    where n = length (ps)
          edges = zip [0 ..] (map pred ps)
          graph = buildG (0, n - 1) edges

solve :: Metro -> Integer
solve m = case sizes of
            [x] -> sqr x
            (x:y:zs) -> sum $ map sqr (x + y:zs)
    where sizes = map fromIntegral . reverse . sort $ getCirclesSizes m
          sqr x = x * x

test0 = Metro [2, 1, 3]
test1 = Metro [1, 5, 4, 3, 2]

type Tokenizer = State [L.ByteString]

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

go :: Tokenizer Integer
go = do
  n <- nextInt
  ps <- replicateM n nextInt
  return . solve $ Metro ps

main :: IO ()
main = do
  input <- L.words <$> L.getContents
  let result = evalState go input
  print result

module Main where

import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.Graph
import Data.List (sort)
import Data.Tree
import qualified Data.ByteString.Lazy.Char8 as L

data Metro = Metro { next :: [Int] } deriving (Show, Eq)

treeSize :: Tree a -> Int
treeSize = length . flatten

getCirclesSizes :: Metro -> [Int]
getCirclesSizes (Metro ps) = map treeSize $ dfs graph [0 .. n - 1]
    where n = length (ps)
          edges = zip [0 ..] (map pred ps)
          graph = buildG (0, n - 1) edges

solve :: Metro -> Integer
solve m = case sizes of
            [x] -> sqr x
            (x:y:zs) -> sum $ map sqr (x + y:zs)
    where sizes = map fromIntegral . reverse . sort $ getCirclesSizes m
          sqr x = x * x

test0 = Metro [2, 1, 3]
test1 = Metro [1, 5, 4, 3, 2]

type Tokenizer = State [L.ByteString]

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

go :: Tokenizer Integer
go = do
  n <- nextInt
  ps <- replicateM n nextInt
  return . solve $ Metro ps

main :: IO ()
main = do
  input <- L.words <$> L.getContents
  let result = evalState go input
  print result

import Data.Graph
import Data.Foldable(Foldable(foldl'))
import Data.Int
import Data.List(sortBy)
main = getContents >>= print . exec
exec = solve . map read . words
solve (n:xs) = case sortBy (flip compare) $ map (foldl' (\l _ -> l + 1) 0) $ scc $ buildG (1, n) $ zip [1..] xs of
  (a:b:as) -> sum $ map (\x -> fromIntegral x ^ 2 :: Int64) $ (a + b):as
  [a] -> fromIntegral $ a^2

import Prelude
import Data.List
import Data.Maybe
import Data.Function
import Data.Char
import Data.Graph
import Data.Tree
--import qualified Data.HashTable.IO as B
import qualified Data.ByteString.Lazy.Char8 as B

readInts :: IO [Int]
readInts = fmap (map (foldl' (\x y -> 10*x + digitToInt y) 0) . words) getLine

textRepresentation :: Show a => [a] -> String
textRepresentation row = unwords . map show $ row

main :: IO ()
main = do
    n:_ <- readInts
    input <- readInts
    let list = map (length.flatten) . components $ buildG (1,n) $ zip [1..n] input
    if null $ tail list
        then print $ n*n
        else
            let max1 = maximum list ::Int
                list1= list\\[max1]
                max2 = maximum list1 ::Int
                in print $ (max1+max2)^2 - max2^2 + (foldl' (+) 0 . map (^2) $ list1)

{-main :: IO ()
main = do
    print 3
    where gg=H.fromList-}

import Prelude
import Data.List
import Data.Maybe
import Data.Function
import Data.Char
import Data.Graph
import Data.Tree
import Data.Int
--import qualified Data.HashTable.IO as B
import qualified Data.ByteString.Lazy.Char8 as B

readInts :: IO [Int]
readInts = fmap (map (foldl' (\x y -> 10*x + digitToInt y) 0) . words) getLine

textRepresentation :: Show a => [a] -> String
textRepresentation row = unwords . map show $ row

main :: IO ()
main = do
    n:_ <- readInts
    input <- readInts
    let list = map (length.flatten) . components $ buildG (1,n) $ zip [1..n] input
    if null $ tail list
        then print $ n*n
        else
            let max1 = maximum list
                list1= list\\[max1]
                max2 = maximum list1
                in print $ (max1+max2)^2 - max2^2 + (foldl' (+) 0 . map (^2) $ list1)

{-main :: IO ()
main = do
    print 3
    where gg=H.fromList-}


import Control.Monad

main = do
    numTests <- read <$> getLine
    replicateM_ numTests $ do
        [a,b,c,d] <- map read . words <$> getLine
        [x,y,x1,y1,x2,y2] <- map read . words <$> getLine
        if b - a > x2 - x ||
           b - a < x1 - x ||
           d - c > y2 - y ||
           d - c < y1 - y ||
           (a > 0 || b > 0) && x2 - x1 == 0 ||
           (c > 0 || d > 0) && y2 - y1 == 0 then
            putStrLn "No"
        else
            putStrLn "Yes"

type Point = (Int, Int)

solve :: Point -> Point -> Point -> Int -> Int -> Int -> Int -> Bool
solve (inix, iniy) (lbx, lby) (rtx, rty) a b c d = x >= lbx && x <= rtx && lby <= y && y <= rty &&
                                                   cornerCase (inix, iniy) (lbx, lby) (rtx, rty) a b c d
  where x = inix - a + b
        y = iniy - c + d

cornerCase :: Point -> Point -> Point -> Int -> Int -> Int -> Int -> Bool
cornerCase (inix, iniy) (lbx, lby) (rtx, rty) a b c d
  | inix == lbx && inix == rtx = a == 0 && b == 0 && if iniy == lby && iniy == rty then c == 0 && d == 0 else True
  | iniy == lby && iniy == rty = c == 0 && d == 0 && if inix == lbx && inix == rtx then a == 0 && b == 0 else True
  | otherwise = True

groupByNLines :: Int -> [String] -> [[String]]
groupByNLines _ [] = []
groupByNLines n arr = (take n arr):(groupByNLines n (drop n arr))

readInt :: String -> Int
readInt a = read a :: Int

parse :: [String] -> String
parse [fstLine, sndLine]
  | solve (x, y) (x1, y1) (x2, y2) a b c d = "YES"
  | otherwise = "NO"
  where [a, b, c, d] = map readInt $ words fstLine
        [x, y, x1, y1, x2, y2] = map readInt $ words sndLine

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

type Point = (Int, Int)

solve :: Point -> Point -> Point -> Int -> Int -> Int -> Int -> Bool
solve (inix, iniy) (lbx, lby) (rtx, rty) a b c d
  | inix == lbx && inix == rtx = a == 0 && b == 0 && if iniy == lby && iniy == rty then c == 0 && d == 0 else lby <= y && y <= rty
  | iniy == lby && iniy == rty = c == 0 && d == 0 && if inix == lbx && inix == rtx then a == 0 && b == 0 else x >= lbx && x <= rtx
  | otherwise = x >= lbx && x <= rtx && lby <= y && y <= rty
  where x = inix - a + b
        y = iniy - c + d

groupByNLines :: Int -> [String] -> [[String]]
groupByNLines _ [] = []
groupByNLines n arr = (take n arr):(groupByNLines n (drop n arr))

readInt :: String -> Int
readInt a = read a :: Int

parse :: [String] -> String
parse [fstLine, sndLine]
  | solve (x, y) (x1, y1) (x2, y2) a b c d = "YES"
  | otherwise = "NO"
  where [a, b, c, d] = map readInt $ words fstLine
        [x, y, x1, y1, x2, y2] = map readInt $ words sndLine

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

main = getLine >>= test.read
test 0 = return ()
test t = do
  (a:b:c:d:_) <- map read.words <$> getLine
  (x:y:x1:y1:x2:y2:_) <- map read.words <$> getLine
  let x' = x + b - a
      y' = y + d - c
  if x1 <= x' && x' <= x2 && y1 <= y' && y' <= y2 && (x1 /= x2 || (a == 0 && b == 0)) && (y1 /= y2 || (c == 0 && d == 0))
    then putStrLn "YES"
    else putStrLn "NO"
  test $ pred t

type Point = (Int, Int)

-- solve :: Point -> Point -> Point -> Int -> Int -> Int -> Int -> Bool
solve (iniX, iniY) (lbX, lbY) (rtX, rtY) a b c d
  | iniX == lbX && iniX == rtX = a == 0 && b == 0 && if iniY == lbY && iniY == rtY then c == 0 && d == 0 else True
  | iniY == lbY && iniY == rtY = c == 0 && d == 0 && if iniX == lbX && iniX == rtX then a == 0 && b == 0 else True
  | otherwise = x >= lbX && x <= rtX && lbY <= y && y <= rtY
  where x = iniX - a + b
        y = iniY - c + d

groupByNLines :: Int -> [String] -> [[String]]
groupByNLines _ [] = []
groupByNLines n arr = (take n arr):(groupByNLines n (drop n arr))

parse :: [String] -> String
parse [fstLine, sndLine]
  | solve (x, y) (x1, y1) (x2, y2) a b c d = "YES"
  | otherwise = "NO"
  where [a, b, c, d] = map (\x -> read x :: Int) $ words fstLine
        [x, y, x1, y1, x2, y2] = map (\x -> read x :: Int) $ words sndLine

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

type Point = (Int, Int)

solve :: Point -> Point -> Point -> Int -> Int -> Int -> Int -> Bool
solve (iniX, iniY) (lbX, lbY) (rtX, rtY) a b c d
  | iniX == lbX && iniX == rtX = a == 0 && b == 0
  | iniY == lbY && iniY == rtY = c == 0 && d == 0
  | otherwise = x >= lbX && x <= rtX && lbY <= y && y <= rtY
  where x = iniX - a + b
        y = iniY - c + d

groupByNLines :: Int -> [String] -> [[String]]
groupByNLines _ [] = []
groupByNLines n arr = (take n arr):(groupByNLines n (drop n arr))

parse :: [String] -> String
parse [fstLine, sndLine]
  | solve (x, y) (x1, y1) (x2, y2) a b c d = "YES"
  | otherwise = "NO"
  where [a, b, c, d] = map (\x -> read x :: Int) $ words fstLine
        [x, y, x1, y1, x2, y2] = map (\x -> read x :: Int) $ words sndLine

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