Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has $$$a$$$ coins, Barbara has $$$b$$$ coins and Cerene has $$$c$$$ coins. Recently Polycarp has returned from the trip around the world and brought $$$n$$$ coins.He wants to distribute all these $$$n$$$ coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives $$$A$$$ coins to Alice, $$$B$$$ coins to Barbara and $$$C$$$ coins to Cerene ($$$A+B+C=n$$$), then $$$a + A = b + B = c + C$$$.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all $$$n$$$ coins between sisters in a way described above.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given on a new line and consists of four space-separated integers $$$a, b, c$$$ and $$$n$$$ ($$$1 \le a, b, c, n \le 10^8$$$) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.

For each test case, print "YES" if Polycarp can distribute all $$$n$$$ coins between his sisters and "NO" otherwise.

module Main where

import Control.Monad
import Data.List

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

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

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [a, b, c, d] <- getIntList
        putStrLn $ solve a b c d

solve :: Int -> Int -> Int -> Int -> String
solve a b c d =
    let r = 3 * maximum [a, b, c] - sum [a, b, c] in
    if and [d >= r, mod (d - r) 3 == 0] then "YES" else "NO"

canDistribute :: Int -> Int -> Int -> Int -> Bool
canDistribute a b c n =
    let s = a + b + c + n
        third = s `div` 3
    in s `mod` 3 == 0 && third >= (maximum [a, b, c])

solve :: String -> String
solve line =
    let tokens = words line
        a = read (tokens !! 0) :: Int
        b = read (tokens !! 1) :: Int
        c = read (tokens !! 2) :: Int
        n = read (tokens !! 3) :: Int
        valid = canDistribute a b c n
    in if valid then "YES" else "NO"

solveAll :: String -> String
solveAll input =
    let tests = tail . lines $ input
        answers = map solve tests
    in unlines answers

main = interact solveAll

import Control.Monad

-- A + B + C = 3k = n + a + b + c
solve :: [Integer] -> String
solve xs
    | listSum `mod` 3 /= 0 = "NO"
    | a < 0                = "NO"
    | otherwise            = "YES"
    where listSum = sum xs
          a       = (listSum `div` 3) - maximum (take 3 xs)

main :: IO ()
main = do
    input <- getContents
    putStrLn . unlines . map (solve . map read . words) . tail . lines $ input

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

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

main = interact solve

solve :: String -> String
solve input = joinedansert
  where
      asnumbers :: [Int64]
      asnumbers = map read $ words input
      n:others = asnumbers
      byfour = splitbyfour others
      solved :: [String]
      solved = map solve' byfour
      joinedansert = intercalate "\n" solved

splitbyfour :: [Int64] -> [(Int64, Int64, Int64, Int64)]
splitbyfour [] = []
splitbyfour (a:b:c:d:xs) = (a, b, c, d):(splitbyfour xs)

solve' :: (Int64, Int64, Int64, Int64) -> String
solve' (a, b, c, n) -- = show a
    | required > n = "NO"
    | extra `mod` 3 == 0 = "YES"
    | otherwise = "NO"
     where
        maxNum :: Int64
        maxNum = maximum (a:b:c:[])
        required = (maxNum - a) + (maxNum - b) + (maxNum - c)
        extra = n - required

import Control.Monad
import Data.Int
import Data.Sequence as DSeq
import Data.Foldable

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if DSeq.null s then
                aux s
            else
                return $ toList s
        else
            aux $ s |> x
    in aux DSeq.Empty

get :: Read a => IO a
get = liftM read getToken

put :: Show a => a -> IO ()
put = putStr . show

putln :: Show a => a -> IO ()
putln = putStrLn . show

main :: IO ()
main = do
    t <- get :: IO Int
    replicateM_ t f1

f1 :: IO ()
f1 = do
    a <- get :: IO Int64
    b <- get :: IO Int64
    c <- get :: IO Int64
    n <- get :: IO Int64
    putStrLn $ if f2 a b c n then "YES" else "NO"

f2 :: Int64 -> Int64 -> Int64 -> Int64 -> Bool
f2 a b c n = (mod (a + b + c + n) 3) == 0 && (
    let v = (div (a + b + c + n) 3) in
        v - a >= 0 && v - b >= 0 && v - c >= 0
    )

import Control.Monad
import Data.Int

getToken :: IO String
getToken = do
    x <- getChar
    if x == ' ' || x == '\t' || x == '\n'
        then return [x]
        else liftM2 (:) (return x) getToken

get :: Read a => IO a
get = liftM read getToken

put :: Show a => a -> IO ()
put = putStr . show

putln :: Show a => a -> IO ()
putln = putStrLn . show

main :: IO ()
main = do
    t <- get :: IO Int
    replicateM_ t f1

f1 :: IO ()
f1 = do
    a <- get :: IO Int64
    b <- get :: IO Int64
    c <- get :: IO Int64
    n <- get :: IO Int64
    putStrLn $ if f2 a b c n then "YES" else "NO"

f2 :: Int64 -> Int64 -> Int64 -> Int64 -> Bool
f2 a b c n = (mod (a + b + c + n) 3) == 0 && (
    let v = (div (a + b + c + n) 3) in
        v - a >= 0 && v - b >= 0 && v - c >= 0
    )

import System.IO

readInt :: IO Int
readInt = readLn

castToInt x = read x::Int

main = do
    t <- readInt
    solve t

sum2 test_case = sum test_case `div` 3

solve t = do
    if t == 0 then
        return ()
    else do
        line <- getLine
        let test_case = (map castToInt . take 4 . words) line
        let x = sum2 test_case
        if sum test_case `mod` 3 /= 0 || test_case!!0 > x || test_case!!1 > x || test_case!!2 > x then
            putStrLn "NO"
        else
            putStrLn "YES"
        solve (t-1)

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

process [a,b,c,n] |mod s 3==0 && maximum [a,b,c]<=div s 3 = "YES"
		  |otherwise = "NO"
	where s= a+b+c+n

main = do
		n<- read <$> getLine :: IO Int
		x<- map(map read) <$> map words <$> replicateM n getLine::IO [[Integer]]
		mapM_ putStrLn $ map process x

import Data.List as L

solve' :: Int -> Int -> Int -> Int -> Bool
solve' a b c n = isEnough && (mod remain 3 == 0)
  where toGiveToA = c - a
        toGiveToB = c - b
        isEnough = n >= toGiveToA + toGiveToB
        remain = n - toGiveToA - toGiveToB

solve :: Int -> Int -> Int -> Int -> String
solve a b c n = if solve' a' b' c' n then "YES" else "NO"
  where [a', b', c'] = L.sort [a, b, c]

parse :: String -> String
parse input = solve a b c n
  where [a, b, c, n] = map (\x -> read x :: Int) $ words input

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

canDistribute :: Int -> Int -> Int -> Int -> Bool
canDistribute a b c n =
    let s = a + b + c + n
        third = s `div` 3
    in s `mod` 3 == 0 && third > (maximum [a, b, c])

solve :: String -> String
solve line =
    let tokens = words line
        a = read (tokens !! 0) :: Int
        b = read (tokens !! 1) :: Int
        c = read (tokens !! 2) :: Int
        n = read (tokens !! 3) :: Int
        valid = canDistribute a b c n
    in if valid then "YES" else "NO"

solveAll :: String -> String
solveAll input =
    let tests = tail . lines $ input
        answers = map solve tests
    in unlines answers

main = interact solveAll

import Control.Monad

-- A + B + C = 3k = n + a + b + c
solve :: [Integer] -> String
solve xs
    | 3 * k == listSum && k >= min = "YES"
    | otherwise                        = "NO"
    where listSum = sum xs
          k       = listSum `div` 3
          min     = minimum xs
solve _ = []

main :: IO ()
main = do
    input <- getContents
    putStrLn . unlines . map (solve . map read . words) . tail . lines $ input

import Control.Monad
import Data.Int

getToken :: IO String
getToken = do
    x <- getChar
    if x == ' ' || x == '\t' || x == '\n'
        then return [x]
        else liftM2 (\x y -> x : y) (return x) getToken

get :: Read a => IO a
get = liftM read getToken

put :: Show a => a -> IO ()
put = putStr . show

putln :: Show a => a -> IO ()
putln = putStrLn . show

main :: IO ()
main = do
    n <- get :: IO Int64
    m <- get :: IO Int64
    a <- get :: IO Int64
    putln $ f1 n m a

f1 :: Int64 -> Int64 -> Int64 -> Int64
f1 n m a = ((div (n + a - 1) a) * (div (m + a - 1) a))

import Control.Monad
import Data.Int

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if null s then
                aux s
            else
                return s
        else
            aux $ x : s
    in aux []

get :: Read a => IO a
get = liftM read getToken

put :: Show a => a -> IO ()
put = putStr . show

putln :: Show a => a -> IO ()
putln = putStrLn . show

main :: IO ()
main = do
    t <- get :: IO Int
    replicateM_ t f1

f1 :: IO ()
f1 = do
    a <- get :: IO Int64
    b <- get :: IO Int64
    c <- get :: IO Int64
    n <- get :: IO Int64
    putStrLn $ if f2 a b c n then "YES" else "NO"

f2 :: Int64 -> Int64 -> Int64 -> Int64 -> Bool
f2 a b c n = (mod (a + b + c + n) 3) == 0 && (
    let v = (div (a + b + c + n) 3) in
        v - a >= 0 && v - b >= 0 && v - c >= 0
    )


You have integer $$$n$$$. Calculate how many ways are there to fully cover belt-like area of $$$4n-2$$$ triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. $$$2$$$ coverings are different if some $$$2$$$ triangles are covered by the same diamond shape in one of them and by different diamond shapes in the other one.Please look at pictures below for better understanding.  On the left you can see the diamond shape you will use, and on the right you can see the area you want to fill. These are the figures of the area you want to fill for $$$n = 1, 2, 3, 4$$$. You have to answer $$$t$$$ independent test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$1 \le n \le 10^{9}$$$).

For each test case, print the number of ways to fully cover belt-like area of $$$4n-2$$$ triangles using diamond shape. It can be shown that under given constraints this number of ways doesn't exceed $$$10^{18}$$$.

NoteIn the first test case, there are the following $$$2$$$ ways to fill the area:  In the second test case, there is a unique way to fill the area:

main = interact $ drop 1 . dropWhile (/= '\n')

module Main where

import Control.Monad
import Data.List

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

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

printStrList :: [String] -> IO ()
printStrList = putStrLn . intercalate " "

printList :: (Show a) => [a] -> IO ()
printList = printStrList . map show

main :: IO ()
main = do
    getLine
    interact id

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

main = do
		n<- read <$> getLine ::IO Int
		k<-map read <$> replicateM n getLine ::IO [Int]
		mapM_ print k

process :: Int -> Int
process = id

readInt :: String -> Int
readInt = read

run :: Int -> IO ()
run 0 = return ()
run t = do
    n <- fmap readInt getLine
    print $ process n
    run (t-1)

main :: IO ()
main = do
    t <- fmap readInt getLine
    run t

process :: Int -> Int
process n
    | n == 1 = 1
    | otherwise = 2

readInt :: String -> Int
readInt = read

run :: Int -> IO ()
run 0 = return ()
run t = do
    n <- fmap readInt getLine
    print $ process n
    run (t-1)

main :: IO ()
main = do
    t <- fmap readInt getLine
    run t


You are given an array $$$a$$$ of length $$$n$$$, and an integer $$$x$$$. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was $$$[3, 6, 9]$$$, in a single operation one can replace the last two elements by their sum, yielding an array $$$[3, 15]$$$, or replace the first two elements to get an array $$$[9, 9]$$$. Note that the size of the array decreases after each operation.The beauty of an array $$$b=[b_1, \ldots, b_k]$$$ is defined as $$$\sum_{i=1}^k \left\lceil \frac{b_i}{x} \right\rceil$$$, which means that we divide each element by $$$x$$$, round it up to the nearest integer, and sum up the resulting values. For example, if $$$x = 3$$$, and the array is $$$[4, 11, 6]$$$, the beauty of the array is equal to $$$\left\lceil \frac{4}{3} \right\rceil + \left\lceil \frac{11}{3} \right\rceil + \left\lceil \frac{6}{3} \right\rceil = 2 + 4 + 2 = 8$$$.Please determine the minimum and the maximum beauty you can get by performing some operations on the original array.

The first input line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 1000$$$). The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq x \leq 10^9$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$), the elements of the array $$$a$$$.  It is guaranteed that the sum of values of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output two integers — the minimal and the maximal possible beauty.

NoteIn the first test case the beauty of the array does not change if we perform any operations.In the second example we can leave the array unchanged to attain the maximum beauty, and to get the minimum beauty one can replace two elements $$$4$$$ and $$$11$$$ with their sum, yielding an array $$$[6, 15]$$$, which has its beauty equal to $$$7$$$.

import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.List
import Data.Maybe
import Control.Monad (replicateM)
import Data.Int

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

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

do_test :: IO ()
do_test = do

  [n, x] <- readIntegers
  ns <- readIntegers
  let
    mini = div ((sum ns) + x - 1) x
    maxi = sum $ map ((`div` x) . (+(x-1))) ns
  putStrLn $ (show mini) ++ " " ++ (show maxi)

main :: IO [()]
main = do
  t <- readInt
  replicateM t do_test

import Control.Monad (replicateM)
import Data.Int

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

do_test :: IO ()
do_test = do

  [n, x] <- readInts
  ns <- readInts
  let
    mini = div ((sum ns) + x - 1) x
    maxi = sum $ map ((`div` x) . (+(x-1))) ns
  putStrLn $ (show mini) ++ " " ++ (show maxi)

main :: IO [()]
main = do
  t <- readLn :: IO Int
  replicateM t do_test

import Control.Arrow
import Control.Monad
import Data.Char
import Data.List (foldl)
import Data.Set (Set, fromList, member, insert)
import System.IO
import Text.Read
-- import Debug.Trace

handleCase :: Integer -> IO ()
handleCase c = do
  -- print c
  [n, x] <- fmap (map read . words) getLine :: IO [Integer]
  a <- fmap (map read . words) getLine :: IO [Integer]
  putStrLn  $ (\ (a, b) -> unwords [show a, show b]) $ solve n x a
  return ()

main :: IO ()
main = do
  t <- readLn :: IO Integer
  forM_ [1 .. t] handleCase

-- type State = (Set Integer, Integer, Integer)
--
-- c :: Integer -> State -> Integer -> State
-- c x (m, cnt, total) i
--   | i == 0 = ( m, cnt, total)
--   | newCnt `member` m = (fromList [0], 0, total + 1)
--   | otherwise = (insert newCnt m, newCnt, total)
--   where
--     newCnt = (cnt + i) `mod` x

solve :: Integer -> Integer -> [Integer] -> (Integer, Integer)
solve n x a =
  let roundUp i = (i + x - 1) `quot` x
      mx = sum $ map roundUp a
      mn = roundUp $ sum a
   in (mn, mx)

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

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

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

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

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

main = readInt >>= flip replicateM solve

solve = do
	[ _, x ] <- readIntegers
	as <- readIntegers
	let
		mi = rdiv ( sum as ) x
		ma = sum $ map ( flip rdiv x ) as
	printf "%lld %lld\n" mi ma

rdiv a b = ( a + b - 1 ) `div` b

import Control.Monad
import Data.List
import Text.Printf

readArray :: Read a => IO [a]
readArray = fmap (map read . words) getLine

readInts :: IO [Integer]
readInts = readArray

solve :: Integer -> [Integer] -> (Integer, Integer)
solve x a = (roundUp $ sum a, sum $ map roundUp a)
  where roundUp y = (y + x - 1) `div` x

solveCase :: IO String
solveCase = do
  (n:x:[]) <- readInts
  (a, b) <- fmap (solve x) readInts
  pure $ printf "%d %d" a b

main :: IO ()
main = readLn >>= flip replicateM_ (solveCase >>= putStrLn)

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

import safe Control.Arrow ((>>>))
import qualified Data.Text as T
import qualified Data.Text.IO as TI
import Data.List
import Data.Function
import Data.Maybe

main :: IO ()
main = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where
  tcio :: [T.Text] -> [String]
  tcio [] = []
  tcio (nm : rest) = ((:[]).istoline . solve . linestoiss) (nm:( take 1 rest)) ++ tcio (drop 1 rest)
  linetoi t = f 0 t where f n t = if (T.null) t then n else f (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;
  linetois = (map linetoi).(T.words); linestoiss = map linetois
  itoline = show; istoline = unwords . (map itoline); isstolines = map istoline

solve :: [[Integer]] -> [Integer]
solve [[n,x],as] = [(sum as + x - 1) `div` x, sum $ map (`div` x) $ map (+ (x-1)) as]

import Control.Monad
import Data.Int

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

runSeveral :: IO () -> IO ()
runSeveral act = do
  t <- read <$> getLine
  replicateM_ t act

ceilDiv :: Integral t => t -> t -> t
ceilDiv x y = div (x + y - 1) y

main :: IO ()
main = runSeveral $ do
  [_n, x] <- readInts
  -- reading so many Int64s with [Char]s may be too slow
  -- but the ByteString version of this is so much uglier
  a <- readInts
  let
    le = ceilDiv (sum a) x
    ri = sum [ceilDiv ai x | ai <- a]
  putStrLn . unwords $ map show [le, ri]

{-# LANGUAGE DeriveFunctor       #-}
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Arrow              ((>>>))
import           Control.Monad              (MonadPlus (mplus), foldM_, forM_,
                                             join, 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.ST.Safe         as STA
import           Data.Bits
import qualified Data.ByteString.Char8      as B8
import           Data.Char
import           Data.Functor               ((<&>))
import           Data.IORef                 (modifyIORef, newIORef, readIORef)
import           Data.Int
import qualified Data.IntMap                as IM
import           Data.List                  (elemIndices, find, findIndices,
                                             intersect, isPrefixOf, nub, sort,
                                             sortOn)
import qualified Data.Map                   as M
import           Data.Maybe                 (fromJust, fromMaybe, isJust)
import qualified Data.Set                   as S
import           Data.Traversable           (forM)
import           GHC.IO.Handle              (hDuplicateTo)
import           System.IO                  (IOMode (ReadMode, WriteMode),
                                             openFile, stdin, stdout)
import           Text.Printf                (printf)

-- import Debug.Trace (trace)
-- debug = flip trace

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

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

solve :: Int -> Int64 -> [Int64] -> (Int64, Int64)
solve n x as = (minAnswer, maxAnswer)
    where
        minAnswer = (sum as + x - 1) `div` x
        maxAnswer = sum [(a + x - 1) `div` x | a <- as]

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [n, x] <- B8.getLine <&> map readIntB8 . B8.words
        as <- B8.getLine <&> map (\e -> (fromInteger (readIntegerB8 e)) :: Int64) . B8.words
        let (minAnswer, maxAnswer) = solve n ((fromIntegral x) :: Int64) as
        printf "%lld %lld\n" minAnswer maxAnswer

import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.List
import Data.Maybe
import Control.Monad (replicateM)
import Data.Int

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

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

do_test :: IO ()
do_test = do

  [n, x] <- readInts
  ns <- readInts
  let
    mini = div ((sum ns) + x - 1) x
    maxi = sum $ map ((`div` x) . (+(x-1))) ns
  putStrLn $ (show mini) ++ " " ++ (show maxi)

main :: IO [()]
main = do
  t <- readLn :: IO Int
  replicateM t do_test

import Control.Monad (replicateM)

solve_min :: [Int] -> Int -> Int
solve_min ns x = ceiling ((fromIntegral (sum ns)) / (fromIntegral x))

solve_max :: [Int] -> Int -> Int
solve_max ns x = sum (map (ceiling . (/ (fromIntegral x)) . fromIntegral) ns)

solve :: [Int] -> Int -> (Int, Int)
solve ns x = (solve_min ns x, solve_max ns x)

do_test :: IO ()
do_test = do
  line <- getLine
  let [n, x] = (map read . words) line :: [Int] in
    do
    ns <- map read . words <$> getLine :: IO [Int]
    let (mini, maxi) = solve ns x in
      do
        putStrLn $ (show mini) ++ " " ++ (show maxi)

main :: IO [()]
main = do
  t <- readLn :: IO Int
  replicateM t do_test

import Control.Monad (replicateM)

solve_min :: [Int] -> Int -> Int
solve_min ns x = ceiling ((fromIntegral (sum ns)) / (fromIntegral x))

solve_max :: [Int] -> Int -> Int
solve_max ns x = sum (map (ceiling . (/ (fromIntegral x)) . fromIntegral) ns)

solve :: [Int] -> Int -> (Int, Int)
solve ns x = (solve_min ns x, solve_max ns x)

do_test :: IO ()
do_test = do
  line <- getLine
  let [n, x] = (map read . words) line :: [Int] in
    do
    ns <- map read . words <$> getLine :: IO [Int]
    let (mini, maxi) = solve ns x in
      do
        putStrLn $ (show mini) ++ " " ++ (show maxi)

main :: IO [()]
main = do
  t <- readLn :: IO Int
  print t
  replicateM t do_test

import Control.Arrow
import Control.Monad
import Data.Char
import Data.List (foldl)
import Data.Set (Set, fromList, member, insert)
import System.IO
import Text.Read
-- import Debug.Trace

handleCase :: Int -> IO ()
handleCase c = do
  -- print c
  [n, x] <- fmap (map read . words) getLine :: IO [Int]
  a <- fmap (map read . words) getLine :: IO [Int]
  putStrLn  $ (\ (a, b) -> unwords [show a, show b]) $ solve n x a
  return ()

main :: IO ()
main = do
  t <- readLn :: IO Int
  forM_ [1 .. t] handleCase

-- type State = (Set Int, Int, Int)
--
-- c :: Int -> State -> Int -> State
-- c x (m, cnt, total) i
--   | i == 0 = ( m, cnt, total)
--   | newCnt `member` m = (fromList [0], 0, total + 1)
--   | otherwise = (insert newCnt m, newCnt, total)
--   where
--     newCnt = (cnt + i) `mod` x

solve :: Int -> Int -> [Int] -> (Int, Int)
solve n x a =
  let roundUp i = (i + x - 1) `quot` x
      mx = sum $ map roundUp a
      mn = roundUp $ sum a
   in (mn, mx)

import Control.Arrow
import Control.Monad
import Data.Char
import Data.List (foldl)
import Data.Set (Set, fromList, member, insert)
import System.IO
import Text.Read
-- import Debug.Trace

handleCase :: Int -> IO ()
handleCase c = do
  -- print c
  [n, x] <- fmap (map read . words) getLine :: IO [Int]
  a <- fmap (map read . words) getLine :: IO [Int]
  putStrLn  $ (\ (a, b) -> unwords [show a, show b]) $ solve n x a
  return ()

main :: IO ()
main = do
  t <- readLn :: IO Int
  forM_ [1 .. t] handleCase

type State = (Set Int, Int, Int)

c :: Int -> State -> Int -> State
c x (m, cnt, total) i
  | i == 0 = ( m, cnt, total)
  | newCnt `member` m = (fromList [0], 0, total + 1)
  | otherwise = (insert newCnt m, newCnt, total)
  where
    newCnt = (cnt + i) `mod` x

solve :: Int -> Int -> [Int] -> (Int, Int)
solve n x a =
  let base = sum $ map (`quot` x) a
      mods = map (`mod` x) a
      (_, _, total) = foldl (c x) (fromList [0], 0, 0) mods
   in (base, base + total)


Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer n he can represent fraction  as a sum of three distinct positive fractions in form .Help Vladik with that, i.e for a given n find three distinct positive integers x, y and z such that . Because Chloe can't check Vladik's answer if the numbers are large, he asks you to print numbers not exceeding 109.If there is no such answer, print -1.

The single line contains single integer n (1 ≤ n ≤ 104).

If the answer exists, print 3 distinct numbers x, y and z (1 ≤ x, y, z ≤ 109, x ≠ y, x ≠ z, y ≠ z). Otherwise print -1. If there are multiple answers, print any of them.

{-# LANGUAGE TypeApplications #-}

main :: IO ()
main = do
  n <- read @ Int <$> getLine
  if n == 1
     then putStrLn "-1"
     else putStrLn . unwords . fmap show $ [n, n + 1, n * (n + 1)]

module Main where
  import Data.List
  import Control.Monad
  import Data.Array
  import qualified Data.Set as S

  toArray :: [a] -> Array Int a
  toArray xs =
    let ls = length xs - 1
        in array (0, ls) $ zip [0..ls] xs

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

  readMultilineInput :: Int -> (String -> IO a) -> IO [a]
  readMultilineInput n transformer = replicateM n (getLine >>= transformer)

  elemSet :: (Ord a) => a -> S.Set a -> Bool
  elemSet elem sets =
    let found = elem `S.lookupIndex` sets
        in toBool found
        where
          toBool :: Maybe Int -> Bool
          toBool (Just _) = True
          toBool Nothing = False

  main :: IO()
  main = do
    n <- getLine >>= return . readInt
    let m = n * (n + 1)
    case n of
      1 -> putStrLn "-1"
      _ -> putStrLn $ (show m)  ++ " " ++ (show n) ++ " " ++ (show (n + 1))

module Main where

import Control.Applicative
import Control.Monad
import Prelude
import Text.Printf

main = do
    n <- read <$> getLine :: IO Int
    if n == 1 then print $ -1
    else printf "%d %d %d\n" n (n + 1) (n*(n+1))

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

main = do
	n<-read <$> getLine ::IO Int
	let a =  take 1 $ [[n,y,denominator z] |y<-[n+1..(n+n)],let z=(1%n)- ( 1%y), numerator z==1,denominator z /=y]
	if length a ==1 then putStrLn (intercalate " " ( map show (head a))) else print (-1)

{-# LANGUAGE TypeApplications #-}

main :: IO ()
main = do
  n <- read @ Int <$> getLine
  putStrLn . unwords . fmap show $ [n, n + 1, n * (n + 1)]

module Main where
  import Data.List
  import Control.Monad
  import Data.Array
  import qualified Data.Set as S

  toArray :: [a] -> Array Int a
  toArray xs =
    let ls = length xs - 1
        in array (0, ls) $ zip [0..ls] xs

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

  readMultilineInput :: Int -> (String -> IO a) -> IO [a]
  readMultilineInput n transformer = replicateM n (getLine >>= transformer)

  elemSet :: (Ord a) => a -> S.Set a -> Bool
  elemSet elem sets =
    let found = elem `S.lookupIndex` sets
        in toBool found
        where
          toBool :: Maybe Int -> Bool
          toBool (Just _) = True
          toBool Nothing = False

  main :: IO()
  main = do
    n <- getLine >>= return . readInt
    putStrLn $ "1 " ++ (show n) ++ " " ++ (show (n + 1))

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

main = do
	n<-read <$> getLine ::IO Int
	let a =  take 1 $ [[n,y,denominator z] |y<-[n+1..(n+n)],let z=(1%n)- ( 1%y), numerator z==1]
	if length a ==1 then putStrLn (intercalate " " ( map show (head a))) else print (-1)

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

main = do
	n<-read <$> getLine ::IO Int
	print $ head $ [[x,y,denominator z] |x<-[2..10^9],y<-[x+1..10^9],let z=(2%n)- ((1%x) +( 1%y)), numerator z==1]


Phoenix's homeland, the Fire Nation had $$$n$$$ cities that were connected by $$$m$$$ roads, but the roads were all destroyed by an earthquake. The Fire Nation wishes to repair $$$n-1$$$ of these roads so that all the cities are connected again. The $$$i$$$-th city has $$$a_i$$$ tons of asphalt. $$$x$$$ tons of asphalt are used up when repairing a road, and to repair a road between $$$i$$$ and $$$j$$$, cities $$$i$$$ and $$$j$$$ must have at least $$$x$$$ tons of asphalt between them. In other words, if city $$$i$$$ had $$$a_i$$$ tons of asphalt and city $$$j$$$ had $$$a_j$$$ tons, there would remain $$$a_i+a_j-x$$$ tons after repairing the road between them. Asphalt can be moved between cities if the road between them is already repaired.Please determine if it is possible to connect all the cities, and if so, output any sequence of roads to repair.

The first line contains integers $$$n$$$, $$$m$$$, and $$$x$$$ ($$$2 \le n \le 3 \cdot 10^5$$$; $$$n-1 \le m \le 3 \cdot 10^5$$$; $$$1 \le x \le 10^9$$$) — the number of cities, number of roads, and amount of asphalt needed to repair one road. The next line contains $$$n$$$ space-separated integer $$$a_i$$$ ($$$0 \le a_i \le 10^9$$$) — the amount of asphalt initially at city $$$i$$$. The next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$x_i\ne y_i$$$; $$$1 \le x_i, y_i \le n$$$) — the cities connected by the $$$i$$$-th road. It is guaranteed that there is at most one road between each pair of cities, and that the city was originally connected before the earthquake.

If it is not possible to connect all the cities, print NO. Otherwise, print YES followed by $$$n-1$$$ integers $$$e_1, e_2, \dots, e_{n-1}$$$, the order in which the roads should be repaired. $$$e_i$$$ is the index of the $$$i$$$-th road to repair. If there are multiple solutions, print any.

NoteIn the first example, the roads are repaired in the following order:   Road $$$3$$$ is repaired, connecting cities $$$3$$$ and $$$4$$$. City $$$4$$$ originally had $$$4$$$ tons of asphalt. After this road is constructed, $$$3$$$ tons remain.  Road $$$2$$$ is repaired, connecting cities $$$2$$$ and $$$3$$$. The asphalt from city $$$4$$$ can be transported to city $$$3$$$ and used for the road. $$$2$$$ tons remain.  Road $$$1$$$ is repaired, connecting cities $$$1$$$ and $$$2$$$. The asphalt is transported to city $$$2$$$ and used for the road. $$$1$$$ ton remain.  Road $$$4$$$ is repaired, connecting cities $$$4$$$ and $$$5$$$. The asphalt is transported to city $$$4$$$ and used for the road. No asphalt remains.  All the cities are now connected.In the second example, cities $$$1$$$ and $$$2$$$ use all their asphalt together to build the road. They each have $$$1$$$ ton, so together they have $$$2$$$ tons, which is enough.In the third example, there isn't enough asphalt to connect cities $$$1$$$ and $$$2$$$.

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

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

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

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

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

type Graph = Array Int [(Int,Int)]

buildG :: (Int, Int) -> [(Int, (Int, Int))] -> Graph
buildG = accumArray (flip (:)) []

main = do
    [n,m,x'] <- map parseInt . BS.words <$> BS.getLine
    let xx = fromIntegral x' :: Int64
    a <- listArray (1,n) . map (fromIntegral . parseInt) . BS.words <$> BS.getLine :: IO (UArray Int Int64)
    uf <- newArray (1,n) (-1) :: IO (IOArray Int Int)

    let union a b = do
            ufa <- readArray uf a
            ufb <- readArray uf b
            let un aa bb = writeArray uf aa (ufa + ufb) >> writeArray uf bb aa
            if ufa < ufb then un a b else un b a
        find a = do
            ufa <- readArray uf a
            if ufa < 0 then
                return a
            else do
                r <- find ufa
                writeArray uf a r
                return r

    es <- newIORef []
    forM_ [1..m] $ \i -> do
        [a,b] <- map parseInt . BS.words <$> BS.getLine
        aa <- find a
        bb <- find b
        when (aa /= bb) $ do
            union aa bb
            modifyIORef' es ((a,(b,i)):)
            modifyIORef' es ((b,(a,i)):)
    es <- readIORef es

    let g = buildG (1,n) es
        (c,s) = runST $ do
            c <- newArray (1,n) 1 :: ST s (STUArray s Int Int)
            s <- newListArray (1,n) (elems a) :: ST s (STUArray s Int Int64)
            let dfs x p = forM_ (g ! x) $ \(y,_) -> when (y /= p) $ do
                dfs y x
                readArray c y >>= \v -> modifyArray (+v) c x
                readArray s y >>= \v -> modifyArray (+v) s x
            dfs 1 0
            c <- unsafeFreezeSTUArray c
            s <- unsafeFreezeSTUArray s
            return (c,s)

    if (s ! 1) < fromIntegral (n-1) * xx then
        putStrLn "NO"
    else do
        putStrLn "YES"
        ans <- newIORef [] :: IO (IORef [Int])

        let dfs :: Int -> Int -> [(Int64, Int, Int)] -> IO ()
            dfs x p w = do
                let asd = reverse . sort $ [((s ! y) - (xx * fromIntegral (c ! y)),y,ei) | (y,ei) <- g ! x, y /= p] ++ w
                qwe <- newIORef (a ! x)
                forM_ asd $ \(v, y, ei) -> do
                    if y == p then do
                        modifyIORef' ans (ei:)
                    else do
                        t <- readIORef qwe
                        dfs y x [(t-xx,x,ei)]
                    modifyIORef' qwe (+v)
        dfs 1 0 []
        mapM_ print . reverse =<< readIORef ans


We will consider the numbers $$$a$$$ and $$$b$$$ as adjacent if they differ by exactly one, that is, $$$|a-b|=1$$$.We will consider cells of a square matrix $$$n \times n$$$ as adjacent if they have a common side, that is, for cell $$$(r, c)$$$ cells $$$(r, c-1)$$$, $$$(r, c+1)$$$, $$$(r-1, c)$$$ and $$$(r+1, c)$$$ are adjacent to it.For a given number $$$n$$$, construct a square matrix $$$n \times n$$$ such that:   Each integer from $$$1$$$ to $$$n^2$$$ occurs in this matrix exactly once;  If $$$(r_1, c_1)$$$ and $$$(r_2, c_2)$$$ are adjacent cells, then the numbers written in them must not be adjacent.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$). Then $$$t$$$ test cases follow. Each test case is characterized by one integer $$$n$$$ ($$$1 \le n \le 100$$$).

For each test case, output:    -1, if the required matrix does not exist;  the required matrix, otherwise (any such matrix if many of them exist).  The matrix should be outputted as $$$n$$$ lines, where each line contains $$$n$$$ integers.

import Control.Arrow

main = interact $
         words >>> drop 1
         >>> map (
               read
               >>> solve
               >>> maybe "-1\n" (unlines . map (unwords . map show)))
         >>> concat

solve :: Int -> Maybe [[Int]]
solve 1 = Just [[1]]
solve 2 = Nothing
solve n = Just [[val $ i*n + j | j <- [0..n-1]] | i <- [0..n-1]]
    where
        val x = 1 + (if even x then (n^2 `div` 2) else 0) + x `div` 2

import Control.Monad

main = do
    t <- read <$> getLine
    replicateM_ t $
        getLine >>= putStr . unlines . map (unwords . map show) . solve . read

solve :: Int -> [[Int]]
solve 2 = [[-1]]
solve n = chunks n $ [2,4 .. n * n] ++ [1,3 .. n * n]

chunks :: Int -> [Int] -> [[Int]]
chunks _ [] = []
chunks n l =
    let (xs, ys) = splitAt n l
     in xs : chunks n ys

{-# LANGUAGE ParallelListComp #-}
import Control.Arrow
import Data.List

main = interact $
         words >>> drop 1
         >>> map (
               read
               >>> solve
               >>> maybe "-1\n" (unlines . map (unwords . map show)))
         >>> concat

solve :: Int -> Maybe [[Int]]
solve 1 = Just [[1]]
solve 2 = Nothing
solve 3 = Just [[1,6,2], [7,3,8], [4,9,5]]
solve n = let (Just grid) = solve (n - 1) in
            Just $ [(n - 1) * n + 1 .. n^2] : [((n - 1)^2 + x) : row | row <- grid | x <- [1..n-1]]


Let there be an array $$$b_1, b_2, \ldots, b_k$$$. Let there be a partition of this array into segments $$$[l_1; r_1], [l_2; r_2], \ldots, [l_c; r_c]$$$, where $$$l_1 = 1$$$, $$$r_c = k$$$, and for any $$$2 \leq i \leq c$$$ holds that $$$r_{i-1} + 1 = l_i$$$. In other words, each element of the array belongs to exactly one segment.Let's define the cost of a partition as $$$$$$c + \sum_{i = 1}^{c} \operatorname{mex}(\{b_{l_i}, b_{l_i + 1}, \ldots, b_{r_i}\}),$$$$$$ where $$$\operatorname{mex}$$$ of a set of numbers $$$S$$$ is the smallest non-negative integer that does not occur in the set $$$S$$$. In other words, the cost of a partition is the number of segments plus the sum of MEX over all segments. Let's define the value of an array $$$b_1, b_2, \ldots, b_k$$$ as the maximum possible cost over all partitions of this array.You are given an array $$$a$$$ of size $$$n$$$. Find the sum of values of all its subsegments.An array $$$x$$$ is a subsegment of an array $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

The input contains several test cases. The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 30$$$) — the number of test cases. The first line for each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the length of the array. The second line contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$100$$$.

For each test case print a single integer — the answer to the problem.

NoteIn the second test case:   The best partition for the subsegment $$$[2, 0, 1]$$$: $$$[2], [0, 1]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0, 1\}) = 2 + 0 + 2 = 4$$$.  The best partition for the subsegment $$$[2, 0]$$$: $$$[2], [0]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0\}) = 2 + 0 + 1 = 3$$$  The best partition for the subsegment $$$[2]$$$: $$$[2]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{2\}) = 1 + 0 = 1$$$.  The best partition for the subsegment $$$[0, 1]$$$: $$$[0, 1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0, 1\}) = 1 + 2 = 3$$$.  The best partition for the subsegment $$$[0]$$$: $$$[0]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0\}) = 1 + 1 = 2$$$.  The best partition for the subsegment $$$[1]$$$: $$$[1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{1\}) = 1 + 0 = 1$$$. The sum of values over all subsegments equals to $$$4 + 3 + 1 + 3 + 2 + 1 = 14$$$.

import Data.List

parseInt :: String -> Int
parseInt number = (read number) :: Int

readInt :: IO Int
readInt = do
    number <- getLine
    pure $ parseInt number

readIntArr :: IO [Int]
readIntArr = do
    numbers <- getLine
    pure $ map parseInt $ words numbers

calc :: (Int, Int, [Int]) -> Int
calc (_, _, []) = 0
calc (i, n, (0 : xs)) = (i + 1) * (n - i) + calc (i + 1, n, xs)
calc (i, n, (_ : xs)) = calc (i + 1, n, xs)

solve :: IO ()
solve = do
    n   <- readInt
    arr <- readIntArr
    print $ (n * (n + 1) * (n + 2)) `div` 6 + (calc (0, n, arr))

readLoop :: Int -> IO ()
readLoop i =
    if (i == 0)
        then pure ()
        else do
            solve
            readLoop (i - 1)

main :: IO ()
main = do
    n <- readInt
    readLoop n

main = interact $ unlines . map p . chunk 2 . drop 1 . lines

chunk n [] = []
chunk n xs = take n xs : chunk n (drop n xs)

f n t x = let i1 = fst t
              i2 = n - i1 + 1
              s = snd t
          in case x of 0 -> (i1 + 1, s + i1 * i2 * 2)
                       _ -> (i1 + 1, s + i1 * i2)

calc n = foldl (f n) (1,0)

p xs = let ((n:_):s:_) = fmap (fmap read . words) xs :: [[Int]]
        in show $ snd $ calc n s

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

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

mainFun :: SP Builder
mainFun = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    n <- getInt
    a <- replicateM n getInt
    let
      ans = foldl' (+) 0 $ do
        suff <- tails a
        seg <- inits suff
        v <- seg
        pure $ if  v == 0  then  2  else  1
    pure $ putInts [ans]

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

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

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

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

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

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


You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.

For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.

NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.

module Main where
import Data.Functor ((<&>))
import Control.Monad (forM, replicateM, replicateM_)
import Data.Foldable (traverse_)
import GHC.Float.RealFracMethods (ceilingDoubleInt, floorDoubleInt)
import Data.List (group, sort)
import Data.Ratio ((%))
import Prelude hiding (floor)
import Control.Monad (forM_)

readInts :: IO [Int]
readInts = getLine <&> words <&> fmap read

readString :: IO String
readString = getLine

toDoubles :: (Functor f, Integral a) => f a -> f Double
toDoubles xs = (\x -> fromIntegral x :: Double) <$> xs

toDouble :: (Integral a) => a -> Double
toDouble = fromIntegral

ceil :: Double -> Int
ceil = ceilingDoubleInt

floor :: Double -> Int
floor = floorDoubleInt

main :: IO ()
main = do
  t:_ <- readInts
  replicateM_ t $ do
    n:_ <- readInts
    as <- readInts
    let
      maxi = maximum as
      mini = minimum as
      ans xs
        | sort xs == xs = 0
        | maxi == last xs || mini == head xs = 1
        | mini == last xs && maxi == head xs = 3
        | otherwise = 2
    print $ ans as

main = do
  interact (unlines .run. map f . lines)

f :: String -> [Int]
f inp = (map g (words inp)) where g x = read x :: Int

run :: [[Int]]->[[Char]]
run (x:y:z:xs)= ((solve (head y) z): (run ([(head x) - 1]: xs)))
run [[0]] = []

solve :: Int -> [Int] -> [Char]
solve y z |z == [1..y] = "0"
  |head z == 1 = "1"
  |last z == y = "1"
  |((head z == y) && (last z == 1)) = "3"
  | otherwise = "2"

import qualified Data.ByteString.Lazy.Char8 as BS
import Control.Monad
import Data.List
import Data.Maybe
import System.IO
import System.IO.Unsafe

deb s e = unsafePerformIO $ do
    hPutStrLn stderr s
    return e

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

solve :: [Int] -> Int
solve xs
    | Data.List.sort xs == xs =
        0
    | minimum xs == head xs || maximum xs == last xs =
        1
    | minimum xs == last xs && maximum xs == head xs =
        3
    | otherwise =
        2

main = do
    ls <- tail . BS.lines <$> BS.getContents
    let ls' = snd <$> filter (odd . fst) (zip [0..] ls)
    forM_ ls' (print . solve . map parseInt . BS.words)

import Control.Monad

main = do
    t <- read <$> getLine
    replicateM_ t $ do
        n <- read <$> getLine :: IO Int
        a <- map read . words <$> getLine :: IO [Int]
        print $
            if a == [1 .. n]
                then 0
                else if head a == 1 || last a == n
                         then 1
                         else if head a /= n || last a /= 1
                                  then 2
                                  else 3

module Main where
import Data.Functor ((<&>))
import Control.Monad (forM, replicateM, replicateM_)
import Data.Foldable (traverse_)
import GHC.Float.RealFracMethods (ceilingDoubleInt, floorDoubleInt)
import Data.List (group, sort)
import Data.Ratio ((%))
import Prelude hiding (floor)
import Control.Monad (forM_)

readInts :: IO [Int]
readInts = getLine <&> words <&> fmap read

readString :: IO String
readString = getLine

toDoubles :: (Functor f, Integral a) => f a -> f Double
toDoubles xs = (\x -> fromIntegral x :: Double) <$> xs

toDouble :: (Integral a) => a -> Double
toDouble = fromIntegral

ceil :: Double -> Int
ceil = ceilingDoubleInt

floor :: Double -> Int
floor = floorDoubleInt

main :: IO ()
main = do
  t:_ <- readInts
  replicateM_ t $ do
    n:_ <- readInts
    as <- readInts
    let
      maxi = maximum as
      mini = minimum as
      unsorted xs
          | sort xs == xs = 0
          | otherwise = 1
      ans xs
        | sort xs == xs = 0
        | maxi == last xs || mini == head xs = 1
        | mini == last xs || maxi == head xs = 3
        | otherwise = 2
    print $ ans as

import qualified Data.ByteString.Lazy.Char8 as BS
import Control.Monad
import Data.List
import Data.Maybe
import System.IO
import System.IO.Unsafe

deb s e = unsafePerformIO $ do
    hPutStrLn stderr s
    return e

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

solve :: [Int] -> Int
solve xs
    | Data.List.sort xs == xs =
        0
    | minimum xs == head xs || maximum xs == last xs =
        1
    | minimum xs == last xs || maximum xs == head xs =
        3
    | otherwise =
        2

main = do
    ls <- tail . BS.lines <$> BS.getContents
    let ls' = snd <$> filter (odd . fst) (zip [0..] ls)
    forM_ ls' (print . solve . map parseInt . BS.words)


Iahub has drawn a set of n points in the cartesian plane which he calls "special points". A quadrilateral is a simple polygon without self-intersections with four sides (also called edges) and four vertices (also called corners). Please note that a quadrilateral doesn't have to be convex. A special quadrilateral is one which has all four vertices in the set of special points. Given the set of special points, please calculate the maximal area of a special quadrilateral.

The first line contains integer n (4 ≤ n ≤ 300). Each of the next n lines contains two integers: xi, yi ( - 1000 ≤ xi, yi ≤ 1000) — the cartesian coordinates of ith special point. It is guaranteed that no three points are on the same line. It is guaranteed that no two points coincide.

Output a single real number — the maximal area of a special quadrilateral. The answer will be considered correct if its absolute or relative error does't exceed 10 - 9.

NoteIn the test example we can choose first 4 points to be the vertices of the quadrilateral. They form a square by side 4, so the area is 4·4 = 16.

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

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

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

maxRect p1 p2 l = abs (a1 - a2)
    where
    l'  = map f $ filter ((/=p1) <&&> (/=p2)) $ l
    f p = signedArea3 p1 p2 p
    a1  = maximum l'
    a2  = minimum l'

signedArea l = (sum $ zipWith (\(a,b) (c,d) -> a*d - b*c) l (tail (cycle l)))

signedArea3 (x1,y1) (x2,y2) (x3,y3) = a*d - b*c
    where
    (a,b) = (x2-x1,y2-y1)
    (c,d) = (x3-x1,y3-y1)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

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

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

--maxRect p1 p2 = abs . uncurry (-)  maxMin . map (signedArea3 p1 p2) . filter ((/=p1) <&&> (/=p2))

maxRect p1 p2 l = go minBound maxBound  l
    where
    go !a !b [] = a - b
    go !a !b (p:ps)
        | p == p1 || p == p2 = go a b ps
        | otherwise =
            let x = signedArea3 p1 p2 p in
                go (max a x) (min b x) ps

signedArea3 (x1,y1) (x2,y2) (x3,y3) =
    (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)

--maxMin = foldl' (\(a,b) x -> (max a x,min b x)) (minBound,maxBound)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

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

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

maxRect p1 p2 l = go minBound maxBound  l
    where
    go !a !b (p:ps)
        | p == p1 || p == p2 = go a b ps
        | otherwise =
            let x = signedArea3 p1 p2 p in
                go (max a x) (min b x) ps
    go !a !b [] = a - b

signedArea3 (x1,y1) (x2,y2) (x3,y3) =
    (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

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

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

maxRect p1 p2 l = abs (a1 - a2)
    where
    l'  = map (signedArea3 p1 p2) $ filter ((/=p1) <&&> (/=p2)) $ l
    a1  = maximum l'
    a2  = minimum l'

signedArea3 (x1,y1) (x2,y2) (x3,y3) = (x2-x1)*(y3-y1) - (y2-y1)*(x3-x1)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

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

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

maxRect p1 p2 l = go minBound maxBound  l
    where
    go a b [] = a - b
    go a b (p:ps)
        | p == p1 || p == p2 = go a b ps
        | otherwise =
            let x = signedArea3 p1 p2 p in
                go (max a x) (min b x) ps

signedArea3 (x1,y1) (x2,y2) (x3,y3) =
    (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

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

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

maxRect p1 p2 l = go minBound maxBound  l
    where
    go !a !b (p:ps)
        | p == p1 || p == p2 = go a b ps
        | otherwise =
            let x = signedArea3 p1 p2 p in
                go (max a x) (min b x) ps
    go !a !b [] = a - b

{-# INLINE signedArea3 #-}
signedArea3 (x1,y1) (x2,y2) (x3,y3) =
    (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

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

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

maxRect p1 p2 l = abs (a1 - a2)
    where
    l'  = map f l
    f p = signedArea3 p1 p2 p
    a1  = maximum l'
    a2  = minimum l'

signedArea l = (sum $ zipWith (\(a,b) (c,d) -> a*d - b*c) l (tail (cycle l)))

signedArea3 (x1,y1) (x2,y2) (x3,y3) = a*d - b*c
    where
    (a,b) = (x2-x1,y2-y1)
    (c,d) = (x3-x1,y3-y1)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

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

type Point = (Double,Double)

main = do
    n <- readLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- readsLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = maximum [ maxRect p1 p2 l | p1 <- l, p2 <- l, p1 /= p2 ]

maxRect p1@(x1,y1) p2@(x2,y2) l = a1 - a2
    where
    l'  = map f l
    f p = signedArea [p1,p2,p]
    a1  = maximum l'
    a2  = minimum l'

signedArea l = 0.5 * (sum $ zipWith (\(a,b) (c,d) -> a*d - b*c) l (tail l))

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

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

type Point = (Int,Int)

main = do
    n <- readInt <$> B.getLine
    l <- replicateM n parseLine
    print $ solve n l

parseLine :: IO Point
parseLine = do
    [a,b] <- map readInt . B.words <$> B.getLine
    return (a,b)

solve :: Int -> [Point] -> Double
solve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]

--maxRect p1 p2 = abs . uncurry (-)  maxMin . map (signedArea3 p1 p2) . filter ((/=p1) <&&> (/=p2))

maxRect p1 p2 l = go minBound maxBound  l
    where
    go !a !b [] = a - b
    go !a !b (p:ps)
        | p == p1 || p == p2 = go a b ps
        | otherwise =
            let x = signedArea3 p1 p2 p in
                go (max a x) (min a x) ps

signedArea3 (x1,y1) (x2,y2) (x3,y3) =
    (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)

--maxMin = foldl' (\(a,b) x -> (max a x,min b x)) (minBound,maxBound)


There is a chess board of size $$$n \times m$$$. The rows are numbered from $$$1$$$ to $$$n$$$, the columns are numbered from $$$1$$$ to $$$m$$$.Let's call a cell isolated if a knight placed in that cell can't move to any other cell on the board. Recall that a chess knight moves two cells in one direction and one cell in a perpendicular direction:   Find any isolated cell on the board. If there are no such cells, print any cell on the board.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 64$$$) — the number of testcases. The only line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 8$$$) — the number of rows and columns of the board.

For each testcase, print two integers — the row and the column of any isolated cell on the board. If there are no such cells, print any cell on the board.

NoteIn the first testcase, all cells are isolated. A knight can't move from any cell of the board to any other one. Thus, any cell on board is a correct answer.In the second testcase, there are no isolated cells. On a normal chess board, a knight has at least two moves from any cell. Thus, again, any cell is a correct answer.In the third testcase, only the middle cell of the board is isolated. The knight can move freely around the border of the board, but can't escape the middle.

{-# LANGUAGE ScopedTypeVariables #-}

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Control.Monad.Trans.State
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import qualified Data.ByteString.Lazy.Char8 as P
import Data.Maybe
import System.IO

mainFun :: SP Builder
mainFun = do
  casnum <- getInt
  ress <- forM [1 .. casnum] $ \_ -> do
    n <- getInt
    m <- getInt
    let res
          | n == 1 || m == 1 = [1, 1] -- isolate on [1,1]
          | n >= 4 || m >= 4 = [1, 1] -- no isolate
          | otherwise = [2, 2]
    pure res
  pure $ foldl1 (<>) $ map putInts ress

type SP = State P.ByteString

type S = StateT P.ByteString

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

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

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

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

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

--
-- 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
import Data.Tuple

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 $ do
        [n,m] <- ri
        return (n,m)
    mapM_ (putStrLn.showT.solve) tcs

showT (a,b) = show a ++ " " ++ show b

solve (n,m) = f (n,m) :: (Int,Int)
  where
    f | n <= m     =        solveN
      | otherwise  = swap . solveN . swap

solveN (n,m) | n >  m            = error "Wrong usage"
             | n >= 2 && m >= 4  = (2,2)
             | n == 1            = (1,1)
             | n == 2            = (2,2)
             | n == 3            = (2,2)
             | otherwise         = error "Logic error (impossible)"

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

import qualified Data.ByteString.Char8 as B8
import qualified Data.String as S

import Control.Arrow ((>>>))
import Data.Functor ((<&>))
import Data.Maybe
import qualified Data.Traversable as T

import qualified Control.Applicative as A
import qualified Control.Monad as M
import qualified Control.Monad.State as MS
import qualified Control.Monad.Trans as MT
import qualified Control.Monad.Trans.Maybe as M

import qualified Data.List as L
import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import qualified Data.IntSet as IS
import qualified Data.IntMap as IM
import qualified Data.Set as S
import Data.List (sortBy, sortOn)

import Data.Char
import Data.Int

import System.IO (stdin, stdout, hFlush)
import Text.Printf

#ifdef DEBUG
import Debug.Trace (trace, traceM, traceShowM)
debug = flip trace

tracing t x = trace (t ++ " = " ++ show x) x
debugging x t = tracing t x

tracingM t x = traceM $ t ++ " = " ++ show x

#else

debug x _ = x
trace _ x = x
tracing _ x = x
debugging x _ = x

traceM _ = pure ()
tracingM _ _ = pure ()
#endif

{- reading -}
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))

solve 1 m = [1, m]
solve n 1 = [n, 1]
solve n m = [2, 2]

main :: IO()
main = do
	t <- B8.getLine <&> readIntB8
	M.replicateM_ t $ do
		[n, m] <- B8.getLine <&> readIntB8s
		let answer = solve n m
		M.forM_ answer $ \x -> printf "%d " x
		putStrLn ""

import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase = map read . words <$> getLine >>=
        \[n, m] -> case isolated n m of
                     Just (x, y) -> putStrLn (show x ++ " " ++ show y)
                     Nothing -> putStrLn "1 1"
isolated :: Int -> Int -> Maybe (Int, Int)
isolated n m = if (div n 2) >= 2 && (div m 2) >= 2
               then Nothing
               else Just (mod n 2 + div n 2, mod m 2 + div m 2)

import Control.Monad

toShow (x,y) = show x ++ " " ++ show y

solve n m = (div (n+1) 2,div (m+1) 2)

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let [n,m] = map read . words $ input ::[Int]
        putStrLn.toShow$ solve n m
    return ()

{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad
import Control.Monad.State (State, evalState, get, gets, put)
import Data.Bool
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Function
import Data.Int
import Data.List
import Data.Maybe
import Debug.Trace

main :: IO ()
main = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1 ..] >>> map (uncurry output) >>> C.unlines

data TC = TC { n :: Int, m :: Int }

type Output = (Int, Int)

input :: Scanner TC
input = do
  n <- int
  m <- int
  return TC {..}

solve :: TC -> Output
solve TC {..}
  | n >= 2 && m >= 2 = (2, 2)
  | otherwise = (1, 1)

output :: Int -> Output -> C.ByteString
output _ (x, y) = C.pack $ show x <> " " <> show y

-------------------------- Template ------------------------------------------
-- Debug
debug :: Show a => a -> a
#ifdef ONLINE_JUDGE
debug = id
#else
debug a = trace (show a) a
#endif

-- Lists
groupOn :: Eq b => (a -> b) -> [a] -> [[a]]
groupOn = groupBy . on (==)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts

adjacents :: [a] -> [(a, a)]
adjacents xs = zip xs (tail xs)

adjacentsWith :: (a -> a -> b) -> [a] -> [b]
adjacentsWith f xs = zipWith f xs (tail xs)

count :: Eq a => a -> [a] -> Int
count = countBy . (==)

countBy :: (a -> Bool) -> [a] -> Int
countBy p = length . filter p

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

readStr :: Read a => Scanner a
readStr = read <$> str

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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

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

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

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

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

(><) = times

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

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

showB :: Show a => a -> C.ByteString
showB = C.pack . show

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UnboxedTuples #-}

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Control.Monad.Trans.State
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Bits
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import qualified Data.ByteString.Lazy.Char8 as P
import Data.List
import Data.Maybe
import Data.Semigroup
import GHC.Exts
import System.IO

mainFun :: SP Builder
mainFun = do
  casnum <- getInt
  ress <- forM [1 .. casnum] $ \_ -> do
    n <- getInt
    m <- getInt
    let res
          | n == 2 && (m == 2 || m == 3) = [1, 2]
          | n == 3 && m == 2 = [2, 1]
          | otherwise = [1, 1]
    pure res
  pure $ foldl1 (<>) $ map putInts ress
type SP = State P.ByteString

type S = StateT P.ByteString

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

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

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

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

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

--
-- 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
import Data.Tuple

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 $ do
        [n,m] <- ri
        return (n,m)
    mapM_ (putStrLn.showT.solve) tcs

showT (a,b) = show a ++ " " ++ show b

solve (n,m) = f (n,m) :: (Int,Int)
  where
    f | n <= m     =        solveN
      | otherwise  = swap . solveN . swap

solveN (n,m) | n >= 2 && m >= 4  = (2,4)  -- any
             | n == 1            = (1,1)
             | n == 2            = (1,1)
             | n == 3            = (2,2)
             | otherwise         = error "Logic error (impossible)"


You are a game designer and want to make an obstacle course. The player will walk from left to right. You have $$$n$$$ heights of mountains already selected and want to arrange them so that the absolute difference of the heights of the first and last mountains is as small as possible. In addition, you want to make the game difficult, and since walking uphill or flat is harder than walking downhill, the difficulty of the level will be the number of mountains $$$i$$$ ($$$1 \leq i < n$$$) such that $$$h_i \leq h_{i+1}$$$ where $$$h_i$$$ is the height of the $$$i$$$-th mountain. You don't want to waste any of the mountains you modelled, so you have to use all of them. From all the arrangements that minimize $$$|h_1-h_n|$$$, find one that is the most difficult. If there are multiple orders that satisfy these requirements, you may find any.

The first line will contain a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — the number of mountains. The second line of each test case contains $$$n$$$ integers $$$h_1,\ldots,h_n$$$ ($$$1 \leq h_i \leq 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th mountain. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output $$$n$$$ integers — the given heights in an order that maximizes the difficulty score among all orders that minimize $$$|h_1-h_n|$$$. If there are multiple orders that satisfy these requirements, you may output any.

NoteIn the first test case:The player begins at height $$$2$$$, next going up to height $$$4$$$ increasing the difficulty by $$$1$$$. After that he will go down to height $$$1$$$ and the difficulty doesn't change because he is going downhill. Finally the player will go up to height $$$2$$$ and the difficulty will increase by $$$1$$$. The absolute difference between the starting height and the end height is equal to $$$0$$$ and it's minimal. The difficulty is maximal.In the second test case:The player begins at height $$$1$$$, next going up to height $$$3$$$ increasing the difficulty by $$$1$$$. The absolute difference between the starting height and the end height is equal to $$$2$$$ and it's minimal as they are the only heights. The difficulty is maximal.

import Control.Monad
import Data.List
readInts = fmap (map read.words) getLine :: IO [Int]
printArr = putStrLn . unwords . map show

printResult = do
    n <- readLn :: IO Int
    h <- readInts
    let sh = sort h
    if n <= 2 then printArr sh
    else
        let zh = zip (zipWith (-) (tail sh) sh) [0..]
            (_,i) = minimum zh
            (f,l) = splitAt (i+1) sh
        in printArr $ l ++ f

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

import Control.Monad
import Data.List
readInts = fmap (map read.words) getLine :: IO [Int]

toStr [] = ""
toStr (x:xs) = show x ++ " " ++ toStr xs

printResult = do
    n <- readLn :: IO Int
    h <- readInts
    let sh = sort h
    if n <= 2 then putStrLn $ toStr sh
    else
        let zh = zip (zipWith (-) (tail sh) sh) [0..]
            (_,i) = minimum zh
            (f,l) = splitAt (i+1) sh
        in putStrLn $ toStr $ l ++ f

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

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

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

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

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    as <- sort <$> getInts
    let diff = minimum $ zipWith (flip (-)) as $ tail as
        func (x1 : x2 : xs)
          | x2 - x1 == diff = x2 : xs
          | otherwise = func (x2 : xs)
        results
          | n == 2 = as
          | otherwise = take n $ func $ as ++ as
    return $ mconcat (map (\x -> intDec x `mappend` charUtf8 ' ') results) `mappend` charUtf8 '\n'
  hPutBuilder stdout output

{-# LANGUAGE FlexibleContexts #-}
import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.IO
import Data.Array.Unboxed
import Data.Bits
import Data.Bool
import Data.Char
import Data.Int
import Data.List
import Data.Maybe
import Data.Ord
import Data.Ratio
import qualified Data.Set as Set
import qualified Data.Sequence as Seq
import System.IO
import System.IO.Unsafe

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

deb s e = unsafePerformIO $ do
    hPutStrLn stderr s
    return e

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

main = do
    tn <- parseInt <$> BS.getLine
    replicateM_ tn $ do
        n <- parseInt <$> BS.getLine
        xs <- sort . map parseInt . BS.words <$> BS.getLine
        let
            (_,i) = minimum (map (\(x,y,i) -> (y-x,i)) $ zip3 xs (drop 1 xs) [0..])
            (a,x0:x1:b) = splitAt i xs
            r = x0:b ++ a ++ [x1]
        putStrLn . unwords $ map show r

import Control.Monad
import Data.List
readInts = fmap (map read.words) getLine :: IO [Int]

toStr [] = ""
toStr (x:xs) = show x ++ " " ++ toStr xs

printResult = do
    n <- readLn :: IO Int
    h <- readInts
    let sh = sort h
        zh = zip (zipWith (-) (tail sh) sh) [0..]
        (_,i) = if n > 1 then minimum zh else (0,0)
        (a,b) = splitAt (i+1) sh
    putStrLn $ toStr $ b ++ a

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


Valera's lifelong ambition was to be a photographer, so he bought a new camera. Every day he got more and more clients asking for photos, and one day Valera needed a program that would determine the maximum number of people he can serve.The camera's memory is d megabytes. Valera's camera can take photos of high and low quality. One low quality photo takes a megabytes of memory, one high quality photo take b megabytes of memory. For unknown reasons, each client asks him to make several low quality photos and several high quality photos. More formally, the i-th client asks to make xi low quality photos and yi high quality photos.Valera wants to serve as many clients per day as possible, provided that they will be pleased with his work. To please the i-th client, Valera needs to give him everything he wants, that is, to make xi low quality photos and yi high quality photos. To make one low quality photo, the camera must have at least a megabytes of free memory space. Similarly, to make one high quality photo, the camera must have at least b megabytes of free memory space. Initially the camera's memory is empty. Valera also does not delete photos from the camera so that the camera's memory gradually fills up.Calculate the maximum number of clients Valera can successfully serve and print the numbers of these clients.

The first line contains two integers n and d (1 ≤ n ≤ 105, 1 ≤ d ≤ 109) — the number of clients and the camera memory size, correspondingly. The second line contains two integers a and b (1 ≤ a ≤ b ≤ 104) — the size of one low quality photo and of one high quality photo, correspondingly.  Next n lines describe the clients. The i-th line contains two integers xi and yi (0 ≤ xi, yi ≤ 105) — the number of low quality photos and high quality photos the i-th client wants, correspondingly.  All numbers on all lines are separated by single spaces.

On the first line print the answer to the problem — the maximum number of clients that Valera can successfully serve. Print on the second line the numbers of the client in any order. All numbers must be distinct. If there are multiple answers, print any of them. The clients are numbered starting with 1 in the order in which they are defined in the input data.

import Data.List

data Client = Client { size :: Integer,
					ident :: Integer
					}
					deriving(Eq,Ord)
instance Show Client where
	show (Client _s i) = show i

process ls hs  = flip go 1
	where
		go [] _ = []
		go (l:h:cs) n = Client (l*ls+h*hs) n : go cs (succ n)

serve mem = flip go 0
	where
		go [] _ = []
		go (c@(Client s _):xs) n
			| n+s<=mem = c:go xs (n+s)
			| otherwise = []

main = do
	s <- fmap words getContents
	let (_:mem:ls:hs:cs) = map read s
	let servedclients =serve mem $ sort $ process ls hs cs
	print $ length servedclients
	putStrLn $ unwords $ map show servedclients

import Char (isDigit, ord)
import Control.Monad (liftM)
import Data.List (sortBy)

--import CPUTime
--import IO (hPutStrLn, stderr)

{-
import HUnit

testInput :: Test
testInput  =  TestList "TestInput"
  [
    Test "1" $ assertEq (2, [2,3]) $ solve 3 10 2 3 [(1,4), (2,1), (1,0)],
    Test "2" $ assertEq (1, [2]) $ solve 3 6 6 6 [(1,1), (1,0), (1,0)]
  ]

testBigNumbers :: Test
testBigNumbers  =  Test "TestBigNumbers" $
    assertEq (1, [3]) $ solve 3 (10^9) (10^5) (10^5) [(10000, 10000), (10000, 0), (0,1)]

test :: IO ()
test  =  runs
  [
    testInput,
    testBigNumbers
  ]
-}

solve :: Int -> Int -> Int -> Int -> [(Int, Int)] -> (Int, [Int])
solve n d a b xs  =  solve' d (0, []) sorted
  where
    sorted  =  sortBy (\n1 n2 -> compare (snd n1) (snd n2)) $
        zipWith (\n (x, y) -> (n, a * x + b * y)) [1..] xs
    solve' _ acc []  =  acc
    solve' freeMemory (c, acc) ((n, memory) : xs)
      | freeMemory' >= 0  =  solve' freeMemory' (c + 1, n : acc) xs
      | otherwise  =  (c, acc)
      where
        freeMemory'  =  freeMemory - memory

readPair :: String -> (Int, Int)
readPair s  =  reads' 0 s
  where
    reads' a (' ':s)  =  reads'' a 0 (dropWhile (== ' ') s)
    reads' a (c:s)
      | isDigit c  =  reads' (10*a + ord c - ord '0') s
      | otherwise  =  error $ concat ["readPair: unknown symbol ", show c]
    reads'' a b []  =  (a, b)
    reads'' a b (c:s)
      | isDigit c  =  reads'' a (10*b + ord c - ord '0') s
      | otherwise  =  error $ concat ["readPair: unknown symbol ", show c]

printAns :: (Int, [Int]) -> IO ()
printAns (n, xs)  =  print n  >> printAns' xs
  where
    printAns' []  =  return ()
    printAns' [x]  =  print x
    printAns' (x:xs)  =  putStr (concat [show x, " "]) >> printAns' xs

main :: IO ()
main  =  do
--    timeStart  <-  getCPUTime

    lines'  <-  liftM lines getContents
    let (n, d)  =  (readPair . head) lines'
    let (a, b)  =  (readPair . (head . tail)) lines'
    let xs  =  (take n . map readPair . (tail . tail)) lines'
    printAns $ solve n d a b xs

--    timeEnd  <-  getCPUTime
--    hPutStrLn stderr $ concat ["Time = ", show $ fromIntegral (timeEnd - timeStart) / (10^12), " sec."]

{-# LANGUAGE BangPatterns #-}

import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Ord
import Control.Applicative

readInteger s = let Just (n,_) = B.readInteger s in n

main = do
  [_,d] <- map read.words <$> getLine
  [a,b] <- map read.words <$> getLine
  let toCosts [] = []
      toCosts (x:y:xys) = (a*x+b*y):toCosts xys
  costs <- zip[1..].toCosts.map readInteger.B.words <$> B.getContents
  let solve ans !total [] = do
        print $ length ans
        putStrLn $ unwords $ map show $  ans
      solve ans !total ((i,c):rest)
        | total+c<=d = solve (i:ans) (total+c) rest
        | otherwise = do
            print $ length ans
            putStrLn $ unwords $ map show $ ans
  solve [] 0 $ sortBy(comparing snd)costs

import Data.List

data Client = Client { size :: Int,
					ident :: Int
					}
					deriving(Eq,Ord)
instance Show Client where
	show (Client _s i) = show i

process ls hs  = flip go 1
	where
		go [] _ = []
		go (l:h:cs) n = Client (l*ls+h*hs) n : go cs (succ n)

serve mem = flip go 0
	where
		go [] _ = []
		go (c@(Client s _):xs) n
			| n+s<=mem = c:go xs (n+s)
			| otherwise = []

main = do
	s <- fmap words getContents
	let (_:mem:ls:hs:cs) = map read s
	let servedclients =serve mem $ sort $ process ls hs cs
	print $ length servedclients
	putStrLn $ unwords $ map show servedclients

{-# LANGUAGE BangPatterns #-}

import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Ord
import Control.Applicative

readInt s = let Just (n,_) = B.readInt s in n

main = do
  [_,d] <- map read.words <$> getLine
  [a,b] <- map read.words <$> getLine
  let toCosts [] = []
      toCosts (x:y:xys) = (a*x+b*y):toCosts xys
  costs <- zip[1..].toCosts.map readInt.B.words <$> B.getContents
  let solve !ans !total [] = do
        print $ length ans
        putStrLn $ unwords $ map show $  ans
      solve !ans !total ((i,c):rest)
        | total+c<=d = solve (i:ans) (total+c) rest
        | otherwise = do
          print $ length ans
          putStrLn $ unwords $ map show $ ans
  solve [] 0 $ sortBy(comparing snd)costs