Monocarp has got an array $$$a$$$ consisting of $$$n$$$ integers. Let's denote $$$k$$$ as the mathematic mean of these elements (note that it's possible that $$$k$$$ is not an integer). The mathematic mean of an array of $$$n$$$ elements is the sum of elements divided by the number of these elements (i. e. sum divided by $$$n$$$).Monocarp wants to delete exactly two elements from $$$a$$$ so that the mathematic mean of the remaining $$$(n - 2)$$$ elements is still equal to $$$k$$$.Your task is to calculate the number of pairs of positions $$$[i, j]$$$ ($$$i < j$$$) such that if the elements on these positions are deleted, the mathematic mean of $$$(n - 2)$$$ remaining elements is equal to $$$k$$$ (that is, it is equal to the mathematic mean of $$$n$$$ elements of the original array $$$a$$$).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array. The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the $$$i$$$-th element of the array. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

Print one integer — the number of pairs of positions $$$[i, j]$$$ ($$$i < j$$$) such that if the elements on these positions are deleted, the mathematic mean of $$$(n - 2)$$$ remaining elements is equal to $$$k$$$ (that is, it is equal to the mathematic mean of $$$n$$$ elements of the original array $$$a$$$).

NoteIn the first example, any pair of elements can be removed since all of them are equal.In the second example, there is no way to delete two elements so the mathematic mean doesn't change.In the third example, it is possible to delete the elements on positions $$$1$$$ and $$$3$$$, or the elements on positions $$$4$$$ and $$$5$$$.

{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B8
import qualified Data.ByteString.Builder as Bu
import Data.Functor.Identity
import Control.Monad.Trans.State
import Control.Monad
import Control.Applicative
import Control.Arrow
import Data.Function
import qualified Data.Bits as B
import qualified Data.Map.Lazy as M
import qualified Data.Set as S
import qualified Data.List as L

data Input = Input {n0 :: Int, xs0 :: [Int]}
data Output = Output Integer deriving Show

solve :: Input -> Output
solve (Input n xs) = if sumYs `mod` n /= 0 then Output 0 else Output ans where
  ys = map (*2) xs
  sumYs = sum ys
  avgYs = sumYs `div` n
  zs = L.sortBy (compare `on` abs) $ map (avgYs -) ys
  groupsss = map L.group $ map L.sort $ L.groupBy ((==) `on` abs) zs
  groupAns :: Eq a => Num a => [[a]] -> Integer    -- CF1598C
  groupAns [xs1]
    | head xs1 == 0 = m*(m-1)`div`2
    | otherwise = 0
    where m =  fromIntegral $ length xs1
  groupAns [negs,poss] = fromIntegral (length negs) * fromIntegral (length poss)
  groupAns _ = fromIntegral (-n*n)
  ans = sum $ map groupAns groupsss

-- gives a State(T) monad which when run gives Input
input :: StateT [B8.ByteString] Identity Input
input = do
  ~[n] <- getIntegrals 1
  ps <- (getIntegrals n)
  return $ Input n ps

output :: Output -> Bu.Builder
output = go where
  str = Bu.string7
  nl  = Bu.string7 "\n"
  sp  = Bu.string7 " "
  dec = Bu.intDec
  go (Output x) = Bu.integerDec x <> nl

numberOfTestcases :: St [Int]
numberOfTestcases = explicit
  where implicit = return [1] :: St [Int]
        explicit = getIntegrals 1

----------------------------- library -------------------------------
modp :: Integral t=>t->t
modp = (`mod` (10^9+7))

fastPow :: Integral t=>(t->t)->t->t->t
fastPow modf base' p' = go base' p' where
  go base 0 = base
  go base p = go (base`times`base) (p`div`2)  `times`  base^(p`mod`2)
  times = (modf.).(*)

primeFac :: Integral t=> t -> [(t,Int)]
primeFac  = map (\xs-> (head xs,length xs)).L.group.tryDiv 2 where
  tryDiv d n
    | n `mod` d == 0 = d : tryDiv d (n `div` d)
    | n == 1 = []
    | d*d < n = tryDiv (d+1+d`mod`2) n
    | otherwise = tryDiv n n

umakeset xs = (M.fromList (zip xs xs), M.fromList (zip xs (repeat 0)))
ufind uf@(parents,ranks) x = if parents M.! x == x then x else ufind uf (parents M.! x)
uunion uf@(parents, ranks) x y = if fx==fy then (False,uf) else (True, (parents1, ranks1)) where
  (fx, fy) = (ufind uf x, ufind uf y)
  [(r0,f0), (r1,f1)] = L.sort [(ranks M.! fx, fx), (ranks M.! fy, fy)]
  parents1 = M.insert f0 f1 parents
  ranks1 = if r0 /= r1 then ranks else M.insert f1 (r1+1) ranks

------------------------------- main --------------------------------
type St = StateT [B8.ByteString] Identity

doTestcase :: St Bu.Builder
doTestcase = input >>= (solve >>> output >>> return)

getNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])
getNext [] =  (B8.take 0 (B8.pack "."),[])
getNext (w:ws) =  (w,ws)

getIntegral :: Num t => B8.ByteString -> t
getIntegral x =  fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x

getIntegrals :: Num t => Int -> St [t]
getIntegrals n = replicateM n $ getIntegral <$> state getNext

main :: IO ()
main = do
  raw <- B8.getContents
  let bytestrings = B8.words raw
  let outputs = flip evalState bytestrings $ do
        ~[nTc] <- numberOfTestcases
        let answers = replicateM nTc doTestcase
        fmap mconcat answers
  B8.putStr $ Bu.toLazyByteString outputs

{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B8
import qualified Data.ByteString.Builder as Bu
import Data.Functor.Identity
import Control.Monad.Trans.State
import Control.Monad
import Control.Applicative
import Control.Arrow
import Data.Function
import qualified Data.Bits as B
import qualified Data.Map.Lazy as M
import qualified Data.Set as S
import qualified Data.List as L
--import Debug.Trace

data Input = Input {n0 :: Int, xs0 :: [Int]}
data Output = Output Integer deriving Show

solve :: Input -> Output
solve (Input n xs) = if sumYs `mod` n /= 0 then Output 0 else Output ans where
  ys = map (*2) xs
  sumYs = sum ys
  avgYs = sumYs `div` n
  zs = L.sortBy (compare `on` abs) $ map (avgYs -) ys
  -- [0,0,0,0] [[0,0,0,0]]  [ [[0,0,0,0]] ]
  -- [ [[0,0,0,0]] ]
  -- groupAns
  groupsss = map L.group $ L.groupBy ((==) `on` abs) zs -- [[[],[] ],[],[]]
  groupAns :: Eq a => Num a => [[a]] -> Integer    -- CF1598C
  groupAns [xs1]
    | head xs1 == 0 = m*(m-1)`div`2
    | otherwise = 0
    where m =  fromIntegral $ length xs1
  groupAns [negs,poss] = fromIntegral (length negs) * fromIntegral (length poss)
  groupAns _ = fromIntegral (-n*n)
  ans = sum $ map groupAns groupsss

-- gives a State(T) monad which when run gives Input
input :: StateT [B8.ByteString] Identity Input
input = do
  ~[n] <- getIntegrals 1
  ps <- (getIntegrals n)
  return $ Input n ps

output :: Output -> Bu.Builder
output = go where
  str = Bu.string7
  nl  = Bu.string7 "\n"
  sp  = Bu.string7 " "
  dec = Bu.intDec
  go (Output x) = Bu.integerDec x <> nl

numberOfTestcases :: St [Int]
numberOfTestcases = explicit
  where implicit = return [1] :: St [Int]
        explicit = getIntegrals 1

----------------------------- library -------------------------------
modp :: Integral t=>t->t
modp = (`mod` (10^9+7))

fastPow :: Integral t=>(t->t)->t->t->t
fastPow modf base' p' = go base' p' where
  go base 0 = base
  go base p = go (base`times`base) (p`div`2)  `times`  base^(p`mod`2)
  times = (modf.).(*)

primeFac :: Integral t=> t -> [(t,Int)]
primeFac  = map (\xs-> (head xs,length xs)).L.group.tryDiv 2 where
  tryDiv d n
    | n `mod` d == 0 = d : tryDiv d (n `div` d)
    | n == 1 = []
    | d*d < n = tryDiv (d+1+d`mod`2) n
    | otherwise = tryDiv n n

umakeset xs = (M.fromList (zip xs xs), M.fromList (zip xs (repeat 0)))
ufind uf@(parents,ranks) x = if parents M.! x == x then x else ufind uf (parents M.! x)
uunion uf@(parents, ranks) x y = if fx==fy then (False,uf) else (True, (parents1, ranks1)) where
  (fx, fy) = (ufind uf x, ufind uf y)
  [(r0,f0), (r1,f1)] = L.sort [(ranks M.! fx, fx), (ranks M.! fy, fy)]
  parents1 = M.insert f0 f1 parents
  ranks1 = if r0 /= r1 then ranks else M.insert f1 (r1+1) ranks

------------------------------- main --------------------------------
type St = StateT [B8.ByteString] Identity

doTestcase :: St Bu.Builder
doTestcase = input >>= (solve >>> output >>> return)

getNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])
getNext [] =  (B8.take 0 (B8.pack "."),[])
getNext (w:ws) =  (w,ws)

getIntegral :: Num t => B8.ByteString -> t
getIntegral x =  fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x

getIntegrals :: Num t => Int -> St [t]
getIntegrals n = replicateM n $ getIntegral <$> state getNext

main :: IO ()
main = do
  raw <- B8.getContents
  let bytestrings = B8.words raw
  let outputs = flip evalState bytestrings $ do
        ~[nTc] <- numberOfTestcases
        let answers = replicateM nTc doTestcase
        fmap mconcat answers
  B8.putStr $ Bu.toLazyByteString outputs


You have a string $$$s$$$ and a chip, which you can place onto any character of this string. After placing the chip, you move it to the right several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is $$$i$$$, you move it to the position $$$i + 1$$$. Of course, moving the chip to the right is impossible if it is already in the last position.After moving the chip to the right, you move it to the left several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is $$$i$$$, you move it to the position $$$i - 1$$$. Of course, moving the chip to the left is impossible if it is already in the first position.When you place a chip or move it, you write down the character where the chip ends up after your action. For example, if $$$s$$$ is abcdef, you place the chip onto the $$$3$$$-rd character, move it to the right $$$2$$$ times and then move it to the left $$$3$$$ times, you write down the string cdedcb.You are given two strings $$$s$$$ and $$$t$$$. Your task is to determine whether it's possible to perform the described operations with $$$s$$$ so that you write down the string $$$t$$$ as a result.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of test cases. Each test case consists of two lines. The first line contains the string $$$s$$$ ($$$1 \le |s| \le 500$$$), the second line contains the string $$$t$$$ ($$$1 \le |t| \le 2 \cdot |s| - 1$$$). Both strings consist of lowercase English characters. It is guaranteed that the sum of $$$|s|$$$ over all test cases does not exceed $$$500$$$.

For each test case, print "YES" if you can obtain the string $$$t$$$ by performing the process mentioned in the statement with the string $$$s$$$, or "NO" if you cannot. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).

6
abcdef
cdedcb
aaa
aaaaa
aab
baaa
ab
b
abcdef
abcdef
ba
baa

NoteConsider the examples.The first test case is described in the statement.In the second test case, you can place the chip on the $$$1$$$-st position, move it twice to the right, and then move it twice to the left.In the fourth test case, you can place the chip on the $$$2$$$-nd position, and then don't move it at all.In the fifth test case, you can place the chip on the $$$1$$$-st position, move it $$$5$$$ times to the right, and then finish the process.

import Control.Monad (replicateM_)
import Data.List (inits, tails, isPrefixOf)

allPaths :: String -> [String]
allPaths s = [suffs ++ drop 1 (reverse prefs) |
  prefs <- inits s,
  suffs <- tails prefs
  ]

main :: IO ()
main = do
  q <- readLn
  replicateM_ q $ do
    s <- getLine
    t <- getLine
    let paths = allPaths s
    putStrLn $ if any (t `isPrefixOf`) paths
      then "YES" else "NO"

import Control.Arrow ((>>>))
import Data.Bool (bool)
import Data.List (tails, inits)

main :: IO ()
main =
  interact $
    words
      >>> drop 1
      >>> chunksOf 2
      >>> map (solve >>> bool "No" "Yes")
      >>> unlines

solve :: [String] -> Bool
solve [s, t] = t `elem` concatMap (map (take n) . tails) [p ++ tail (reverse p) | p <- inits s, not . null $ p]
  where
    n = length t

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

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

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

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [q] <- readInts
  replicateM_ q $ do
    s <- P.unpack <$> readLine
    t <- P.unpack <$> readLine
    let  opts = [v ++ drop 1 (reverse si) | si <- inits s, v <- tails si]
    lift $ B.hPutBuilder stdout $ if  any (t `isPrefixOf`) opts
      then  B.string7 "YES\n"
      else  B.string7 "NO\n"

type SIO = StateT P.ByteString IO

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

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

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


There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 < x_i < m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 < x_i < m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.

For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.

NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase:   Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.

import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST
import Data.Array.ST
import Data.Array.Unboxed
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, Char, Int)] -> [(Int, Int)]
solve n uws =
    let
        ws = sort uws
    in
        go ws []
    where
        go :: [(Int, Char, Int)] -> [(Int, Int)] -> [(Int, Int)]
        go [] [] = []
        go [] [_] = []
        go [] ((x,i):(y,j):ss) =
            let
                k = (2*n-x-y) `div` 2
            in
                (k,i) : (k,j) : go [] ss
        go ((x, d, i):ws) ss
            | d == 'R' = go ws ((x,i):ss)
            | d == 'L' =
                case ss of
                    [] ->
                        go ws ((-x,i):ss)
                    ((y,j):ss) ->
                        let
                            k = (x-y) `div` 2
                        in
                            (k,i) : (k,j) : go ws ss

main = do
    tn <- parseInt <$> BS.getLine
    replicateM_ tn $ do
        [m, n] <- map parseInt . BS.words <$> BS.getLine
        xs <- map parseInt . BS.words <$> BS.getLine
        ds <- map BS.head . BS.words <$> BS.getLine
        let w = zip3 xs ds [0::Int ..]
            (w0, w1) = partition (\(x,_,_) -> even x) w
            r0 = solve n w0
            r1 = solve n w1
            r = elems $ runSTUArray $ do
                ra <- newArray (0, m-1) (-1)
                forM_ (r0 ++ r1) (\(x, i) -> writeArray ra i x)
                return ra
        putStrLn . unwords . map show $ r

import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST
import Data.Array.ST
import Data.Array.Unboxed
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, Char, Int)] -> [(Int, Int)]
solve n uws =
    let
        ws = sort uws
    in
        go ws []
    where
        go :: [(Int, Char, Int)] -> [(Int, Int)] -> [(Int, Int)]
        go [] [] = []
        go [] [_] = []
        go [] ((x,i):(y,j):ss) =
            let
                k = (2*n-x-y) `div` 2
            in
                (k,i) : (k,j) : go [] ss
        go ((x, d, i):ws) ss
            | d == 'R' = go ws ((x,i):ss)
            | d == 'L' =
                case ss of
                    [] ->
                        go ws ((-x,i):ss)
                    ((y,j):ss) ->
                        let
                            k = (x-y) `div` 2
                        in
                            (k,i) : (k,j) : go ws ss

main = do
    tn <- parseInt <$> BS.getLine
    forM_ [1..tn] (\_ -> do
        [m, n] <- map parseInt . BS.words <$> BS.getLine
        xs <- map parseInt . BS.words <$> BS.getLine
        ds <- map BS.head . BS.words <$> BS.getLine
        let w = zip3 xs ds [0::Int ..]
            (w0, w1) = partition (\(x,_,_) -> even x) w
            r0 = solve n w0
            r1 = solve n w1
            r = elems $ runSTUArray $ do
                ra <- newArray (0, m-1) (-1)
                forM_ (r0 ++ r1) (\(x, i) -> writeArray ra i x)
                return ra
        putStrLn . unwords . map show $ r
     )

    import qualified Data.ByteString.Char8 as BS
    import Control.Monad
    import Data.Array.IO
    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, Char, Int)] -> [(Int, Int)]
    solve n uws =
        let
            ws = sort uws
        in
            go ws []
        where
            go :: [(Int, Char, Int)] -> [(Int, Int)] -> [(Int, Int)]
            go [] [] = []
            go [] [_] = []
            go [] ((x,i):(y,j):ss) =
                let
                    k = (2*n-x-y) `div` 2
                in
                    (k,i) : (k,j) : go [] ss
            go ((x, d, i):ws) ss
                | d == 'R' = go ws ((x,i):ss)
                | d == 'L' =
                    case ss of
                        [] ->
                            go ws ((-x,i):ss)
                        ((y,j):ss) ->
                            let
                                k = (x-y) `div` 2
                            in
                                (k,i) : (k,j) : go ws ss

    main = do
        tn <- parseInt <$> BS.getLine
        forM_ [1..tn] (\_ -> do
            [m, n] <- map parseInt . BS.words <$> BS.getLine
            xs <- map parseInt . BS.words <$> BS.getLine
            ds <- map BS.head . BS.words <$> BS.getLine
            let w = zip3 xs ds [0::Int ..]
                (w0, w1) = partition (\(x,_,_) -> even x) w
                r0 = solve n w0
                r1 = solve n w1
            r <- newArray (0, m-1) (-1) :: IO (IOUArray Int Int)
            forM_ (r0 ++ r1) (\(x, i) -> writeArray r i x)

            putStrLn . unwords . map show =<< getElems r
         )

import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Data.Array.IO
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, Char, Int)] -> [(Int, Int)]
solve n uws =
    let
        ws = sort uws
    in
        go ws []
    where
        go :: [(Int, Char, Int)] -> [(Int, Int)] -> [(Int, Int)]
        go [] [] = []
        go [] [_] = []
        go [] ((x,i):(y,j):ss) =
            let
                k = (2*n-x-y) `div` 2
            in
                (k,i) : (k,j) : go [] ss
        go ((x, d, i):ws) ss
            | d == 'R' = go ws ((x,i):ss)
            | d == 'L' =
                case ss of
                    [] ->
                        go ws ((-x,i):ss)
                    ((y,j):ss) ->
                        let
                            k = (x-y) `div` 2
                        in
                            (k,i) : (k,j) : go ws ss

main = do
    tn <- parseInt <$> BS.getLine
    forM_ [1..tn] (\_ -> do
        [m, n] <- map parseInt . BS.words <$> BS.getLine
        xs <- map parseInt . BS.words <$> BS.getLine
        ds <- map BS.head . BS.words <$> BS.getLine
        let w = zip3 xs ds [0::Int ..]
            (w0, w1) = partition (\(x,_,_) -> even x) w
            r0 = solve n w0
            r1 = solve n w1
        r <- newArray (0, m-1) (-1) :: IO (IOArray Int Int)
        forM_ (r0 ++ r1) (\(x, i) -> writeArray r i x)

        putStrLn . unwords . map show =<< getElems r
     )


You are given $$$n$$$ rectangles on a plane with coordinates of their bottom left and upper right points. Some $$$(n-1)$$$ of the given $$$n$$$ rectangles have some common point. A point belongs to a rectangle if this point is strictly inside the rectangle or belongs to its boundary.Find any point with integer coordinates that belongs to at least $$$(n-1)$$$ given rectangles.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 132\,674$$$) — the number of given rectangles. Each the next $$$n$$$ lines contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ ($$$-10^9 \le x_1 < x_2 \le 10^9$$$, $$$-10^9 \le y_1 < y_2 \le 10^9$$$) — the coordinates of the bottom left and upper right corners of a rectangle.

Print two integers $$$x$$$ and $$$y$$$ — the coordinates of any point that belongs to at least $$$(n-1)$$$ given rectangles.

NoteThe picture below shows the rectangles in the first and second samples. The possible answers are highlighted.  The picture below shows the rectangles in the third and fourth samples.

--import Debug.Trace
import qualified Data.ByteString.Char8 as B
import Control.Applicative
import Control.Arrow
import Control.Monad
import Data.List
import Data.Maybe

mx = 2000000000
mn = negate mx
large = [mn,mn,mx,mx]

main = do
  n <- lineInt
  rects <- replicateM n lineInts :: IO [[Int]]
  let pre = scanl int large rects
      suf = scanr int large rects
      both = zipWith int (large:pre) (suf ++ [large])
      ans = snd $ head $ filter (snd . second nempt) $ zip [1..] both
  putStrLn $ unwords $ map show $ take 2 ans

int a b = zipWith uncurry [max, max, min, min] $  zip a b
nempt [x1,y1,x2,y2] = x1 <= x2 && y1 <= y2

readInt = fst . fromJust . B.readInt
lineInt = readInt <$> B.getLine
lineInts = map readInt . B.words <$> B.getLine

--infixr 0 ##
--(##) x msg = traceShow msg x


Let's call a list of positive integers $$$a_0, a_1, ..., a_{n-1}$$$ a power sequence if there is a positive integer $$$c$$$, so that for every $$$0 \le i \le n-1$$$ then $$$a_i = c^i$$$.Given a list of $$$n$$$ positive integers $$$a_0, a_1, ..., a_{n-1}$$$, you are allowed to:  Reorder the list (i.e. pick a permutation $$$p$$$ of $$$\{0,1,...,n - 1\}$$$ and change $$$a_i$$$ to $$$a_{p_i}$$$), then  Do the following operation any number of times: pick an index $$$i$$$ and change $$$a_i$$$ to $$$a_i - 1$$$ or $$$a_i + 1$$$ (i.e. increment or decrement $$$a_i$$$ by $$$1$$$) with a cost of $$$1$$$. Find the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence.

The first line contains an integer $$$n$$$ ($$$3 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_0, a_1, ..., a_{n-1}$$$ ($$$1 \le a_i \le 10^9$$$).

Print the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence.

NoteIn the first example, we first reorder $$$\{1, 3, 2\}$$$ into $$$\{1, 2, 3\}$$$, then increment $$$a_2$$$ to $$$4$$$ with cost $$$1$$$ to get a power sequence $$$\{1, 2, 4\}$$$.

{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}
import Data.List

main = do
  getLine
  as <- sort . map read . words <$> getLine :: IO [Integer]
  print $ minimum $
    takeWhile
      (<= sum as)
      [ sum $ abs <$> zipWith (-) as (iterate (* c) 1)
        | c <- [1 ..]
      ]

import Data.List ( sort, foldl' )

cost :: [Integer] -> Integer -> (Integer, Integer)
cost li c = let
  inp = zip li $ iterate (* c) 1
  fun (p, q) (val, tar) = let
    diff = tar - val
    in  seq p $ seq q $ (p + max 0 diff, q - min 0 diff)
  in  foldl' fun (0, 0) inp

-- no need to special-case n=1 or n=2 for performance reasons since n>=3
solve :: [Integer] -> Integer
solve li = let
  sli = sort li
  (c1, c2) = cost sli 1
  fun x k = let
    (p, q) = cost sli k
    in  if  x < p  then  x  else  fun (min x $ p + q) (k+1)
  in  fun (c1 + c2) 2

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

import Data.List ( sort, foldl' )

cost :: [Integer] -> Integer -> (Integer, Integer)
cost li c = let
  inp = zip li $ iterate (* c) 1
  fun (p, q) (val, tar) = let
    diff = tar - val
    in  seq p $ seq q $ (p + max 0 diff, q - min 0 diff)
  in  foldl' fun (0, 0) inp

-- no need to special-case n=1 or n=2 for performance reasons since n>=3
solve :: [Integer] -> Integer
solve li = let
  sli = sort li
  (c1, c2) = cost sli 1
  fun x k = let
    (p, q) = cost li k
    in  if  x < p  then  x  else  fun (min x $ p + q) (k+1)
  in  fun (c1 + c2) 2

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


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers.Initially, you have an integer $$$x = 0$$$. During one move, you can do one of the following two operations:  Choose exactly one $$$i$$$ from $$$1$$$ to $$$n$$$ and increase $$$a_i$$$ by $$$x$$$ ($$$a_i := a_i + x$$$), then increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$).  Just increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$). The first operation can be applied no more than once to each $$$i$$$ from $$$1$$$ to $$$n$$$.Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by $$$k$$$ (the value $$$k$$$ is given).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5; 1 \le k \le 10^9$$$) — the length of $$$a$$$ and the required divisior. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the minimum number of moves required to obtain such an array that each its element is divisible by $$$k$$$.

NoteConsider the first test case of the example:  $$$x=0$$$, $$$a = [1, 2, 1, 3]$$$. Just increase $$$x$$$;  $$$x=1$$$, $$$a = [1, 2, 1, 3]$$$. Add $$$x$$$ to the second element and increase $$$x$$$;  $$$x=2$$$, $$$a = [1, 3, 1, 3]$$$. Add $$$x$$$ to the third element and increase $$$x$$$;  $$$x=3$$$, $$$a = [1, 3, 3, 3]$$$. Add $$$x$$$ to the fourth element and increase $$$x$$$;  $$$x=4$$$, $$$a = [1, 3, 3, 6]$$$. Just increase $$$x$$$;  $$$x=5$$$, $$$a = [1, 3, 3, 6]$$$. Add $$$x$$$ to the first element and increase $$$x$$$;  $$$x=6$$$, $$$a = [6, 3, 3, 6]$$$. We obtained the required array. Note that you can't add $$$x$$$ to the same element more than once.

import Control.Monad
import Data.IntMap
import Data.List
import Data.Tuple

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [_,k] <- fmap read . words <$> getLine
    a <- fmap swap . toList . fromListWith (+) . fmap (\x -> (x,1)) . mfilter ((/=) 0) . fmap (\x -> mod (k - mod x k) k) . fmap read . words <$> getLine
    print $ if a == [] then 0 else let (c,m) = maximum a in (fromIntegral c - 1) * fromIntegral k + fromIntegral m + 1

import Control.Monad
import Data.List

main = do
    p <- read <$> getLine :: IO Int
    replicateM_ p solveCase
solveCase = do
    [n,k] <- fmap read . words <$> getLine :: IO [Integer]
    as <- fmap read . words <$> getLine :: IO [Integer]
    solveCaseP k as
solveCaseP k as = let as' = fmap (\a -> k - a)
                          . dropWhile (== 0)
                          . sort
                          $ fmap (\a -> a `mod` k) as
                      (b,c) = if null as' then (1,-1) else findPlurality as'
                  in print $ k*(b-1)+(c+1)

findPlurality as = (\a -> (fromIntegral (length a), head a))
                   . foldl1' (\a b -> if length a >= length b then a else b)
                   $ group as

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List

main :: IO ()
main =  interact $  lines >>> drop 1 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (nk : l : rest) = itoline (solve (last $ linetois nk) (linetois l)) : tcio rest
  linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois
  itoline = show; istoline = unwords . (map itoline); isstolines = map istoline

solve :: Int -> [Int] -> Integer
solve k as  =  1 + toInteger m + toInteger k * (toInteger mc - 1) where
  (mc,m) = if null l then (1,-1) else maximum l
  l = [(length t, head t)  | t <- group $ sort $ [(k - (a `mod` k)) `mod` k | a <- as, a `mod` k /= 0]]

import Control.Monad
import Data.IntMap
import Data.List
import Data.Tuple

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [n,k] <- fmap read . words <$> getLine
    a <- fmap swap . toList . fromListWith (+) . fmap (\x -> (x,1)) . mfilter ((/=) 0) . fmap (\x -> mod (k - mod x k) k) . fmap read . words <$> getLine
    print $ if a == [] then 0 else let (c,m) = maximum a in (fromIntegral c - 1) * k + fromIntegral m + 1

import Control.Monad
import Data.IntMap
import Data.List
import Data.Tuple

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [n,k] <- fmap read . words <$> getLine
    a <- fmap swap . toList . fromListWith (+) . fmap (\x -> (x,1)) . mfilter ((/=) 0) . fmap (\x -> mod (k - mod x k) k) . fmap read . words <$> getLine
    print $ if a == [] then 0 else let (c,m) = maximum a in (c - 1) * k + m + 1

import Control.Monad
import Data.IntMap
import Data.List
import Data.Tuple

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [n,k] <- fmap read . words <$> getLine
    (c,m) <- maximum . fmap swap . toList . fromListWith (+) . fmap (\x -> (mod (k - mod x k) k,1)) . fmap read . words <$> getLine
    print $ (c - 1) * k + m + 1

import Control.Monad
import Data.List

main = do
    p <- read <$> getLine :: IO Int
    replicateM_ p solveCase
solveCase = do
    [n,k] <- fmap read . words <$> getLine :: IO [Int]
    as <- fmap read . words <$> getLine :: IO [Int]
    solveCaseP n k as
solveCaseP n k as = let as' = fmap (\a -> k - a)
                            . dropWhile (== 0)
                            . sort
                            $ fmap (\a -> a `mod` k) as
                        (b,c) = if null as' then (1,-1) else findPlurality as'
                    in print $ k*(b-1)+(c+1)

findPlurality as = (\a -> (length a, head a))
                   . foldl1' (\a b -> if length a >= length b then a else b)
                   $ group as

import Control.Monad
import Data.List

main = do
    p <- read <$> getLine :: IO Int
    print p
    replicateM_ p solveCase
solveCase = do
    [n,k] <- fmap read . words <$> getLine :: IO [Int]
    as <- fmap read . words <$> getLine :: IO [Int]
    solveCaseP n k as
solveCaseP n k as = let as' = fmap (\a -> k - a)
                            . dropWhile (== 0)
                            . sort
                            $ fmap (\a -> a `mod` k) as
                        (b,c) = if null as' then (1,-1) else findPlurality as'
                    in print $ k*(b-1)+(c+1)

findPlurality as = (\a -> (length a, head a))
                   . foldl1' (\a b -> if length a >= length b then a else b)
                   $ group as

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List

main :: IO ()
main =  interact $  lines >>> drop 1 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (nk : l : rest) = itoline (solve (last $ linetois nk) (linetois l)) : tcio rest
  linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois
  itoline = show; istoline = unwords . (map itoline); isstolines = map istoline

solve :: Int -> [Int] -> Int
solve k as  =  1 + m + k * (mc - 1) where
  (mc,m) = if null l then (1,-1) else maximum l
  l = [(length t, head t)  | t <- group $ sort $ [(k - (a `mod` k)) `mod` k | a <- as, a `mod` k /= 0]]


The Central Company has an office with a sophisticated security system. There are $$$10^6$$$ employees, numbered from $$$1$$$ to $$$10^6$$$.The security system logs entrances and departures. The entrance of the $$$i$$$-th employee is denoted by the integer $$$i$$$, while the departure of the $$$i$$$-th employee is denoted by the integer $$$-i$$$.The company has some strict rules about access to its office:  An employee can enter the office at most once per day.  He obviously can't leave the office if he didn't enter it earlier that day.  In the beginning and at the end of every day, the office is empty (employees can't stay at night). It may also be empty at any moment of the day. Any array of events satisfying these conditions is called a valid day.Some examples of valid or invalid days:  $$$[1, 7, -7, 3, -1, -3]$$$ is a valid day ($$$1$$$ enters, $$$7$$$ enters, $$$7$$$ leaves, $$$3$$$ enters, $$$1$$$ leaves, $$$3$$$ leaves).  $$$[2, -2, 3, -3]$$$ is also a valid day.  $$$[2, 5, -5, 5, -5, -2]$$$ is not a valid day, because $$$5$$$ entered the office twice during the same day.  $$$[-4, 4]$$$ is not a valid day, because $$$4$$$ left the office without being in it.  $$$[4]$$$ is not a valid day, because $$$4$$$ entered the office and didn't leave it before the end of the day. There are $$$n$$$ events $$$a_1, a_2, \ldots, a_n$$$, in the order they occurred. This array corresponds to one or more consecutive days. The system administrator erased the dates of events by mistake, but he didn't change the order of the events.You must partition (to cut) the array $$$a$$$ of events into contiguous subarrays, which must represent non-empty valid days (or say that it's impossible). Each array element should belong to exactly one contiguous subarray of a partition. Each contiguous subarray of a partition should be a valid day.For example, if $$$n=8$$$ and $$$a=[1, -1, 1, 2, -1, -2, 3, -3]$$$ then he can partition it into two contiguous subarrays which are valid days: $$$a = [1, -1~ \boldsymbol{|}~ 1, 2, -1, -2, 3, -3]$$$.Help the administrator to partition the given array $$$a$$$ in the required way or report that it is impossible to do. Find any required partition, you should not minimize or maximize the number of parts.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$ and $$$a_i \neq 0$$$).

If there is no valid partition, print $$$-1$$$. Otherwise, print any valid partition in the following format:   On the first line print the number $$$d$$$ of days ($$$1 \le d \le n$$$).  On the second line, print $$$d$$$ integers $$$c_1, c_2, \ldots, c_d$$$ ($$$1 \le c_i \le n$$$ and $$$c_1 + c_2 + \ldots + c_d = n$$$), where $$$c_i$$$ is the number of events in the $$$i$$$-th day.  If there are many valid solutions, you can print any of them. You don't have to minimize nor maximize the number of days.

NoteIn the first example, the whole array is a valid day.In the second example, one possible valid solution is to split the array into $$$[1, -1]$$$ and $$$[1, 2, -1, -2, 3, -3]$$$ ($$$d = 2$$$ and $$$c = [2, 6]$$$). The only other valid solution would be to split the array into $$$[1, -1]$$$, $$$[1, 2, -1, -2]$$$ and $$$[3, -3]$$$ ($$$d = 3$$$ and $$$c = [2, 4, 2]$$$). Both solutions are accepted.In the third and fourth examples, we can prove that there exists no valid solution. Please note that the array given in input is not guaranteed to represent a coherent set of events.

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

main :: IO ()
main = do
  _ <- getLine -- n
  a <- map read . words <$> getLine
  case solve a of
    Nothing -> print (-1)
    Just d -> print (length d) >> putStr (unwords $ map show d)

solve :: [Int] -> Maybe [Int]
solve d = (\(s, c) -> if Set.findMax s < 0 then Just $ map (*2) $ reverse (Set.size s : c) else Nothing) =<< foldl' fn (Just (Set.empty, [])) d
  where fn Nothing _ = Nothing
        fn (Just (s,c)) e
          | e < 0 && entered e = Just (mkNeg e s, c)
          | e < 0 = Nothing
          | e > 0 && Set.null s = Just (Set.singleton e, c)
          | e > 0 && unknown e && Set.findMax s > 0 = Just (Set.insert e s, c)
          | e > 0 && unknown e && Set.findMax s < 0 = Just (Set.singleton e, Set.size s : c)
          | e > 0 && exited  e && Set.findMax s < 0 = Just (Set.singleton e, Set.size s : c)
          | e > 0 && exited  e && Set.findMax s > 0 = Nothing
          | e > 0 && entered e = Nothing
          where entered = flip Set.member s . abs
                exited  = flip Set.member s . negate . abs
                unknown x = Set.notMember x s && Set.notMember (-x) s
        mkNeg e = Set.insert e . Set.delete (-e)

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

main :: IO ()
main = do
  _ <- getLine -- n
  a <- map read . words <$> getLine
  case solve a of
    Nothing -> print (-1)
    Just d -> print (length d) >> putStr (intersperse ' ' $ concatMap show d)

solve :: [Int] -> Maybe [Int]
solve d = (\(s, c) -> if Set.findMax s < 0 then Just $ map (*2) $ reverse (Set.size s : c) else Nothing) =<< foldl' fn (Just (Set.empty, [])) d
  where fn Nothing _ = Nothing
        fn (Just (s,c)) e
          | e < 0 && entered e = Just (mkNeg e s, c)
          | e < 0 && exited  e = Nothing
          | e < 0 && unknown e = Nothing
          | e > 0 && unknown e = Just (Set.insert e s, c)
          | e > 0 && exited  e && Set.findMax s < 0 = Just (Set.singleton e, Set.size s : c)
          | e > 0 && exited  e && Set.findMax s > 0 = Nothing
          where entered = flip Set.member s . abs
                exited  = flip Set.member s . negate . abs
                unknown x = Set.notMember x s && Set.notMember (-x) s
        mkNeg e = Set.insert e . Set.delete (-e)

import Data.List
import qualified Data.Set as Set

main :: IO ()
main = do
  _ <- getLine -- n
  a <- map read . words <$> getLine
  case solve a of
    Nothing -> print (-1)
    Just d -> print (length d) >> putStr (intersperse ' ' $ concatMap show d)

solve :: [Int] -> Maybe [Int]
solve d = (\(s, c) -> map (*2) $ reverse (Set.size s : c)) <$> foldl' fn (Just (Set.empty, [])) d
  where fn Nothing _ = Nothing
        fn (Just (s,c)) e
          | e < 0 && entered e = Just (mkNeg e s, c)
          | e < 0 && exited  e = Nothing
          | e < 0 && unknown e = Nothing
          | e > 0 && unknown e = Just (Set.insert e s, c)
          | e > 0 && exited  e && Set.findMax s < 0 = Just (Set.singleton e, Set.size s : c)
          | e > 0 && exited  e && Set.findMax s > 0 = Nothing
          where entered = flip Set.member s . abs
                exited  = flip Set.member s . negate . abs
                unknown x = Set.notMember x s && Set.notMember (-x) s
        mkNeg e = Set.insert e . Set.delete (-e)

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

main :: IO ()
main = do
  _ <- getLine -- n
  a <- map read . words <$> getLine
  case solve a of
    Nothing -> print (-1)
    Just d -> print (length d) >> putStr (unwords $ map show d)

solve :: [Int] -> Maybe [Int]
solve d = (\(s, c) -> if Set.findMax s < 0 then Just $ map (*2) $ reverse (Set.size s : c) else Nothing) =<< foldl' fn (Just (Set.empty, [])) d
  where fn Nothing _ = Nothing
        fn (Just (s,c)) e
          | e < 0 && entered e = Just (mkNeg e s, c)
          | e < 0 && exited  e = Nothing
          | e < 0 && unknown e = Nothing
          | e > 0 && unknown e = Just (Set.insert e s, c)
          | e > 0 && exited  e && Set.findMax s < 0 = Just (Set.singleton e, Set.size s : c)
          | e > 0 && exited  e && Set.findMax s > 0 = Nothing
          where entered = flip Set.member s . abs
                exited  = flip Set.member s . negate . abs
                unknown x = Set.notMember x s && Set.notMember (-x) s
        mkNeg e = Set.insert e . Set.delete (-e)


Bob has a string $$$s$$$ consisting of lowercase English letters. He defines $$$s'$$$ to be the string after removing all "a" characters from $$$s$$$ (keeping all other characters in the same order). He then generates a new string $$$t$$$ by concatenating $$$s$$$ and $$$s'$$$. In other words, $$$t=s+s'$$$ (look at notes for an example).You are given a string $$$t$$$. Your task is to find some $$$s$$$ that Bob could have used to generate $$$t$$$. It can be shown that if an answer exists, it will be unique.

The first line of input contains a string $$$t$$$ ($$$1 \leq |t| \leq 10^5$$$) consisting of lowercase English letters.

Print a string $$$s$$$ that could have generated $$$t$$$. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters).

NoteIn the first example, we have $$$s = $$$ "aaaaa", and $$$s' = $$$ "".In the second example, no such $$$s$$$ can work that will generate the given $$$t$$$.In the third example, we have $$$s = $$$ "ababacac", and $$$s' = $$$ "bbcc", and $$$t = s + s' = $$$ "ababacacbbcc".

-- code_report Solution
-- Video Link:
-- Problem Link: https://www.codechef.com/APRIL19B/problems/STRCH/

import Control.Monad

splitInHalf xs = splitAt (div (length xs) 2) xs

solve :: String -> String
solve s
    | all (=='a') s = s
    | a == b && (length end) >= (length b) = reverse $ drop (length a) $ reverse s
    | otherwise = ":("
    where end = takeWhile (/='a') $ reverse s
          (a, b) = splitInHalf $ filter (/='a') s

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

-- code_report Solution
-- Video Link:
-- Problem Link: https://www.codechef.com/APRIL19B/problems/STRCH/

import Control.Monad

splitInHalf xs = splitAt (div (length xs) 2) xs

solve :: String -> String
solve s
    | all (=='a') s = s
    | a == b && (length end) > (length b) = reverse $ drop (length a) $ reverse s
    | otherwise = ":("
    where end = takeWhile (/='a') $ reverse s
          (a, b) = splitInHalf $ filter (/='a') s

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


Two players decided to play one interesting card game.There is a deck of $$$n$$$ cards, with values from $$$1$$$ to $$$n$$$. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has at least one card. The game goes as follows: on each turn, each player chooses one of their cards (whichever they want) and puts on the table, so that the other player doesn't see which card they chose. After that, both cards are revealed, and the player, value of whose card was larger, takes both cards in his hand. Note that as all cards have different values, one of the cards will be strictly larger than the other one. Every card may be played any amount of times. The player loses if he doesn't have any cards.For example, suppose that $$$n = 5$$$, the first player has cards with values $$$2$$$ and $$$3$$$, and the second player has cards with values $$$1$$$, $$$4$$$, $$$5$$$. Then one possible flow of the game is:The first player chooses the card $$$3$$$. The second player chooses the card $$$1$$$. As $$$3>1$$$, the first player gets both cards. Now the first player has cards $$$1$$$, $$$2$$$, $$$3$$$, the second player has cards $$$4$$$, $$$5$$$.The first player chooses the card $$$3$$$. The second player chooses the card $$$4$$$. As $$$3<4$$$, the second player gets both cards. Now the first player has cards $$$1$$$, $$$2$$$. The second player has cards $$$3$$$, $$$4$$$, $$$5$$$.The first player chooses the card $$$1$$$. The second player chooses the card $$$3$$$. As $$$1<3$$$, the second player gets both cards. Now the first player has only the card $$$2$$$. The second player has cards $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$.The first player chooses the card $$$2$$$. The second player chooses the card $$$4$$$. As $$$2<4$$$, the second player gets both cards. Now the first player is out of cards and loses. Therefore, the second player wins.Who will win if both players are playing optimally? It can be shown that one of the players has a winning strategy.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). The description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$k_1$$$, $$$k_2$$$ ($$$2 \le n \le 100, 1 \le k_1 \le n - 1, 1 \le k_2 \le n - 1, k_1 + k_2 = n$$$) — the number of cards, number of cards owned by the first player and second player correspondingly. The second line of each test case contains $$$k_1$$$ integers $$$a_1, \dots, a_{k_1}$$$ ($$$1 \le a_i \le n$$$) — the values of cards of the first player. The third line of each test case contains $$$k_2$$$ integers $$$b_1, \dots, b_{k_2}$$$ ($$$1 \le b_i \le n$$$) — the values of cards of the second player. It is guaranteed that the values of all cards are different.

For each test case, output "YES" in a separate line, if the first player wins. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).

NoteIn the first test case of the example, there is only one possible move for every player: the first player will put $$$2$$$, the second player will put $$$1$$$. $$$2>1$$$, so the first player will get both cards and will win.In the second test case of the example, it can be shown that it is the second player who has a winning strategy. One possible flow of the game is illustrated in the statement.

import Control.Monad
import Data.Bool

main = getLine >>= flip replicateM_ test . read

test = do
    getLine
    as <- map read . words <$> getLine :: IO [Integer]
    bs <- map read . words <$> getLine :: IO [Integer]
    putStrLn $ bool "NO" "YES" $ maximum as > maximum bs

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

do_solve :: Int -> IO ()
do_solve 0 = return ()
do_solve n = do
    vals <- getinp
    frst <- getinp
    scnd <- getinp
    putStrLn $ id $ let f = maximum frst; s = maximum scnd in if f >= s then "YES" else "NO"
    do_solve (n - 1)

main :: IO ()
main = do
    ntest <- getinp
    do_solve $ head ntest

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

onecase = do
		getLine
		a<- map read <$> words <$> getLine::IO [Int]
		b<- map read <$> words <$> getLine::IO [Int]
		putStrLn $ if maximum a > maximum b then "YES" else "NO"

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

--ghc 7.10

winner :: [Int] -> [Int] -> String
winner as bs
    | maximum as > maximum bs = "YES"
    | otherwise = "NO"

process :: Int -> IO ()
process 0 = return ()
process t = do
    line1 <- getLine
    line2 <- getLine
    let as = map read . words $ line2
    line3 <- getLine
    let bs = map read . words $ line3
    putStrLn $ winner as bs
    process (t-1)

main = do
    tStr <- getLine
    let t = read tStr :: Int
    process t


One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Martian laws, one can buy only an integer number of dollars. Which maximal sum of money in bourles can Vasya get by the end of day n?

The first line contains two integers n and b (1 ≤ n, b ≤ 2000) — the number of days and the initial number of money in bourles. The next line contains n integers ai (1 ≤ ai ≤ 2000) — the prices of Martian dollars.

Print the single number — which maximal sum of money in bourles can Vasya get by the end of day n.

main = do
	n:b:a <- fmap (map read . words) getContents
	putStrLn $ show $ maximum $ zipWith (\x y -> b + div b y * (x - y)) a $ scanl1 min a

getArray = fmap (map read . words) getLine

main = do
	[n, b] <- getArray
	a <- getArray
	putStrLn $ show $ maximum $ b: zipWith (\x y -> b + div b x * (y - x)) (scanl1 min a) (tail a)

getArray = fmap (map read . words) getLine

main = do
	[n, b] <- getArray
	a <- getArray
	putStrLn $ show $ maximum $ zipWith (\x y -> b + div b y * (x - y)) a $ scanl1 min a

--

import List
main = interact (show.s.map read.words)
s (n:b:xs) = foldl f b (init(tails xs)) where f z y = max z (b`mod`a+b`div`a*maximum y) where a=head y

import Array

solve :: Int -> Array Int Int -> Int
solve b a  =  maximum $ b : [solve' i j | i <- [1..n], j <- [i+1..n]]
  where
    n  =  snd $ bounds a
    solve' i j
      | a ! i <= a ! j  =  div b (a ! i) * (a ! j) + mod b (a ! i)
      | otherwise  =  b

main :: IO ()
main  =  do
    [n, b]  <-  fmap (map read . words) getLine
    xs      <-  fmap (map read . words) getLine
    let array  =  listArray (1, n) xs
    print $ solve b array

import Data.List (maximumBy)

createWay [] = []
createWay xs = (map (\z -> (y, z)) xs):createWay ys
  where (y:ys) = xs

solve (x:xs) = maximum $ map (\(a, b) -> (x `div` a) * b + (x `mod` a)) $ concat $ createWay xs

main = interact (show.solve.map read.tail.words)

import Data.List
main = interact solve
solve input = output where
  [[n,b],a] = map (map (read::String->Int)) $ map words $ lines input
  output = show $ answer a + b
  answer [] = 0
  answer (x:xs) = foldl' max (answer xs) [div b x * (y-x)|y<-xs,y>x]

main = do
    let i = fmap (map read . words) getLine :: IO [Int]
    [n, b] <- i
    a <- i
    if n == 1
        then print b
        else print $ max b $ foldl1 max $ zipWith (\x y -> b`mod`x+b`div`x*y) (init a) (tail $ scanr1 max a)

getArray = fmap (map read . words) getLine

main = do
	[n, b] <- getArray
	a <- getArray
	putStrLn $ show $ maximum $ zipWith (\x y -> b + div b x * (y - x)) a $ scanl1 min a

--

import Data.List (maximumBy)

createWay [] = []
createWay xs = (map (\z -> (y, z)) xs):createWay ys
  where (y:ys) = xs

getMax xs = maximumBy p $ filter (\(a, b) -> a <= b) $ concat $ createWay xs
  where p (a1, b1) (a2, b2) = compare (b1 - a1) (b2 - a2)

solve (x:xs) = (x `div` a) * b + (x `mod` a)
  where (a, b) = getMax xs

main = interact (show.solve.map read.tail.words)


Valera has a strip infinite in both directions and consisting of cells. The cells are numbered by integers. The cell number 0 has a robot.The robot has instructions — the sequence of moves that he must perform. In one move, the robot moves one cell to the left or one cell to the right, according to instructions. Before the robot starts moving, Valera puts obstacles in some cells of the strip, excluding cell number 0. If the robot should go into the cell with an obstacle according the instructions, it will skip this move.Also Valera indicates the finish cell in which the robot has to be after completing the entire instructions. The finishing cell should be different from the starting one. It is believed that the robot completed the instructions successfully, if during the process of moving he visited the finish cell exactly once — at its last move. Moreover, the latter move cannot be skipped.Let's assume that k is the minimum number of obstacles that Valera must put to make the robot able to complete the entire sequence of instructions successfully and end up in some finishing cell. You need to calculate in how many ways Valera can choose k obstacles and the finishing cell so that the robot is able to complete the instructions successfully.

The first line contains a sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), consisting only of letters "L" and "R". If character si equals "L", then the robot on the i-th move must try to move one cell to the left. If the si-th character equals "R", then the robot on the i-th move must try to move one cell to the right.

Print a single integer — the required number of ways. It's guaranteed that this number fits into 64-bit signed integer type.

NoteIn the first sample Valera mustn't add any obstacles and his finishing cell must be cell 2.In the second sample, Valera must add an obstacle in cell number 1, and his finishing cell must be cell number  - 1. In this case robot skips the first two moves and on the third move he goes straight from the starting cell to the finishing one. But if Valera doesn't add any obstacles, or adds an obstacle to another cell, then the robot visits the finishing cell more than once.

import Data.List (groupBy)
import Data.Function (on)

count :: Eq e => e -> [e] -> Int
count a = foldr go 0
    where go i acc = if i == a then acc + 1 else acc

solve :: String -> Int
solve [_] = 1  -- single char
solve str = if peak < pos then 1 else loop pos minBound $ reverse (tail btm)
    where
    inc = map (\i -> if i == r then 1 else -1) str :: [Int] -- increments
        where r = last str

    idx = scanl (+) 0 inc      -- entire path
    pos = last idx             -- final position

    idx' = init idx         -- exclude very last step
    roll = scanr1 max idx'  -- reverse rolling maximums
    peak = head roll        -- peak before the very last step

    -- how far it goes back up, once it hits a minimum
    btm = map head . groupBy  ((==) `on` fst) $ zip (scanl1 min idx') roll

    loop _ _ [] = 0
    loop k r ((_, j):rest) = inc + loop (k + 1) r' rest
        where
        -- putting the skipping boundry at i
        r' = max (r + 1) (j + 1)
        inc = if max peak r' < k + 1 then 1 else 0

main = getLine >>= print . solve


You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. You want to split it into exactly $$$k$$$ non-empty non-intersecting subsegments such that each subsegment has odd sum (i. e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearrange (shuffle) the elements of a given array. Each of the $$$n$$$ elements of the array $$$a$$$ must belong to exactly one of the $$$k$$$ subsegments.Let's see some examples of dividing the array of length $$$5$$$ into $$$3$$$ subsegments (not necessarily with odd sums): $$$[1, 2, 3, 4, 5]$$$ is the initial array, then all possible ways to divide it into $$$3$$$ non-empty non-intersecting subsegments are described below:  $$$[1], [2], [3, 4, 5]$$$;  $$$[1], [2, 3], [4, 5]$$$;  $$$[1], [2, 3, 4], [5]$$$;  $$$[1, 2], [3], [4, 5]$$$;  $$$[1, 2], [3, 4], [5]$$$;  $$$[1, 2, 3], [4], [5]$$$. Of course, it can be impossible to divide the initial array into exactly $$$k$$$ subsegments in such a way that each of them will have odd sum of elements. In this case print "NO". Otherwise, print "YES" and any possible division of the array. See the output format for the detailed explanation.You have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the number of elements in the array and the number of subsegments, respectively. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each query, print the answer to it. If it is impossible to divide the initial array into exactly $$$k$$$ subsegments in such a way that each of them will have odd sum of elements, print "NO" in the first line. Otherwise, print "YES" in the first line and any possible division of the array in the second line. The division can be represented as $$$k$$$ integers $$$r_1$$$, $$$r_2$$$, ..., $$$r_k$$$ such that $$$1 \le r_1 < r_2 < \dots < r_k = n$$$, where $$$r_j$$$ is the right border of the $$$j$$$-th segment (the index of the last element that belongs to the $$$j$$$-th segment), so the array is divided into subsegments $$$[1; r_1], [r_1 + 1; r_2], [r_2 + 1, r_3], \dots, [r_{k - 1} + 1, n]$$$. Note that $$$r_k$$$ is always $$$n$$$ but you should print it anyway.

import Control.Monad (replicateM_)

findSegments :: Int -> Int -> [Int] -> [Int]
findSegments n k xs
    | numOdds < k || (numOdds - k) `mod` 2 == 1 = []
    | otherwise = (take (k - 1) $ map snd odds) ++ [n]
    where
        odds = filter (\(x, _) -> x `mod` 2 == 1) (zip xs [1..n])
        numOdds = length odds

readLine :: IO [Int]
readLine = (map read) . words <$> getLine

main =
    read <$> getLine >>= \q ->
    replicateM_ q (
        readLine >>= \[n, k] ->
        readLine >>= \xs ->
        putStrLn(
            let ans = findSegments n k xs in
                if null ans then "NO"
                else "YES\n" ++ unwords (map show ans)
        )
    )

import Data.List
import Control.Monad
main = do
  q <- readLn
  replicateM_ q $ do
    [n,k] <- map read . words <$> getLine
    as <- map read . words <$> getLine
    let rs = findIndices odd (0:as)
        l = length rs
    if l < k || odd l /= odd k then putStrLn "NO" else do
      putStrLn "YES"
      putStrLn $ unwords $ map show $ init (drop (l-k) rs) ++ [n]

main = interact $ unlines . process . tail . lines

process :: [String] -> [String]
process [] = []
process (a:b:xs) = (work a b) : (process xs)

work :: String -> String -> String
work a b
  | len < k = "NO"
  | odd (len - k) = "NO"
  | otherwise = "YES\n" ++ unwords(map show $ take (k-1) odds ++ [n])
  where
    n : k : _ = (map read $ words a) :: [Int]
    arr = (map read $ words b) :: [Integer]
    odds = map snd $ filter (odd . fst) $ zip arr [1..]
    len = length odds

import Data.List
import Control.Monad
main = do
  q <- readLn
  replicateM_ q $ do
    [n,k] <- map read . words <$> getLine
    as <- map read . words <$> getLine
    let rs = findIndices odd (0:as)
        l = length rs
    if l < k || odd l /= odd k then putStrLn "NO" else do
      putStrLn "YES"
      putStrLn $ unwords $ map show $ drop (l-k) rs

import Data.List
import Control.Monad
main = do
  q <- readLn
  replicateM_ q $ do
    [n,k] <- map read . words <$> getLine
    as <- map read . words <$> getLine
    let rs = findIndices odd (0:as)
        l = length rs
    if l < k || odd l /= odd k then putStrLn "NO" else do
      putStrLn "YES"
      putStrLn $ unwords $ map show $ drop (k-l) rs


Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya will beat all present opponents. Otherwise, if all opponents are present, then they will beat Arya.For each opponent Arya knows his schedule — whether or not he is going to present on each particular day. Tell him the maximum number of consecutive days that he will beat all present opponents.Note, that if some day there are no opponents present, Arya still considers he beats all the present opponents.

The first line of the input contains two integers n and d (1 ≤ n, d ≤ 100) — the number of opponents and the number of days, respectively. The i-th of the following d lines contains a string of length n consisting of characters '0' and '1'. The j-th character of this string is '0' if the j-th opponent is going to be absent on the i-th day.

Print the only integer — the maximum number of consecutive days that Arya will beat all present opponents.

NoteIn the first and the second samples, Arya will beat all present opponents each of the d days.In the third sample, Arya will beat his opponents on days 1, 3 and 4 and his opponents will beat him on days 2 and 5. Thus, the maximum number of consecutive winning days is 2, which happens on days 3 and 4.

import Data.List

main = getLine >> getContents >>= print . f . map length . filter ( id . head ) . group . map ( not . all ( == '1' ) ) . lines

f x
	| null x = 0
	| otherwise = maximum x

import Data.List

main :: IO()
main = print . solve . tail . lines =<< getContents

solve :: [String] -> Int
solve = maximum . (++) [0] . map length . filter head . group . map check

check :: String -> Bool
check s = length (filter (== '0') s) > 0

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

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

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

main = do
  [n, d] <- fmap (map read . words) getLine
  ls <- replicateM d getLine

  let xs = map length $ filter (id . head) $ group $ map (any (== '0')) ls
  print $ if null xs then 0 else maximum xs

import Data.List

main = do
    input <- getContents
    print $ sol $ tail $ lines input
    where sol xs = if any (elem '0') xs then (maximum . map length . filter (\x -> head x) . group . map (elem '0')) xs
                                        else 0

import Data.List
import Data.Char
main = do
  [n,d] <- map read . words <$> getLine
  print . maximum . (0 :) . map length . filter head . group . map ((< n) . sum . map digitToInt) . lines =<< getContents

import System.IO

getBestRun :: Int -> [Int] -> (Int, Int)
getBestRun n [] = (0, 0)
getBestRun n (x:xs) | x == n = (0, restBest)
                    | otherwise = (next + 1, best)
                    where (next, restBest) = getBestRun n xs
                          best = if next >= restBest then (next + 1) else restBest

getBestRunFromStr :: Int -> [String] -> Int
getBestRunFromStr n inps = let countArr = map (\x -> sum [1 | c <- x, c == '1']) inps
                               (next, best) = getBestRun n countArr
                           in best

main :: IO ()
main = do
    fstStr <- getLine
    let (n:d:_) = map (read :: String -> Int) $ words fstStr
    inpStrs <- (mapM (\_ -> getLine) [1..d])
    -- putStrLn . show $ getCountArr inpStrs
    putStrLn . show $ getBestRunFromStr n inpStrs
    return ()

import System.IO

getBestRun :: Int -> [Int] -> (Int, Int)
getBestRun n [] = (0, 0)
getBestRun n (x:xs) | x == n = (0, restBest)
                    | otherwise = (next + 1, best)
                    where (next, restBest) = getBestRun n xs
                          best = if next >= restBest then (next + 1) else restBest

getBestRunFromStr :: Int -> [String] -> Int
getBestRunFromStr n inps = let countArr = map (\x -> sum [1 | c <- x, c == '1']) inps
                               (next, best) = getBestRun n countArr
                           in best

main :: IO ()
main = do
    fstStr <- getLine
    let (n:d:_) = map (read :: String -> Int) $ words fstStr
    inpStrs <- (mapM (\_ -> getLine) [1..d])
    putStrLn . show $ getBestRunFromStr n inpStrs

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

main = do
  [n, d] <- map read . words <$> getLine
  [ss] <- transpose . map words <$> replicateM d getLine
  print $ maximum $ map length $ [] : (filter (any (== True)) $ group $ map (any (== '0')) ss)

import Data.List

main = getContents >>= print . maximum . map (\ls -> if head ls then length ls else 0) . group . map ('0' `elem`) . tail . lines

import Data.List( group)
main = do
    [n,d] <- return . map read . words =<< getLine
    abs <- sequence $ take d $ repeat getLine
    let isAbletoWin = not . cantWin
	cantWin = all (=='1')
	results = isAbletoWin `map` abs
	wins = filter (True `elem`) $ group results
	winconts =  length `map` wins
    if winconts == []
	then print 0
	else print $ maximum winconts

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

mymax e [] m n = max m n
mymax e (d:ds) m n | e/=d = mymax e ds m (n+1)
		   | otherwise = mymax e ds (max m n) 0

main = do
		[n,k]<- map read <$> words <$> getLine:: IO [Int]
		d<-replicateM k getLine
		let e= replicate n '1'
		print $ mymax e d 0 0

import Control.Applicative
import Control.Monad

beat = any (=='0')

check [] n     = [n]
check (l:ls) n =
    if beat l
        then n:check ls (n+1)
        else n:check ls 0

main = do
   [n, d] <- map read . words <$> getLine
   ls <- replicateM d getLine
   print $ maximum $ check ls 0

import Data.List (group)

process :: [[Char]] -> Int
process = maximum.map (\x -> if head x then length x else 0).group.map (any (=='0'))

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    [n,d] <- fmap (map readInt.words) getLine
    xs <- fmap lines getContents
    print $ process xs

{-# LANGUAGE FlexibleInstances #-}
module Main (printShit, printShitV, readShit, main, yN) where
import Data.ByteString.Builder
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Maybe
import Data.List
-- Meat
solve :: [String]-> Int
solve = maximum.(0:).fmap length.filter head.group.fmap (elem '0')

-- Shit
main :: IO ()
main = do
        (_:es) <- readShit
        printShit [solve es]

class Shit a where
    printShit :: a -> IO ()
    printShitV :: a -> IO ()
    readShit :: IO a
    printShitV = printShit

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

instance  Shit Int where
    printShit = print
    readShit = fmap read getLine

instance  Shit [Int] where
    printShit = putStrLn . unwords . fmap show
    printShitV = putStrLn . unlines . fmap show
    readShit = fmap (fmap read . words) getLine

instance  Shit [Integer] where
    printShit = putStrLn . unwords . fmap show
    printShitV = putStrLn . unlines . fmap show
    readShit = fmap (fmap read . words) getLine

instance Shit [[Int]] where
    printShit = printShit . (fmap.fmap)  (toLazyByteString . integerDec .toInteger)
    readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit

instance Shit [[Integer]] where
    printShit  = printShit . (fmap.fmap)  (toLazyByteString . integerDec)
    readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit

instance Shit [String] where
    printShit = putStrLn. unwords
    printShitV = putStrLn . unlines
    readShit = fmap lines getContents

instance Shit [[String]] where
    printShit = putStrLn . unlines . fmap unwords
    readShit = fmap (fmap (fmap words) lines) getContents

instance Shit [BS.ByteString] where
    printShit = BS.putStrLn. BS.unwords
    printShitV = BS.putStrLn . BS.unlines
    readShit = fmap BS.lines BS.getContents

instance Shit [[BS.ByteString]] where
    printShit = BS.putStrLn . BS.unlines . fmap BS.unwords
    readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents

import Data.List
main=interact$show.maximum.(0:).fmap length.filter head.group.fmap(elem '0').tail.lines

import Data.List

main :: IO()
main = print . solve . tail . lines =<< getContents

solve :: [String] -> Int
solve = maximum . map length . group . map check

check :: String -> Bool
check s = length (filter (== '0') s) > 0

import Data.List

main = do
    input <- getContents
    print $ sol $ tail $ lines input
    where sol = (maximum . map length . group . map (elem '0'))


You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. 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. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.

import Control.Arrow

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

solve :: [Integer] -> Integer
solve [a, b]
  | d == 0 = 0
  | otherwise = b - d
    where d = a `mod` b

import Control.Monad (replicateM, forM_)

getSolution :: [Int] -> Int

getSolution (a : b : []) =

  let

    x = a `mod` b

  in case x of

    0 -> 0

    otherwise -> (b - x)

main = do

    -- could also do t <- readLn :: IO Int

    t <- fmap (read :: String -> Int) getLine

    -- putStrLn $ show t

    line <- replicateM t getLine

    let

        splitted = fmap words line

        casted   = (fmap . fmap) (read :: String -> Int) splitted

        solutions = fmap getSolution casted  -- [Int]

      in

        forM_ (fmap show solutions) putStrLn

main=interact$unlines.map s.drop 1.lines
s=show.t.map read.words
t[a,b]=mod(b-mod a b)b

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
        [x, y] <- getIntList
        print $ (y - x `mod` y) `mod` y

main = getLine >>= test.read
test 0 = return ();
test i = do
  (a:b:_) <- map read.words <$> getLine
  print $ (b - a `mod` b) `mod` b
  test (i - 1)

main = interact $ unlines . map  ( show . (\ [b,a] -> if b `mod` a == 0 then 0 else a - (b `mod` a)) . map (read :: String -> Int) .  words) .  tail . lines

main :: IO ()
main = map (solve . parse) . tail . lines <$> getContents >>= mapM_ print
  where
    parse = f . words
    f [a, b] = (read a, read b)

solve :: (Int, Int) -> Int
solve (a, b) = ((a + b - 1) `div` b) * b - a

import Control.Monad (replicateM_)

getList :: Read b => IO [b]
getList = map read . words <$> getLine

main = readLn >>= flip replicateM_ solve

solve = do
    [a,b] <- getList
    print $ (-a) `mod` b

import Control.Monad

main :: IO ()
main = do
  n <- fmap read getLine
  replicateM_ n (do
    [a, b] <- map read . words <$> getLine
    putStrLn $ show $ (a + b - 1) `div` b * b - a)

-- PROBLEM: https://codeforces.com/contest/1328/problem/A

import Control.Arrow ((>>>))

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

solve :: [Int] -> Int
solve [u, v]
  | mod u v == 0 = 0
  | otherwise = v - mod u v

import Control.Monad

main = do
    numTests <- read <$> getLine
    replicateM_ numTests $ do
        [a, b] <- map read . words <$> getLine
        let m = mod a b
        print $ if m == 0 then 0 else b - m

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

ans a b | z==0 = 0
        | otherwise = b-z
	where z= mod a b
onecase= do
		[a,b]<-map read <$> words<$> getLine ::IO [Int]
		print $ ans a b

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

import           Control.Monad
main :: IO ()
main = do
    n <- (read :: String -> Int) <$> getLine
    replicateM_ n $ print =<< (\[a,m]->(-a)`mod`m) . map (read :: String -> Int) . words <$> getLine

import           Control.Monad
main :: IO ()
main = do
    n <- (read :: String -> Int) <$> getLine
    replicateM_ n $ print =<< (\[a,m]->(m - a`mod`m)`mod`m) . map (read :: String -> Int) . words <$> getLine

import Data.List

process :: (Int,Int) -> Int
process (a,b) = (b - a) `mod` b

readInt :: String -> Int
readInt = read

readPair :: String -> (Int,Int)
readPair line = (a,b)
    where [a,b] = map readInt $ words line

main = do
    n <- fmap readInt getLine
    xs <- fmap (map readPair.lines) getContents
    sequence . map (print . process) $ xs

import Control.Monad
import Text.Printf

move :: Integer -> Integer -> Integer
move a b = case mod a b of
    0 -> 0
    c -> b - c

main = do
    i <- getLine
    let t = read i :: Integer
    forM_ [1..t] $ \ _ -> do
        ii <- getLine
        let [a,b] = map (\x -> read x :: Integer) $ words ii
        let c = move a b
        printf "%v\n" c

main :: IO ()

main = do
    getLine
    answers <- map (solve . map read . words) <$> lines <$> getContents :: IO [Int]
    mapM_ print answers

solve [x,y] = (-x) `mod` y

import Control.Arrow

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

supersolve :: String -> String
supersolve = words >>> map read >>> solve2 >>> show

solve2 [a, b] = solve a b
solve2 [] = 0

solve :: Int -> Int -> Int
solve a b
    | a `mod` b == 0 = 0
    | otherwise = b - (a `mod` b)


Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.Artem wants to paint an $$$n \times m$$$ board. Each cell of the board should be colored in white or black. Lets $$$B$$$ be the number of black cells that have at least one white neighbor adjacent by the side. Let $$$W$$$ be the number of white cells that have at least one black neighbor adjacent by the side. A coloring is called good if $$$B = W + 1$$$. The first coloring shown below has $$$B=5$$$ and $$$W=4$$$ (all cells have at least one neighbor with the opposite color). However, the second coloring is not good as it has $$$B=4$$$, $$$W=4$$$ (only the bottom right cell doesn't have a neighbor with the opposite color).  Please, help Medina to find any good coloring. It's guaranteed that under given constraints the solution always exists. If there are several solutions, output any of them.

Each test contains multiple test cases.  The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 20$$$). Each of the next $$$t$$$ lines contains two integers $$$n, m$$$ ($$$2 \le n,m \le 100$$$) — the number of rows and the number of columns in the grid.

For each test case print $$$n$$$ lines, each of length $$$m$$$, where $$$i$$$-th line is the $$$i$$$-th row of your colored matrix (cell labeled with 'B' means that the cell is black, and 'W' means white). Do not use quotes. It's guaranteed that under given constraints the solution always exists.

NoteIn the first testcase, $$$B=3$$$, $$$W=2$$$.In the second testcase, $$$B=5$$$, $$$W=4$$$. You can see the coloring in the statement.

import Control.Monad

type Test = (Integer, Integer)
type Row = [Char]
type Board = [Row]

getTests :: Int -> IO [Test]
getTests n = replicateM n getTest

getTest :: IO Test
getTest = do
    test <- getLine
    return $ parseTest test

parseTest :: String -> Test
parseTest str = (parsed !! 0, parsed !! 1)
    where parsed = map read (words str)

getAnswer :: [Test] -> [Board]
getAnswer [] = []
getAnswer ((n, m):rest) = if not $ odd (n*m)
                          then change board : (getAnswer rest)
                          else board : (getAnswer rest)
    where board = getChessBoard n m

change :: Board -> Board
change (first:rest) = if m > 1
                      then (removeOneW first):rest
                      else [first] ++ [removeOneW $ head rest] ++ (tail rest)
    where m = length first

removeOneW :: Row -> Row
removeOneW (symbol:rest) = if symbol == 'W'
                           then 'B':rest
                           else symbol: removeOneW rest

getChessBoard :: Integer -> Integer -> Board
getChessBoard n m = getChessBoard' n (getChessLine 'B' m)

getChessBoard' :: Integer -> Row -> Board
getChessBoard' 0 row = []
getChessBoard' n row = row : getChessBoard' (n - 1) (interchange row)

interchange :: Row -> Row
interchange [] = []
interchange (first:rest) = newSymbol : interchange rest
    where newSymbol = if first == 'W'
                      then 'B'
                      else 'W'

getChessLine :: Char -> Integer -> Row
getChessLine symbol 0 = []
getChessLine symbol m = symbol : getChessLine nextSymbol (m-1)
    where nextSymbol = if symbol == 'W'
                       then 'B'
                       else 'W'

printTest :: Board -> IO ()
printTest board = do
    mapM_ putStrLn board

main :: IO ()
main = do
    count <- getLine
    tests <- getTests $ read count
    mapM_ printTest (getAnswer tests)

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
        [n, m] <- getIntList
        putStr $ f n m

g :: Int -> String
g m = take m
      . concat
      $ repeat "BW"

r :: Char -> Char
r 'B' = 'W'
r 'W' = 'B'

s :: Int -> Int -> String
s n m = concat
        . map (++"\n")
        . take n
        $ iterate (map r) (g m)

f :: Int -> Int -> String
f n m
    | odd (n * m) = s n m
    | otherwise = 'B' : 'B' : (drop 2 $ s n m)

{-# LANGUAGE ScopedTypeVariables #-}

reshape _ 0 _ = []
reshape w h elems =
  let (row, rest) = splitAt w elems in row : reshape w (h - 1) rest

f :: [Int] -> [[String]]
f [h, w] = reshape w h $ take (w * h) $ "W" : repeat "B"

splitInput :: String -> [[Int]]
splitInput = map (map read . words) . tail . lines

go :: String -> String
go input =
  let answers :: [[[String]]] = map f (splitInput input) in
  concat $ map (unlines . map concat) answers

main = interact go

import Control.Monad

linha :: Int -> Int -> String
linha n m = [ "BW"!!pos | h <- [0..m-2], let pos = (n+h)`mod`2 ] ++ "B"

checkers :: Int -> Int -> [String]
checkers n m = [ [ "BW"!!pos | h <- [0..m-1], let pos = (i+h)`mod`2 ] | i <- [0..n-1] ]

foo :: Int -> Int -> [String]
foo n m | odd n && odd m = checkers n m
        | even n && even m = [linha 0 m] ++ (tail (checkers n m))
        | otherwise = (init (checkers n m)) ++ [linha (n-1) m]

readInts :: IO [Int]
readInts = fmap (map read.words) getLine

main :: IO()
main = do
  t <- readLn :: IO Int

  forM_ [1..t] $ \i -> do
    a <- readInts
    let out = foo (a!!0) (a!!1)
    forM_ [0..(a!!0 - 1)] $ \l -> do
      putStrLn (out!!l)

solve :: Int -> Int -> String
solve n m
  | odd len = board
  | otherwise = if (odd m) then ((init board) ++ "B") else ("BB" ++ (drop 2 board))
  where len = n*m
        board = [printer i j | i <- [0..(n-1)], j <- [0..(m-1)]]

printer :: Int -> Int -> Char
printer i j
  | even i && even j = 'B'
  | even i && odd  j = 'W'
  | odd  i && even j = 'W'
  | otherwise        = 'B'

partitionBy :: Int -> String -> [String]
partitionBy _ "" = []
partitionBy n input = [(take n input)] ++ (partitionBy n (drop n input))

parse :: String -> String
parse contents = foldl (++) "" solutions
  where lines' = tail $ lines contents
        inputs = map (\[n', k'] -> (read n' :: Int, read k' :: Int)) $ map words lines'
        solutions = map (\(n, k) -> unlines (partitionBy k (solve n k))) inputs

main :: IO ()
main = do
  contents <- getContents
  putStr (parse contents)

{-# LANGUAGE ScopedTypeVariables #-}

reshape _ 0 _ = []
reshape w h elems =
  let (row, rest) = splitAt w elems in row : reshape w (h - 1) rest

elemsList :: Int -> Int -> [String]
elemsList w h
 | odd (w * h) = take (w * h) $ cycle["B", "W"]
 | otherwise = (take (w * h - 1) $ cycle["B", "W"]) ++ ["B"]

f :: [Int] -> [[String]]
f [h, w] = reshape w h $ elemsList w h

splitInput :: String -> [[Int]]
splitInput = map (map read . words) . tail . lines

go :: String -> String
go input =
  let answers :: [[[String]]] = map f (splitInput input) in
  concat $ map (unlines . map concat) answers

main = interact go

solve :: Int -> Int -> String
solve n m
  | odd len = board
  | otherwise = if (odd m) then ((init board) ++ "B") else ("BB" ++ (drop 2 board))
  where len = n*m
        board = [printer i j | j <- [0..(m-1)], i <- [0..(n-1)]]

printer :: Int -> Int -> Char
printer i j
  | even i && even j = 'B'
  | even i && odd  j = 'W'
  | odd  i && even j = 'W'
  | otherwise        = 'B'

partitionBy :: Int -> String -> [String]
partitionBy _ "" = []
partitionBy n input = [(take n input)] ++ (partitionBy n (drop n input))

parse :: String -> String
parse contents = foldl (++) "" solutions
  where lines' = tail $ lines contents
        inputs = map (\[n', k'] -> (read n' :: Int, read k' :: Int)) $ map words lines'
        solutions = map (\(n, k) -> unlines (partitionBy k (solve n k))) inputs

main :: IO ()
main = do
  contents <- getContents
  putStr (parse contents)

solve :: Int -> Int -> String
solve n m
  | odd len = board
  | otherwise = (init board) ++ "B"
  where len = n*m
        board = [if even i then 'B' else 'W' | i <- [0..(len-1)]]

partitionBy :: Int -> String -> [String]
partitionBy _ "" = []
partitionBy n input = [(take n input)] ++ (partitionBy n (drop n input))

parse :: String -> String
parse contents = foldl (++) "" solutions
  where lines' = tail $ lines contents
        inputs = map (\[n', k'] -> (read n' :: Int, read k' :: Int)) $ map words lines'
        solutions = map (\(n, k) -> unlines (partitionBy k (solve n k))) inputs

main :: IO ()
main = do
  contents <- getContents
  putStr (parse contents)


A tree of size n is an undirected connected graph consisting of n vertices without cycles.Consider some tree with n vertices. We call a tree invariant relative to permutation p = p1p2... pn, if for any two vertices of the tree u and v the condition holds: "vertices u and v are connected by an edge if and only if vertices pu and pv are connected by an edge".You are given permutation p of size n. Find some tree size n, invariant relative to the given permutation.

The first line contains number n (1 ≤ n ≤ 105) — the size of the permutation (also equal to the size of the sought tree). The second line contains permutation pi (1 ≤ pi ≤ n).

If the sought tree does not exist, print "NO" (without the quotes). Otherwise, print "YES", and then print n - 1 lines, each of which contains two integers — the numbers of vertices connected by an edge of the tree you found. The vertices are numbered from 1, the order of the edges and the order of the vertices within the edges does not matter. If there are multiple solutions, output any of them.

NoteIn the first sample test a permutation transforms edge (4, 1) into edge (1, 4), edge (4, 2) into edge (1, 3) and edge (1, 3) into edge (4, 2). These edges all appear in the resulting tree.It can be shown that in the second sample test no tree satisfies the given condition.

import Prelude hiding (getLine)
import Control.Applicative ((<$>))
import Data.List (unfoldr, find)
import Control.Monad (forM_, forM)
import Data.ByteString (ByteString, getLine)
import qualified Data.ByteString.Char8 as B
import Control.Monad.ST.Safe (ST, runST)
import Data.Array.Unboxed (listArray, UArray, (!))
import Data.Array.ST.Safe (STUArray, newArray, readArray, writeArray)

parse :: ByteString -> [Int]
parse = unfoldr $ B.readInt . B.dropWhile (== ' ')

dump Nothing = putStrLn "NO"
dump (Just a) = do
    putStrLn "YES"
    forM_ a $ (\(x, y) -> putStrLn $ show x ++ " " ++ show y)

loop :: UArray Int Int -> STUArray s Int Bool -> Int -> ST s [Int]
loop arr tag i = do
    flag <- readArray tag i
    if flag then return []
    else writeArray tag i True >> (i:) <$> loop arr tag (arr ! i)

run :: Int -> [[Int]] -> Maybe [(Int, Int)]
run n a = case find ((== 1) . length) a of
    (Just [r]) -> Just . map ((,) r) $ [1..r - 1] ++ [r + 1..n]
    _          -> case any (odd . length) a of
        True  -> Nothing
        False -> case find ((== 2) . length) a of
            Nothing -> Nothing
            (Just [x, y]) -> Just $ (x, y): concatMap go a
                where
                go xs
                    | xs == [x, y] = []
                    | otherwise = zip xs (cycle [x, y])

solve :: Int -> [Int] -> Maybe [(Int, Int)]
solve n a = run n cycl
    where
    arr = listArray (1, n) a :: UArray Int Int

    cycl = filter (not . null) $ runST $ do
        tag <- newArray (1, n) False :: ST s (STUArray s Int Bool)
        mapM (loop arr tag) [1..n]

main = do
    [n] <- parse <$> getLine
    getLine >>= dump . solve n . parse

import Prelude hiding (getLine)
import Control.Applicative ((<$>))
import Data.List (unfoldr, find)
import Control.Monad (forM_, forM)
import Data.ByteString (ByteString, getLine)
import qualified Data.ByteString.Char8 as B
import Control.Monad.ST.Safe (ST, runST)
import Data.Array.Unboxed (listArray, UArray, (!))
import Data.Array.ST.Safe (STUArray, newArray, readArray, writeArray)

parse :: ByteString -> [Int]
parse = unfoldr $ B.readInt . B.dropWhile (== ' ')

dump 1 _ = putStrLn "YES"
dump _ [] = putStrLn "NO"
dump _ a = do
    putStrLn "YES"
    forM_ a $ (\(x, y) -> putStrLn $ show x ++ " " ++ show y)

loop :: UArray Int Int -> STUArray s Int Bool -> Int -> ST s [Int]
loop arr tag i = do
    flag <- readArray tag i
    if flag
    then return []
    else writeArray tag i True >> (i:) <$> loop arr tag (arr ! i)

run :: Int -> [[Int]] -> [(Int, Int)]
run n a = case find ((== 1) . length) a of
    (Just [r]) -> map ((,) r) $ [1..r - 1] ++ [r + 1..n]
    _          -> case any (odd . length) a of
        True  -> []
        False -> case find ((== 2) . length) a of
            Nothing -> []
            (Just [x, y]) -> (x, y): concatMap go a
                where
                go xs
                    | xs == [x, y] = []
                    | otherwise = zip xs (cycle [x, y])

solve :: Int -> [Int] -> [(Int, Int)]
solve n a = run n cycl
    where
    arr = listArray (1, n) a :: UArray Int Int

    cycl = filter (not . null) $ runST $ do
        tag <- newArray (1, n) False :: ST s (STUArray s Int Bool)
        mapM (loop arr tag) [1..n]

main = do
    [n] <- parse <$> getLine
    getLine >>= dump n . solve n . parse

import Prelude hiding (getLine)
import Control.Applicative ((<$>))
import Data.List (unfoldr, find)
import Control.Monad (forM_, forM)
import Data.ByteString (ByteString, getLine)
import qualified Data.ByteString.Char8 as B
import Control.Monad.ST.Safe (ST, runST)
import Data.Array.Unboxed (listArray, UArray, (!))
import Data.Array.ST.Safe (STUArray, newArray, readArray, writeArray)

parse :: ByteString -> [Int]
parse = unfoldr $ B.readInt . B.dropWhile (== ' ')

dump [] = putStrLn "NO"
dump a = do
    putStrLn "YES"
    forM_ a $ (\(x, y) -> putStrLn $ show x ++ " " ++ show y)

loop :: UArray Int Int -> STUArray s Int Bool -> Int -> ST s [Int]
loop arr tag i = do
    flag <- readArray tag i
    if flag
    then return []
    else writeArray tag i True >> (i:) <$> loop arr tag (arr ! i)

run :: Int -> [[Int]] -> [(Int, Int)]
run n a = case find ((== 1) . length) a of
    (Just [r]) -> map ((,) r) $ [1..r - 1] ++ [r + 1..n]
    _          -> case any (odd . length) a of
        True  -> []
        False -> case find ((== 2) . length) a of
            Nothing -> []
            (Just [x, y]) -> (x, y): concatMap go a
                where
                go xs
                    | xs == [x, y] = []
                    | otherwise = zip xs (cycle [x, y])

solve :: Int -> [Int] -> [(Int, Int)]
solve n a = run n cycl
    where
    arr = listArray (1, n) a :: UArray Int Int

    cycl = filter (not . null) $ runST $ do
        tag <- newArray (1, n) False :: ST s (STUArray s Int Bool)
        mapM (loop arr tag) [1..n]

main = do
    [n] <- parse <$> getLine
    getLine >>= dump . solve n . parse


One day Squidward, Spongebob and Patrick decided to go to the beach. Unfortunately, the weather was bad, so the friends were unable to ride waves. However, they decided to spent their time building sand castles.At the end of the day there were n castles built by friends. Castles are numbered from 1 to n, and the height of the i-th castle is equal to hi. When friends were about to leave, Squidward noticed, that castles are not ordered by their height, and this looks ugly. Now friends are going to reorder the castles in a way to obtain that condition hi ≤ hi + 1 holds for all i from 1 to n - 1.Squidward suggested the following process of sorting castles:   Castles are split into blocks — groups of consecutive castles. Therefore the block from i to j will include castles i, i + 1, ..., j. A block may consist of a single castle.  The partitioning is chosen in such a way that every castle is a part of exactly one block.  Each block is sorted independently from other blocks, that is the sequence hi, hi + 1, ..., hj becomes sorted.  The partitioning should satisfy the condition that after each block is sorted, the sequence hi becomes sorted too. This may always be achieved by saying that the whole sequence is a single block. Even Patrick understands that increasing the number of blocks in partitioning will ease the sorting process. Now friends ask you to count the maximum possible number of blocks in a partitioning that satisfies all the above requirements.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of castles Spongebob, Patrick and Squidward made from sand during the day. The next line contains n integers hi (1 ≤ hi ≤ 109). The i-th of these integers corresponds to the height of the i-th castle.

Print the maximum possible number of blocks in a valid partitioning.

NoteIn the first sample the partitioning looks like that: [1][2][3].  In the second sample the partitioning is: [2, 1][3, 2]

import Data.List (scanl1, sort)
main = interact $ show . solve . map read . words
solve (_:a) = length $ filter (==0) $ scanl1 (+) $ zipWith (-) a $ sort a

import Data.List

main = do
    n <- getLine
    line <- getLine
    let mlist = (map read . words) line
    print (chack (sums 0 mlist) (sums 0 (sort mlist)) - 1)
        where
            sums c [] = [c]
            sums c (a:b) = [c + a] ++ sums (a + c) b
            chack [] [] = 0
            chack (a : xv) (b : zv) | a == b = 1 + chack xv zv
            chack (a : xv) (b : zv) = 0 + chack xv zv

import Data.List

main = do
    n <- getLine
    line <- getLine
    let mlist = (map read . words) line
    print (chack 0 0 mlist (sort mlist))
        where
            chack c d [] [] = 0
            chack c d (a : xv) (b : zv) | c == d = 1 +  chack (c+a) (d + b) xv zv
            chack c d (a : xv) (b : zv) = 0 + chack (c+a) (d + b) xv zv

import Control.Applicative

prefixMax = scanl1 max

suffixMin = scanr1 min

computeIndexes prefixMax suffixMin = foldl (\res (a, b) -> if a <= b then res+1 else res) 1 $ zip prefixMax $ drop 1 suffixMin

main = do
    n <- readLn
    list <- take n . map read <$> words <$> getLine :: IO [Integer]
    let max = prefixMax list
        min = suffixMin list
    print $ computeIndexes max min


Find the minimum area of a square land on which you can place two identical rectangular $$$a \times b$$$ houses. The sides of the houses should be parallel to the sides of the desired square land.Formally,   You are given two identical rectangles with side lengths $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 100$$$) — positive integers (you are given just the sizes, but not their positions).  Find the square of the minimum area that contains both given rectangles. Rectangles can be rotated (both or just one), moved, but the sides of the rectangles should be parallel to the sides of the desired square. Two rectangles can touch each other (side or corner), but cannot intersect. Rectangles can also touch the sides of the square but must be completely inside it. You can rotate the rectangles. Take a look at the examples for a better understanding.    The picture shows a square that contains red and green rectangles.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) —the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing two integers $$$a$$$, $$$b$$$ ($$$1 \le a, b \le 100$$$) — side lengths of the rectangles.

Print $$$t$$$ answers to the test cases. Each answer must be a single integer — minimal area of square land, that contains two rectangles with dimensions $$$a \times b$$$.

NoteBelow are the answers for the first two test cases:

module Main where

import Control.Monad
import Data.List

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [a, b] <- sort <$> map (read) <$> words <$> getLine
        print $ sqr $ max b (a * 2)
                    where sqr x = x * x

import           Control.Monad

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

solve :: IO ()
solve = do
    [a, b] <- map read . words <$> getLine
    print $ min (area (2 * a) b) (area a (2 * b))
  where
    area :: Int -> Int -> Int
    area x y = max x y ^ 2

{-- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}
import Control.Monad

main = getLine >>= flip replicateM_ test . read

test = do
    (a:b:_) <- map read . words <$> getLine
    print $ minimum [max (max a b) (2 * min a b) ^ 2, (a + b) ^ 2]

module Main where

main = interact $ unlines . map ( show . (^2) .  (\[x,y] -> let z = min (y * 2) (x * 2) in if z >= max x y then z else max x y). map (read :: String -> Integer) . words ) . tail . lines

import Control.Monad (replicateM_)

getMinSquare [a, b] = side * side where
    side = max (2 * min a b) (max a b)

parseLine = fmap ((map read) . words) getLine

main =
    fmap read getLine >>= \t ->
    replicateM_ t (fmap getMinSquare parseLine >>= print)

--- frederick99, 6/2020
--- https://codeforces.com/contest/1360/problem/A

import Control.Monad ( replicateM_ )

minSquare :: [Int] -> Int
minSquare [w, h] = max a (2*b) ^ 2
    where a = max w h
          b = min w h

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

main :: IO ()
main = do
    x <- read <$> getLine
    replicateM_ x (minSquare <$> readInput >>= print)

import Control.Monad ( replicateM_ )

readInput = map read . words <$> getLine

minSquare [w, h] = (max a (2*b)) ^ 2
    where a = max w h
          b = min w h

main = do
    x <- read <$> getLine
    replicateM_ x (minSquare <$> readInput >>= print)

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

onecase = do
		[a,b]<- map read <$> words <$> getLine ::IO [Int]
		print $ (^2)  $ min (max a (b+b)) (max b (a+a))

main= do
		a<- read <$> getLine ::IO Int
		replicateM_ a onecase

import Data.Array

memoize :: Ix i => (i,i) -> (i -> e) -> (i -> e)
memoize bnds fun = (array bnds [(i, fun i) | i <- range bnds] !)

listMemoize :: Ix i => (i,i) -> (i -> e) -> (i -> e)
listMemoize bnds fun = let li = map fun (range bnds) in
  \ix -> li !! (index bnds ix)

parse :: String -> [(Int, Int)]
parse inp = [(x, y) | [x, y] <- map (map read . words) . tail $ lines inp]

solve :: [(Int, Int)] -> [Int]
solve = map (\(x, y) -> let l = maximum [x, y, 2 * min x y] in l*l)

showAns :: [Int] -> String
showAns = unlines . map show

main :: IO ()
main = interact (showAns . solve . parse)

module Main where

main = interact $ unlines . map ( show . (^2) .  (\[x,y] -> if x==y then x else min (y * 2) (x * 2) ). map (read :: String -> Integer) . words ) . tail . lines

module Main where

main = interact $ unlines . map ( show . (^2) .  (\[x,y] -> min (y * 2) (x * 2) ). map (read :: String -> Integer) . words ) . tail . lines

module Main where

main = interact $ unlines . map ( show . (^2) .  (\[x,y] -> max (y * 2) (x * 2) ). map (read :: String -> Integer) . words ) . tail . lines

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

onecase = do
		[a,b]<- map read <$> words <$> getLine ::IO [Int]
		print $ min (max a (b+b)) (max b (a+a))

main= do
		a<- read <$> getLine ::IO Int
		replicateM_ a onecase