The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column).    The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.

Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.

4
1 1
L
1 2
L
3 3
RRDLUU
4 3
LUURRDDLLLUU

{-
-}

{-# Options_GHC -O2 #-}
import Data.Char
import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.Bits
import Data.List

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words

getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

move :: [Int] -> Char -> [Int]
move [x,y] c = case c of
    'L' -> [x,y-1]
    'R' -> [x,y+1]
    'U' -> [x-1,y]
    'D' -> [x+1,y]
    _ -> [x,y]

process 0 = return ()
process t = do
    [n,m] <- getIntList
    --cmds <- getLine
    cmds <- takeWhile (not . isSpace) . BS.unpack <$> BS.getLine
    let delta = scanl (\p c -> (move p c)) [0,0] cmds
    let bound = scanl (\[x0,x1,y0,y1] [x,y] -> [min x0 x, max x1 x, min y0 y, max y1 y]) [0,0,0,0] delta
    let xxx = [[x1-x0+1, y1-y0+1] | [x0,x1,y0,y1] <- bound]
    let yyy = filter (\x -> ((x!!0)<=n) && ((x!!1)<=m) ) xxx
    let [x0,x1,y0,y1] = bound !! ((length yyy) -1)
    putStrLn $ tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show

    process (t-1)

main = do
    t <- getInt
    process t

{-
-}

{-# Options_GHC -O2 #-}
import Data.Char
import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.Bits
import Data.List

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words

getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

move :: [Int] -> Char -> [Int]
move [x,y] c = case c of
    'L' -> [x,y-1]
    'R' -> [x,y+1]
    'U' -> [x-1,y]
    'D' -> [x+1,y]

process 0 = return ()
process t = do
    [n,m] <- getIntList
    cmds <- takeWhile (not . isSpace) . BS.unpack <$> BS.getLine
    let delta = scanl (\p c -> (move p c)) [0,0] cmds
    let bound = scanl (\[x0,x1,y0,y1] [x,y] -> [min x0 x, max x1 x, min y0 y, max y1 y]) [0,0,0,0] delta
    let xxx = [[x1-x0+1, y1-y0+1] | [x0,x1,y0,y1] <- bound]
    let yyy = filter (\x -> ((x!!0)<=n) && ((x!!1)<=m) ) xxx
    let [x0,x1,y0,y1] = bound !! ((length yyy) -1)
    putStrLn $ tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show

    process (t-1)

main = do
    t <- getInt
    process t

-- https://codeforces.com/contest/1607/problem/E

move command (row, col, minRow, maxRow, minCol, maxCol)
    | command == 'U' = (row-1, col, min (row-1) minRow, maxRow, minCol, maxCol)
    | command == 'D' = (row+1, col, minRow, max (row+1) maxRow, minCol, maxCol)
    | command == 'L' = (row, col-1, minRow, maxRow, min (col-1) minCol, maxCol)
    | command == 'R' = (row, col+1, minRow, maxRow, minCol, max (col+1) maxCol)
    | otherwise = (row, col, minRow, maxRow, minCol, maxCol)

solve _ (_,_, minRow,_, minCol,_) [] = show(2-minRow) ++ " " ++ show(2-minCol)
solve (height, width) (row, col, minRow, maxRow, minCol, maxCol) (command:rest)
    | newMaxCol-newMinCol + 1 > width || newMaxRow-newMinRow + 1 > height =
        if command == 'U' then show(1-newMinRow)++" "++show(2-newMinCol) else
        if command == 'L' then show(2-newMinRow)++" "++show(1-newMinCol) else
                               show(2-newMinRow)++" "++show(2-newMinCol)
    | otherwise = solve (height, width) newPos rest
    where
        newPos = move command (row, col, minRow, maxRow, minCol, maxCol)
        (_, _, newMinRow, newMaxRow, newMinCol, newMaxCol) = newPos

run 0 = return 0
run n = do
    size <- words <$> getLine
    commands <- getLine
    putStrLn $ solve (read $ size!!0, read $ size!!1) (1,1,1,1,1,1) commands
    run $ n-1
main = getLine >>= run . read

-- https://codeforces.com/contest/1607/problem/E

-- move :: Char -> (Int, Int, Int, Int, Int, Int) -> (Int, Int, Int, Int, Int, Int)
move command (row, col, minRow, maxRow, minCol, maxCol)
    | command == 'U' = (row-1, col, min (row-1) minRow, maxRow, minCol, maxCol)
    | command == 'D' = (row+1, col, minRow, max (row+1) maxRow, minCol, maxCol)
    | command == 'L' = (row, col-1, minRow, maxRow, min (col-1) minCol, maxCol)
    | command == 'R' = (row, col+1, minRow, maxRow, minCol, max (col+1) maxCol)
    | otherwise = (row, col, minRow, maxRow, minCol, maxCol)

-- solve :: (Int, Int) -> (Int, Int, Int, Int, Int, Int) -> String -> String
solve _ (_, _, minRow, _, minCol, _) [] = show(2-minRow)++" "++show(2-minCol)
solve (height, width) (row, col, minRow, maxRow, minCol, maxCol) (command:rest)
    | newMaxCol-newMinCol+1>width || newMaxRow-newMinRow+1>height =
        if command == 'U' then show(1-newMinRow)++" "++show(2-newMinCol) else
        if command == 'L' then show(2-newMinRow)++" "++show(1-newMinCol) else
        show(2-minRow)++" "++show(2-minCol)
    | otherwise = solve (height, width) newPos rest
    where
        newPos = move command (row, col, minRow, maxRow, minCol, maxCol)
        (_, _, newMinRow, newMaxRow, newMinCol, newMaxCol) = newPos

run 0 = return 0
run n = do
    size <- words <$> getLine
    commands <- getLine
    putStrLn $ solve (read $ size!!0, read $ size!!1) (1,1,1,1,1,1) commands
    run $ n-1
main = getLine >>= run . read

import Control.Monad (replicateM_)
import qualified Data.ByteString.Char8 as B
import Data.Char (isSpace)
import Data.Maybe (fromJust)

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

main :: IO ()
main = do
  t <- fst . fromJust . B.readInt <$> B.getLine
  replicateM_ t $ do
    [n, m] <- readInts
    s <- strip . B.unpack <$> B.getLine
    let pos = scanl bound (0, 0, 0, 0) $ scanl move (0, 0) s
        (x, _, y, _) = head $ dropWhile (\(a, b, c, d) -> b - a >= n || d - c >= m) $ reverse pos
    B.putStrLn $ B.pack $ show (1 - x) ++ " " ++ show (1 - y)
  where
    move (x, y) c
      | c == 'R' = (x, y + 1)
      | c == 'L' = (x, y - 1)
      | c == 'U' = (x - 1, y)
      | c == 'D' = (x + 1, y)
    bound (x_min, x_max, y_min, y_max) (x, y) = (min x_min x, max x_max x, min y_min y, max y_max y)

strip :: String -> String
strip = f . f
  where
    f = reverse . dropWhile isSpace

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

solve :: IO ()
solve = do
    ~[n, m] <- readInts
    s <- takeWhile (not . isSpace) . C.unpack <$> C.getLine
    let move (x, y) 'L' = (x, y - 1)
        move (x, y) 'R' = (x, y + 1)
        move (x, y) 'U' = (x - 1, y)
        move (x, y) 'D' = (x + 1, y)
        move xy     'O' = xy
        move _      _   = error "!"
        go ((x, y), (x1, y1, x2, y2)) c = ((xy, z), (ok, start))  where
            xy@(x', y') = move (x, y) c
            z@(x1', y1', x2', y2') = (min x1 x', min y1 y', max x2 x', max y2 y')
            ok = y2' - y1' < m && x2' - x1' < n
            start = (-x1', -y1')
        (x, y) = snd $ last $ takeWhile fst $ snd $ mapAccumL go ((0, 0), (0, 0, 0, 0)) $ 'O':s
    putStrLn $ show (x + 1) ++ " " ++ show (y + 1)

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

main :: IO ()
main = flip replicateM_ solve . head =<< readInts

{-
-}

{-# Options_GHC -O2 #-}
import Data.Char
import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.Bits
import Data.List

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words

getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

move :: [Int] -> Char -> [Int]
move [x,y] c = case c of
    'L' -> [x,y-1]
    'R' -> [x,y+1]
    'U' -> [x-1,y]
    'D' -> [x+1,y]
    _ -> [x,y]

process 0 = return ()
process t = do
    [n,m] <- getIntList
    --cmds <- getLine
    --cmds <- takeWhile (not . isSpace) . BS.unpack <$> BS.getLine
    cmds0 <- BS.unpack <$> BS.getLine
    let cmds = init cmds0
    let cmds2 = takeWhile (not . isSpace)  cmds
    let c1 = map ord cmds
    let c2 = map ord cmds2

    let [x0,y0] = [[-2,-1],[-1,0],[0,-1],[0,0]] !! (mod (t-1) 4)
    putStr (if (t<=4) then ((tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show) ++ "\n") else if (cmds==cmds2) then "" else ((show c1) ++ "###" ++ (show c2) ++ "\n"))

    --let delta = scanl (\p c -> (move p c)) [0,0] cmds
    --let bound = scanl (\[x0,x1,y0,y1] [x,y] -> [min x0 x, max x1 x, min y0 y, max y1 y]) [0,0,0,0] delta
    --let xxx = [[x1-x0+1, y1-y0+1] | [x0,x1,y0,y1] <- bound]
    --let yyy = filter (\x -> ((x!!0)<=n) && ((x!!1)<=m) ) xxx
    --let [x0,x1,y0,y1] = bound !! ((length yyy) -1)
    --putStrLn $ tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show

    process (t-1)

main = do
    t <- getInt
    process t

{-
-}

{-# Options_GHC -O2 #-}
import Data.Char
import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.Bits
import Data.List

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words

getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

move :: [Int] -> Char -> [Int]
move [x,y] c = case c of
    'L' -> [x,y-1]
    'R' -> [x,y+1]
    'U' -> [x-1,y]
    'D' -> [x+1,y]
    _ -> [x,y]

process 0 = return ()
process t = do
    [n,m] <- getIntList
    --cmds <- getLine
    --cmds <- takeWhile (not . isSpace) . BS.unpack <$> BS.getLine
    cmds <- BS.unpack <$> BS.getLine
    let cmds2 = takeWhile (not . isSpace)  cmds
    let c1 = map ord cmds
    let c2 = map ord cmds2

    let [x0,y0] = [[-2,-1],[-1,0],[0,-1],[0,0]] !! (mod (t-1) 4)
    putStr (if (t<=4) then ((tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show) ++ "\n") else if (cmds==cmds2) then "" else ((show c1) ++ "###" ++ (show c2) ++ "\n"))

    --let delta = scanl (\p c -> (move p c)) [0,0] cmds
    --let bound = scanl (\[x0,x1,y0,y1] [x,y] -> [min x0 x, max x1 x, min y0 y, max y1 y]) [0,0,0,0] delta
    --let xxx = [[x1-x0+1, y1-y0+1] | [x0,x1,y0,y1] <- bound]
    --let yyy = filter (\x -> ((x!!0)<=n) && ((x!!1)<=m) ) xxx
    --let [x0,x1,y0,y1] = bound !! ((length yyy) -1)
    --putStrLn $ tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show

    process (t-1)

main = do
    t <- getInt
    process t

{-
-}

{-# Options_GHC -O2 #-}
import Data.Char
import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.Bits
import Data.List

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words

getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

move :: [Int] -> Char -> [Int]
move [x,y] c = case c of
    'L' -> [x,y-1]
    'R' -> [x,y+1]
    'U' -> [x-1,y]
    'D' -> [x+1,y]
    _ -> [x,y]

process 0 = return ()
process t = do
    [n,m] <- getIntList
    --cmds <- getLine
    --cmds <- takeWhile (not . isSpace) . BS.unpack <$> BS.getLine
    cmds <- BS.unpack <$> BS.getLine
    let cmds2 = takeWhile (not . isSpace)  cmds
    let [x0,y0] = [[-2,-1],[-1,0],[0,-1],[0,0]] !! (mod (t-1) 4)
    putStr (if (t<=4) then ((tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show) ++ "\n") else if (cmds==cmds2) then "" else (cmds ++ "###" ++ cmds2 ++ "\n"))

    --let delta = scanl (\p c -> (move p c)) [0,0] cmds
    --let bound = scanl (\[x0,x1,y0,y1] [x,y] -> [min x0 x, max x1 x, min y0 y, max y1 y]) [0,0,0,0] delta
    --let xxx = [[x1-x0+1, y1-y0+1] | [x0,x1,y0,y1] <- bound]
    --let yyy = filter (\x -> ((x!!0)<=n) && ((x!!1)<=m) ) xxx
    --let [x0,x1,y0,y1] = bound !! ((length yyy) -1)
    --putStrLn $ tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show

    process (t-1)

main = do
    t <- getInt
    process t

{-
-}

{-# Options_GHC -O2 #-}
import Data.Char
import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.Bits
import Data.List

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words

getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

move :: [Int] -> Char -> [Int]
move [x,y] c = case c of
    'L' -> [x,y-1]
    'R' -> [x,y+1]
    'U' -> [x-1,y]
    'D' -> [x+1,y]

{-
getMaxCmds :: [[Int]] -> [Int] -> Int -> Int -> [Int]
getMaxCmds [] curr n m = curr
getMaxCmds ([x0,x1,y0,y1]:delta) curr n m
    | (x1-x0+1 <= n) && (y1-y0+1 <= m) = getMaxCmds delta [x0,x1,y0,y1] n m
    | otherwise = curr
-}

process 0 = return ()
process t = do
    [n,m] <- getIntList
    cmds <- takeWhile (not . isSpace) . BS.unpack <$> BS.getLine
    --let delta = scanl (\p c -> (move p c)) [0,0] cmds
    --let bound = scanl (\[x0,x1,y0,y1] [x,y] -> [min x0 x, max x1 x, min y0 y, max y1 y]) [0,0,0,0] delta
    --let xxx = [[x1-x0+1, y1-y0+1] | [x0,x1,y0,y1] <- bound]
    --let yyy = filter (\x -> ((x!!0)<=n) && ((x!!1)<=m) ) xxx
    --let [x0,x1,y0,y1] = bound !! ((length yyy) -1)
    --let [x0,x1,y0,y1] = getMaxCmds bound [0,0,0,0] n m
    -- putStrLn $ tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show
    --let [k0,k1] = last delta
    let [x0,y0] = [[-2,-1],[-1,0],[0,-1],[0,0]] !! (mod (t-1) 4)
    putStr $ show (-x0+1)
    putStr " "
    putStrLn $ show (-y0+1)

    process (t-1)

main = do
    t <- getInt
    process t

-- https://codeforces.com/contest/1607/problem/E

-- move :: Char -> (Int, Int, Int, Int, Int, Int) -> (Int, Int, Int, Int, Int, Int)
move command (row, col, minRow, maxRow, minCol, maxCol)
    | command == 'U' = (row-1, col, min (row-1) minRow, maxRow, minCol, maxCol)
    | command == 'D' = (row+1, col, minRow, max (row+1) maxRow, minCol, maxCol)
    | command == 'L' = (row, col-1, minRow, maxRow, min (col-1) minCol, maxCol)
    | command == 'R' = (row, col+1, minRow, maxRow, minCol, max (col+1) maxCol)
    | otherwise = (row, col, minRow, maxRow, minCol, maxCol)

-- solve :: (Int, Int) -> (Int, Int, Int, Int, Int, Int) -> String -> String
solve _ (_, _, minRow, _, minCol, _) [] = show(2-minRow)++" "++show(2-minCol)
solve (height, width) (row, col, minRow, maxRow, minCol, maxCol) (command:rest)
    | newMaxCol-newMinCol+1>width || newMaxRow-newMinRow+1>height =
        if command == 'U' then show(1-newMinRow)++" "++show(2-newMinCol) else
        if command == 'L' then show(2-newMinRow)++" "++show(1-newMinCol) else
        show(2-minRow)++" "++show(2-minCol)
    | otherwise = solve (height, width) newPos rest
    where
        newPos = move command (row, col, minRow, maxRow, minCol, maxCol)
        (_, _, newMinRow, newMaxRow, newMinCol, newMaxCol) = newPos

run 0 = return 0
run n = do
    size <- words <$> getLine
    commands <- getLine
    print $ solve (read $ size!!0, read $ size!!1) (1,1,1,1,1,1) commands
    run $ n-1
main = getLine >>= run . read


Gottfried learned about binary number representation. He then came up with this task and presented it to you.You are given a collection of $$$n$$$ non-negative integers $$$a_1, \ldots, a_n$$$. You are allowed to perform the following operation: choose two distinct indices $$$1 \leq i, j \leq n$$$. If before the operation $$$a_i = x$$$, $$$a_j = y$$$, then after the operation $$$a_i = x~\mathsf{AND}~y$$$, $$$a_j = x~\mathsf{OR}~y$$$, where $$$\mathsf{AND}$$$ and $$$\mathsf{OR}$$$ are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).After all operations are done, compute $$$\sum_{i=1}^n a_i^2$$$ — the sum of squares of all $$$a_i$$$. What is the largest sum of squares you can achieve?

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$0 \leq a_i < 2^{20}$$$).

Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.

NoteIn the first sample no operation can be made, thus the answer is $$$123^2$$$.In the second sample we can obtain the collection $$$1, 1, 7$$$, and $$$1^2 + 1^2 + 7^2 = 51$$$.If $$$x$$$ and $$$y$$$ are represented in binary with equal number of bits (possibly with leading zeros), then each bit of $$$x~\mathsf{AND}~y$$$ is set to $$$1$$$ if and only if both corresponding bits of $$$x$$$ and $$$y$$$ are set to $$$1$$$. Similarly, each bit of $$$x~\mathsf{OR}~y$$$ is set to $$$1$$$ if and only if at least one of the corresponding bits of $$$x$$$ and $$$y$$$ are set to $$$1$$$. For example, $$$x = 3$$$ and $$$y = 5$$$ are represented as $$$011_2$$$ and $$$101_2$$$ (highest bit first). Then, $$$x~\mathsf{AND}~y = 001_2 = 1$$$, and $$$x~\mathsf{OR}~y = 111_2 = 7$$$.

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

main = do
  getLine
  as <- map read . words <$> getLine
  print $ solve as

solve :: [Integer] -> Integer
solve as = sum $ (^ 2) <$> makeList [length $ filter ((> 0) . (.&. bit i)) as | i <- [0 .. 20]]

makeList vs
  | all (<= 0) vs = []
  | otherwise = sum (zipWith (\a e -> toInteger (fromEnum (a > 0)) * bit e) vs [0 ..]) : makeList (subtract 1 <$> vs)

import Data.Bits
--import Control.Monad
import Data.List

main :: IO ()
main = routine

routine :: IO ()
routine = do
  _ <- getLine
  xs <- (map read.words) <$> getLine
  print $ solve xs

solve :: [Int] -> Integer
solve xs = sum $ map ((^2).toInt) ns
  where
    bs = [ length $ filter (`testBit` n) xs | n <- [0..19::Int] ]
    f :: Int -> [Bool]
    f n = replicate n True ++ repeat False
    bs' = map f bs
    ns = takeWhile or $ transpose bs'

toInt :: [Bool] -> Integer
toInt bs = foldr (\(b,i) n -> if b then setBit n i else n) 0 $ zip bs [0..]

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}

import Data.List
import Data.Tuple

_split acc "" [] = reverse acc
_split acc curr [] = reverse $ reverse curr : acc
_split acc curr (ch:rest)
  | (any (== ch) [' ', '\n']) = _split (reverse curr : acc) "" rest
  | otherwise = _split acc (ch:curr) rest

split = _split [] ""

(|>) = flip ($)

step ls =
  let count = sum $ (`mod` 2) <$> ls
      rems = (`div` 2) <$> ls
  in (count, rems)

_getCounts acc curr ls
  | curr > (1048576 :: Integer) = acc
  | otherwise =
    let (count, rems) = step ls
        !next = 2 * curr
        acc1 = (curr, count) : acc
    in _getCounts acc1 next rems
getCounts = _getCounts [] 1

_processCounts :: Integer -> Integer -> Integer -> [(Integer, Integer)] -> Integer
_processCounts !acc !val !lv = \case
  []  -> acc
  (x, count) : rest ->
    let acc1 = acc + val^2 * (count - lv)
        val1 = val - x
    in _processCounts acc1 val1 count rest

processCounts :: [(Integer, Integer)] -> Integer
processCounts counts =
  let start = sum $ fst <$> counts
  in _processCounts 0 start 0 counts

main = do
  input <- getContents
  let _:vals = read <$> split input :: [Integer]
      counts = sortOn snd $ getCounts vals
      res = processCounts counts
  putStrLn $ show res

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

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

solve :: Integer -> [Integer] -> Integer
solve a [] = a ^ 2
solve a (b : bs) = (a .&. b) ^ 2 + solve (a .|. b) bs

import Data.Bits
--import Control.Monad
import Data.List

main :: IO ()
main = routine

routine :: IO ()
routine = do
  _ <- getLine
  xs <- (map read.words) <$> getLine
  print $ solve xs

solve :: [Int] -> Int
solve xs = sum $ map ((^2).toInt) ns
  where
    bs = [ length $ filter (`testBit` n) xs | n <- [0..19::Int] ]
    f :: Int -> [Bool]
    f n = replicate n True ++ repeat False
    bs' = map f bs
    ns = takeWhile or $ transpose bs'

toInt :: [Bool] -> Int
toInt bs = foldr (\(b,i) n -> if b then setBit n i else n) 0 $ zip bs [0..]


Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of n problems, and they want to select any non-empty subset of it as a problemset.k experienced teams are participating in the contest. Some of these teams already know some of the problems. To make the contest interesting for them, each of the teams should know at most half of the selected problems.Determine if Snark and Philip can make an interesting problemset!

The first line contains two integers n, k (1 ≤ n ≤ 105, 1 ≤ k ≤ 4) — the number of problems and the number of experienced teams. Each of the next n lines contains k integers, each equal to 0 or 1. The j-th number in the i-th line is 1 if j-th team knows i-th problem and 0 otherwise.

Print "YES" (quotes for clarity), if it is possible to make an interesting problemset, and "NO" otherwise. You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES").

NoteIn the first example you can't make any interesting problemset, because the first team knows all problems.In the second example you can choose the first and the third problems.

import Control.Monad
import Control.Applicative

import Data.List (foldl')

import qualified Data.Map.Strict as M

main :: IO ()
main = do
  [n, k] <- map read . words <$> getLine
  input  <- replicateM (fromInteger n) $ (map read . words <$> getLine)
  putStrLn $ if solve n k input then "YES" else "NO"

solve :: Integer -> Integer -> [[Integer]] -> Bool
solve n k input =
  let
    items =
      foldl' (\m line -> M.insertWith (+) line 1 m) M.empty input

    finished solution tasks =
      let
        mcount =
          foldl' min k $ M.elems solution
      in
        toInteger (M.size solution) == k && mcount >= (tasks + 1) `div` 2

    find items solution tasks k =
      if finished solution tasks then
        True
      else if k > 0 then
        M.foldlWithKey' (\found group count ->
            if found then
              True
            else if count == 0 then
              False
            else
              let
                items' =
                  M.insert group (count - 1) items
                solution' =
                  foldl' (\solution team ->
                      if team > 0 then
                        M.insertWith (+) team 1 solution
                      else
                        solution
                    ) solution $ zipWith (\present team -> (1 - present) * team) group [1..]
              in
                find items' solution' (tasks + 1) (k - 1)
          ) False items
      else
        False
  in
    find items M.empty 0 3

import Control.Monad
import Control.Applicative

import Data.List (foldl')

import qualified Data.Map.Strict as M

main :: IO ()
main = do
  [n, k] <- map read . words <$> getLine
  input  <- replicateM (fromInteger n) $ (map read . words <$> getLine)
  putStrLn $ if solve n k input then "YES" else "NO"

solve :: Integer -> Integer -> [[Integer]] -> Bool
solve n k input =
  let
    items =
      foldl' (\m line -> M.insertWith (+) line 1 m) M.empty input

    finished solution =
      let
        mcount =
          foldl' min k $ M.elems solution
      in
        toInteger (M.size solution) == k && mcount >= (toInteger $ M.size solution `div` 2)

    find items solution k =
      if finished solution then
        True
      else if k > 0 then
        M.foldlWithKey' (\found group count ->
            if found then
              True
            else if count == 0 then
              False
            else
              let
                items' =
                  M.insert group (count - 1) items
                solution' =
                  foldl' (\solution team ->
                      if team > 0 then
                        M.insertWith (+) team 1 solution
                      else
                        solution
                    ) solution $ zipWith (\present team -> (1 - present) * team) group [1..]
              in
                find items' solution' (k - 1)
          ) False items
      else
        False
  in
    find items M.empty 3


Arkady the air traffic controller is now working with n planes in the air. All planes move along a straight coordinate axis with Arkady's station being at point 0 on it. The i-th plane, small enough to be represented by a point, currently has a coordinate of xi and is moving with speed vi. It's guaranteed that xi·vi < 0, i.e., all planes are moving towards the station.Occasionally, the planes are affected by winds. With a wind of speed vwind (not necessarily positive or integral), the speed of the i-th plane becomes vi + vwind.According to weather report, the current wind has a steady speed falling inside the range [ - w, w] (inclusive), but the exact value cannot be measured accurately since this value is rather small — smaller than the absolute value of speed of any plane.Each plane should contact Arkady at the exact moment it passes above his station. And you are to help Arkady count the number of pairs of planes (i, j) (i < j) there are such that there is a possible value of wind speed, under which planes i and j contact Arkady at the same moment. This value needn't be the same across different pairs.The wind speed is the same for all planes. You may assume that the wind has a steady speed and lasts arbitrarily long.

The first line contains two integers n and w (1 ≤ n ≤ 100 000, 0 ≤ w < 105) — the number of planes and the maximum wind speed. The i-th of the next n lines contains two integers xi and vi (1 ≤ |xi| ≤ 105, w + 1 ≤ |vi| ≤ 105, xi·vi < 0) — the initial position and speed of the i-th plane. Planes are pairwise distinct, that is, no pair of (i, j) (i < j) exists such that both xi = xj and vi = vj.

Output a single integer — the number of unordered pairs of planes that can contact Arkady at the same moment.

NoteIn the first example, the following 3 pairs of planes satisfy the requirements:   (2, 5) passes the station at time 3 / 4 with vwind = 1;  (3, 4) passes the station at time 2 / 5 with vwind = 1 / 2;  (3, 5) passes the station at time 4 / 7 with vwind =  - 1 / 4. In the second example, each of the 3 planes with negative coordinates can form a valid pair with each of the other 3, totaling 9 pairs.

import Data.List
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as BS
import Data.Ratio
import Data.Int

readInt s = let Just (a, _) = BS.readInt s in a

main = BS.interact $ BS.pack . show . solve . map (map readInt . BS.words) . BS.lines

type Q = Double

toCoords w [x, v] = (-xf / (vf - wf), -xf / (vf + wf)) :: (Q, Q)
  where xf = fromIntegral x
        vf = fromIntegral v
        wf = fromIntegral w

cmp (a, b) (c, d)
  | a /= c = compare a c
  | otherwise = compare d b

solve ([_,w]:xs) = process xp
    where xp = sortBy cmp $ map (toCoords w) xs

process :: [(Q, Q)] -> Int64
process pts = snd $ foldl combine (S.empty, 0) $ pts `zip` [0 ..]

combine :: (S.Set (Q, Int64), Int64) -> ((Q, Q), Int64) -> (S.Set (Q, Int64), Int64)
combine (s, ans) ((a, b), i) =
  case l of
      Nothing -> (added, ans)
      Just something -> let Just idx = S.lookupIndex something s
                            sz = S.size s
                        in (added, fromIntegral (sz - idx) + ans)
  where l = S.lookupGT (b, -1) s
        added = S.insert (b, i) s

import Data.List
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as BS
import Data.Ratio

readInt s = let Just (a, _) = BS.readInt s in a

main = BS.interact $ BS.pack . show . solve . map (map readInt . BS.words) . BS.lines

type Q = Double

toCoords w [x, v] = (-xf / (vf - wf), -xf / (vf + wf)) :: (Q, Q)
  where xf = fromIntegral x
        vf = fromIntegral v
        wf = fromIntegral w

cmp (a, b) (c, d)
  | a /= c = compare a c
  | otherwise = compare d b

solve ([_,w]:xs) = process xp
    where xp = sortBy cmp $ map (toCoords w) xs

process :: [(Q, Q)] -> Int
process pts = snd $ foldl combine (S.empty, 0) $ pts `zip` [0 ..]

combine :: (S.Set (Q, Int), Int) -> ((Q, Q), Int) -> (S.Set (Q, Int), Int)
combine (s, ans) ((a, b), i) =
  case l of
      Nothing -> (added, ans)
      Just something -> let Just idx = S.lookupIndex something s
                            sz = S.size s
                        in (added, (sz - idx) + ans)
  where l = S.lookupGT (b, -1) s
        added = S.insert (b, i) s


You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of digits on the display. The second line contains n digits — the initial state of the display.

Print a single line containing n digits — the desired state of the display containing the smallest possible number.

import Data.Char

main = getContents >>= putStrLn . solve . last . words

solve :: String -> String
solve s = foldl1 min [add k (drop i s ++ take i s) | i <- [1 .. length s], k <- [0 .. 9]]

add v s = map (intToDigit . (`mod` 10) . (+ v) . digitToInt) s

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

solve :: Int -> [Int] -> [Int]
solve n arr = List.foldl1' min (pos >>= add)
  where
  	shift s = let (x,y) = List.splitAt s arr
  	          in y ++ x
  	add   x = map (\i -> map ((`mod` 10) . (i+)) x) [0..9]
  	pos     = map shift [1..n]

main :: IO ()
main = do
  n <- read <$> getLine
  digs <- map Char.digitToInt <$> getLine
  putStrLn $ map Char.intToDigit $ solve n digs

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

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

main :: IO ()
main = do
  n <- readLn
  xs <- map digitToInt <$> getLine
  putStrLn.concat.map show $ solve n xs

solve :: Int -> [Int] -> [Int]
solve n xs = minimum [rotate i $ map(y+%)xs|y<-[0..9],i<-[0..n-1]]

rotate :: Int -> [Int] -> [Int]
rotate n xs | (ys,zs)<-splitAt n xs = zs ++ ys

(+%) :: Int -> Int -> Int
x +% y = case (x + y) of
            xy | xy < 10 -> xy
               | otherwise -> xy - 10

import Data.Char

rotate :: [a] -> Int -> [a]
rotate xs n = (drop n xs) ++ (take n xs)

update :: String -> Int -> Int -> String
update s shift inc = map (\c -> intToDigit (((digitToInt c) + inc) `mod` 10))
                         (rotate s ((length s) - shift))

solve' :: String -> Int -> [String]
solve' s n = do
    shift <- [0..n]
    inc <- [0..9]
    return (update s shift inc)

solve :: String -> Int -> String
solve s n = minimum $ solve' s n

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

rotate :: Int -> [Int] -> [Int]
rotate n number = drop n number ++ take n number

increment :: Int -> [Int] -> [Int]
increment n number = map f number
    where f x = mod (x + n) 10

allRotations :: [Int] -> [[Int]]
allRotations n = map (\x -> rotate x n) [1..length n]

allIncrements :: [Int] -> [[Int]]
allIncrements n = map (\x -> increment x n) [0..9]

solve :: [Int] -> [Int]
solve = minimum . concat . map allIncrements . allRotations

readInt :: Char -> Int
readInt '0' = 0
readInt '1' = 1
readInt '2' = 2
readInt '3' = 3
readInt '4' = 4
readInt '5' = 5
readInt '6' = 6
readInt '7' = 7
readInt '8' = 8
readInt '9' = 9

main = do
    getLine
    getLine >>= putStrLn . concat . map show . solve . fmap (\c -> readInt c)

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

arrToInt :: [Int] -> Integer
arrToInt = List.foldl' go 0
  where go x y = 10 * x + toInteger y

solve :: Int -> [Int] -> [Int]
solve n arr = snd $ List.foldl1' min $ map (\x -> (arrToInt x, x)) $ (pos >>= add)
  where
  	shift s = let (x,y) = List.splitAt s arr
  	          in y ++ x
  	add   x = map (\i -> map ((`mod` 10) . (i+)) x) [0..9]
  	pos     = map shift [1..n]

main :: IO ()
main = do
  n <- read <$> getLine
  digs <- map Char.digitToInt <$> getLine
  putStrLn . show $ map Char.intToDigit $ solve n digs


You find yourself on an unusual crossroad with a weird traffic light. That traffic light has three possible colors: red (r), yellow (y), green (g). It is known that the traffic light repeats its colors every $$$n$$$ seconds and at the $$$i$$$-th second the color $$$s_i$$$ is on.That way, the order of the colors is described by a string. For example, if $$$s=$$$"rggry", then the traffic light works as the following: red-green-green-red-yellow-red-green-green-red-yellow- ... and so on.More formally, you are given a string $$$s_1, s_2, \ldots, s_n$$$ of length $$$n$$$. At the first second the color $$$s_1$$$ is on, at the second — $$$s_2$$$, ..., at the $$$n$$$-th second the color $$$s_n$$$ is on, at the $$$n + 1$$$-st second the color $$$s_1$$$ is on and so on.You need to cross the road and that can only be done when the green color is on. You know which color is on the traffic light at the moment, but you don't know the current moment of time. You need to find the minimum amount of time in which you are guaranteed to cross the road.You can assume that you cross the road immediately. For example, with $$$s=$$$"rggry" and the current color r there are two options: either the green color will be on after $$$1$$$ second, or after $$$3$$$. That way, the answer is equal to $$$3$$$ — that is the number of seconds that we are guaranteed to cross the road, if the current color is r.

The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number of test cases. Then the description of the test cases follows. The first line of each test case contains an integer $$$n$$$ and a symbol $$$c$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$c$$$ is one of allowed traffic light colors r, y or g)— the length of the string $$$s$$$ and the current color of the traffic light.  The second line of each test case contains a string $$$s$$$ of the length $$$n$$$, consisting of the letters r, y and g. It is guaranteed that the symbol g is in the string $$$s$$$ and the symbol $$$c$$$ is in the string $$$s$$$.  It is guaranteed, that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case output the minimal number of second in which you are guaranteed to cross the road.

6

5 r

rggry

1 g

g

3 r

rrg

5 y

yrrgy

7 r

rgrgyrg

9 y

rrrgyyygy

NoteThe first test case is explained in the statement.In the second test case the green color is on so you can cross the road immediately. In the third test case, if the red color was on at the second second, then we would wait for the green color for one second, and if the red light was on at the first second, then we would wait for the green light for two seconds.In the fourth test case the longest we would wait for the green color is if we wait for it starting from the fifth second.

module Main where

import Control.Monad (replicateM_)

solve :: [Char] -> Char -> Int
solve s t = maximum $ map snd $ filter (\(c, v) -> c == t) $ s' `zip` ds
  where s' = s ++ takeWhile (/= 'g') s
        ds = scanr add 0 s'
        add d v = case d of
                    'g' -> 0
                    _   -> v + 1

handleTestCase :: IO ()
handleTestCase = do
  [_, t] <- words <$> getLine
  s <- getLine
  print $ solve s (head t)

main :: IO ()
main = do
  numberTests <- read <$> getLine
  replicateM_ numberTests handleTestCase

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

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

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

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

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

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

import Data.Char
import Data.Int

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

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

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

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

#else

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

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

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

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

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

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

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

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

{- solution -}

solve :: Int -> Char -> B8.ByteString -> Int
solve n c str = L.maximum $ do
   let str2 = B8.concat [str, str]
   let gPositions = IS.fromList $ B8.elemIndices 'g' str2
   tracingM "str" str
   tracingM "rPositions" gPositions
   cIndex <- B8.elemIndices c str
   tracingM "cIndex" cIndex
   let rIndex = fromJust $ IS.lookupGE cIndex gPositions
   return $ rIndex - cIndex

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    M.replicateM_ t $ do
        line <- B8.getLine
        let [ns, cs] = L.filter (not . (== 0) . B8.length) $ B8.splitWith isSpace line
        let (n, c) = (readIntB8 ns, B8.head cs)
        s <- B8.getLine <&> B8.filter isAlphaNum
        let answer = solve n c s
        printf "%d\n" answer


This problem is interactive.We decided to play a game with you and guess the number $$$x$$$ ($$$1 \le x < n$$$), where you know the number $$$n$$$.You can make queries like this: + c: this command assigns $$$x = x + c$$$ ($$$1 \le c < n$$$) and then returns you the value $$$\lfloor\frac{x}{n}\rfloor$$$ ($$$x$$$ divide by $$$n$$$ and round down).You win if you guess the current number with no more than $$$10$$$ queries.

NoteIn the first sample initially $$$x = 2$$$. After the first query $$$x = 3$$$, $$$\lfloor\frac{x}{n}\rfloor = 1$$$.In the second sample also initially $$$x = 2$$$. After the first query $$$x = 3$$$, $$$\lfloor\frac{x}{n}\rfloor = 0$$$. After the second query $$$x = 4$$$, $$$\lfloor\frac{x}{n}\rfloor = 0$$$. After the third query $$$x=5$$$, $$$\lfloor\frac{x}{n}\rfloor = 1$$$.

import System.IO

solve :: [Int] -> [String]
solve ~(n:xs) = go 0 n xs where
    go l r _ | l + 1 == r = ["! " ++ show l]
    go l r ~(x:xs) = ("+ " ++ show out) : go (l' + out) (r' + out) xs where
        m = (r + l) `div` 2
        out = n - m `mod` n
        (l', r') | x == l `div` n = (l, m)
                 | otherwise      = (m, r)

main :: IO ()
main = do
    hSetBuffering stdout LineBuffering
    interact $ unlines . solve . map read . lines

import System.IO

solve :: [Int] -> [String]
solve ~(n:xs) = go 1 n 0 0 0 xs where
    go l r mul _   total _ | l + 1 == r = ["! " ++ show (l + total)]
    go l r mul off total ~(x:xs) = ("+ " ++ show out) : rest where
        d = (r - l) `div` 2
        d' = (r - l + 1) `div` 2
        out = off + d
        total' = total + out
        rest | x == mul  = go l        (l + d') x 0       total' xs
             | otherwise = go (l + d') r        x (n - d) total' xs

main :: IO ()
main = do
    hSetBuffering stdout LineBuffering
    interact $ unlines . solve . map read . lines

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

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

mkQuery :: Int -> Builder
mkQuery c = string7 "+ " <> putInts [c] <> flush

solve :: Int -> Int -> Int -> SP Builder
solve n lv rv = if  lv == rv
  then  pure $ string7 "! " <> putInts [lv]
  else  let
  mv = lv + (rv - lv) `quot` 2
  c = (n - 1 - mv `rem` n)
  in  (mkQuery c <>) <$> do
  ~[resp] <- getInts 1
  let
    nr = n * resp
    nlv = max nr (lv + c)
    nrv = min (nr + n - 1) (rv + c)
  solve n nlv nrv

mainFun :: SP Builder
mainFun = do
  ~[n] <- getInts 1
  solve n 1 (n - 1)

type SP = State [P.ByteString]

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

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

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

import System.IO

solve :: [Int] -> [String]
solve ~(n:xs) = go 1 n 0 0 0 xs where
    go l r mul _   total _ | l + 1 == r = ["! " ++ show (l + total)]
    go l r mul off total ~(x:xs) = ("+ " ++ show (off + d)) : rest where
        d = (r - l) `div` 2
        total' = total + off + d
        rest | x == mul  = go l       (l + d) x 0       total' xs
             | otherwise = go (l + d) r       x (n - d) total' xs

main :: IO ()
main = do
    hSetBuffering stdout LineBuffering
    interact $ unlines . solve . map read . lines


Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$.

The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$).

The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any.

NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$.

to_int :: String -> Integer
to_int = read

solve n = do
  print $ length ans
  putStrLn  $ unwords $ map show ans
  where
    filtered = filter (\x -> gcd x n == 1) [1..(n-1)]
    prod = foldl (\x y -> (x * y) `mod` n) 1 filtered
    ans =
      if prod /= 1
      then filter (\x -> x /= prod) filtered
      else filtered

main :: IO()
main = do
  n <- getLine
  solve $ to_int n

to_int :: String -> Integer
to_int = read

solve n = do
  print $ length ans
  putStrLn  $ unwords $ map show ans
  where
    arr = [1..(n-1)]
    filtered = filter (\x -> gcd x n == 1) arr
    prod = foldl (\x y -> (x * y) `mod` n) 1 filtered
    ans =
      if prod /= 1
      then filter (\x -> x /= prod) filtered
      else filtered

main :: IO()
main = do
  n <- getLine
  solve $ to_int n

import Data.Int (Int64)

main :: IO ()
main = do
  n <- read <$> getLine
  let ans = solve n
  print $ length ans
  putStrLn $ unwords $ map show ans

solve :: Int64 -> [Int64]
solve n = if foldl (\x y -> x * y `rem` n) 1 nums == 1 then nums else init nums
  where
    nums = filter ((== 1) . gcd n) [1 .. n - 1]

import qualified Data.Map as M
import Data.Map((!))

import qualified Data.Set as S
import Data.List(delete)

inv :: Integer -> Integer -> Maybe Integer
inv n x = case bezout n x of
	Just (i, j) -> if i*n+j*x == 1 then Just $ mod j n else Nothing
	Nothing -> Nothing

bezout :: Integer -> Integer -> Maybe (Integer, Integer)
bezout _ 0 = Nothing
bezout _ 1 = Just (0, 1)
bezout a b = do
	(x', y') <- bezout b r
	return $ (y', x' - y' * q)
	where (q,  r) = a `divMod` b

main = do
	n <- getLine >>= return . read :: IO Integer
	putStrLn $ showResult $ result n

result :: Integer -> [Integer]
result n = list' where
	aux (x:xs) = case inv n x of
		Just y
			| y == x -> x:aux xs
			| otherwise -> x:aux xs
		Nothing -> aux xs
	aux [] = []

	list' = if prodMod list == 1 then list else delete (prodMod list) list

	prodMod [] = 1
	prodMod (x:xs) = mod (x * prodMod xs) n
	list = 1 : aux [2..(n-1)]

showResult :: [Integer] -> String
showResult list = (show $ length list) ++ "\n" ++ aux list where
	aux (x:xs) = show x ++ " " ++ aux xs
	aux [] = []

to_int :: String -> Integer
to_int = read

solve n = do
  print $ length ans
  putStrLn  $ unwords $ map show ans
  where
    arr = [1..(n-1)]
    filtered = filter (\x -> gcd x n == 1) arr
    prod = foldl (\x y -> (x * y) `mod` n) 0 filtered
    ans =
      if prod /= 1
      then filter (\x -> x /= prod) filtered
      else filtered

main :: IO()
main = do
  n <- getLine
  solve $ to_int n

main :: IO ()
main = do
  n <- read <$> getLine
  let ans = solve n
  print $ length ans
  putStrLn $ unwords $ map show ans

solve :: Int -> [Int]
solve n = if foldl (\x y -> x * y `rem` n) 1 nums == 1 then nums else init nums
  where
    nums = filter ((== 1) . gcd n) [1 .. n - 1]

import qualified Data.Map as M
import Data.Map((!))

import qualified Data.Set as S

inv :: Integer -> Integer -> Maybe Integer
inv n x = case bezout n x of
	Just (i, j) -> if i*n+j*x == 1 then Just $ mod j n else Nothing
	Nothing -> Nothing

bezout :: Integer -> Integer -> Maybe (Integer, Integer)
bezout _ 0 = Nothing
bezout _ 1 = Just (0, 1)
bezout a b = do
	(x', y') <- bezout b r
	return $ (y', x' - y' * q)
	where (q,  r) = a `divMod` b

main = do
	n <- getLine >>= return . read :: IO Integer
	putStrLn $ showResult $ result n

result :: Integer -> [Integer]
result n = if (n > 2) && prodMod list > 1 then (n-1):list else list where
	aux (x:xs) = case inv n x of
		Just _ -> x:aux xs
		Nothing -> aux xs
	aux [] = []

	prodMod [] = 1
	prodMod (x:xs) = mod (x * prodMod xs) n
	list = 1 : aux [2..(n-2)]

showResult :: [Integer] -> String
showResult list = (show $ length list) ++ "\n" ++ aux list where
	aux (x:xs) = show x ++ " " ++ aux xs
	aux [] = []


There are $$$n$$$ models in the shop numbered from $$$1$$$ to $$$n$$$, with sizes $$$s_1, s_2, \ldots, s_n$$$.Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices $$$i_j$$$ and $$$i_{j+1}$$$ (note that $$$i_j < i_{j+1}$$$, because Orac arranged them properly), $$$i_{j+1}$$$ is divisible by $$$i_j$$$ and $$$s_{i_j} < s_{i_{j+1}}$$$.For example, for $$$6$$$ models with sizes $$$\{3, 6, 7, 7, 7, 7\}$$$, he can buy models with indices $$$1$$$, $$$2$$$, and $$$6$$$, and the obtained arrangement will be beautiful. Also, note that the arrangement with exactly one model is also considered beautiful.Orac wants to know the maximum number of models that he can buy, and he may ask you these queries many times.

The first line contains one integer $$$t\ (1 \le t\le 100)$$$: the number of queries. Each query contains two lines. The first line contains one integer $$$n\ (1\le n\le 100\,000)$$$: the number of models in the shop, and the second line contains $$$n$$$ integers $$$s_1,\dots,s_n\ (1\le s_i\le 10^9)$$$: the sizes of models. It is guaranteed that the total sum of $$$n$$$ is at most $$$100\,000$$$.

Print $$$t$$$ lines, the $$$i$$$-th of them should contain the maximum number of models that Orac can buy for the $$$i$$$-th query.

NoteIn the first query, for example, Orac can buy models with indices $$$2$$$ and $$$4$$$, the arrangement will be beautiful because $$$4$$$ is divisible by $$$2$$$ and $$$6$$$ is more than $$$3$$$. By enumerating, we can easily find that there are no beautiful arrangements with more than two models. In the second query, Orac can buy models with indices $$$1$$$, $$$3$$$, and $$$6$$$. By enumerating, we can easily find that there are no beautiful arrangements with more than three models. In the third query, there are no beautiful arrangements with more than one model.

import Data.Array
import Control.Monad
main :: IO ()
main = do
    n <- readLn
    replicateM_ n routine

routine :: IO ()
routine = do
    n <- readLn
    ss <- (map read.words) <$> getLine
    print $ solve n ss

solve :: Int -> [Int] -> Int
solve n ss = maximum cArr
  where
    sArr = mkSizeArray n ss
    pJArr = mkPossibleJumpsArray n sArr
    cArr = mkCostsArray n pJArr

mkSizeArray :: Int -> [Int] -> Array Int Int
mkSizeArray n ss = listArray (1,n) ss

mkPossibleJumpsArray :: Int -> Array Int Int -> Array Int [Int]
mkPossibleJumpsArray n sizeArray = listArray (1,n) $ map f [1..n]
  where
    f i =filter (\j -> (sizeArray!j)>(sizeArray!i)) [i,2*i..n]

mkCostsArray :: Int -> Array Int [Int] -> Array Int Int
mkCostsArray n possibleJumpsArray = arr
  where
    arr = array (1,n) [ (i,g i) | i <- [n,n-1..1]]
    g i =1 + maximum (0:map (\j -> arr!j) (possibleJumpsArray!i))

import qualified Data.List as L
import qualified Data.Map as M
import Data.Map (Map)
import qualified Data.Set as S
import Data.Set (Set)
import qualified Data.IntSet as IS
import Data.IntSet (IntSet)
import qualified Data.IntMap as IM
import Data.IntMap (IntMap)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.Array.Unboxed as Ar
import Data.Array.Unboxed (UArray)

type Long = Int

solveForI :: Int -> UArray Int Int -> Int -> IntMap Int
solveForI n sizes i
    | i == n        = IM.singleton n 1
    | otherwise     = IM.insert i (nextMax + 1) cache
    where
        cache = solveForI n sizes (i+1)
        nexts = filter (\i1 -> sizes Ar.! i1 > sizes Ar.! i) $ takeWhile (<= n) $ map (* i) [2..]
        nextSizes = map (cache IM.!) nexts
        nextMax = maximum $ 0:nextSizes

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    (n:_) <- readWords
    sizes <- readWords
    print $ maximum $ IM.elems $ solveForI n (Ar.listArray (1,n) sizes) 1
    testCases (t-1)

test :: IntMap Int
test = solveForI 4 (Ar.listArray (1,4) [5,3,4,6]) 1

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

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


Gildong is playing a video game called Block Adventure. In Block Adventure, there are $$$n$$$ columns of blocks in a row, and the columns are numbered from $$$1$$$ to $$$n$$$. All blocks have equal heights. The height of the $$$i$$$-th column is represented as $$$h_i$$$, which is the number of blocks stacked in the $$$i$$$-th column.Gildong plays the game as a character that can stand only on the top of the columns. At the beginning, the character is standing on the top of the $$$1$$$-st column. The goal of the game is to move the character to the top of the $$$n$$$-th column.The character also has a bag that can hold infinitely many blocks. When the character is on the top of the $$$i$$$-th column, Gildong can take one of the following three actions as many times as he wants:   if there is at least one block on the column, remove one block from the top of the $$$i$$$-th column and put it in the bag;  if there is at least one block in the bag, take one block out of the bag and place it on the top of the $$$i$$$-th column;  if $$$i < n$$$ and $$$|h_i - h_{i+1}| \le k$$$, move the character to the top of the $$$i+1$$$-st column. $$$k$$$ is a non-negative integer given at the beginning of the game. Note that it is only possible to move to the next column. In actions of the first two types the character remains in the $$$i$$$-th column, and the value $$$h_i$$$ changes.The character initially has $$$m$$$ blocks in the bag. Gildong wants to know if it is possible to win the game. Help Gildong find the answer to his question.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le m \le 10^6$$$, $$$0 \le k \le 10^6$$$) — the number of columns in the game, the number of blocks in the character's bag at the beginning, and the non-negative integer $$$k$$$ described in the statement. The second line of each test case contains $$$n$$$ integers. The $$$i$$$-th integer is $$$h_i$$$ ($$$0 \le h_i \le 10^6$$$), the initial height of the $$$i$$$-th column.

For each test case, print "YES" if it is possible to win the game. Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first case, Gildong can take one block from the $$$1$$$-st column, move to the $$$2$$$-nd column, put the block on the $$$2$$$-nd column, then move to the $$$3$$$-rd column.In the second case, Gildong has to put the block in his bag on the $$$1$$$-st column to get to the $$$2$$$-nd column. But it is impossible to get to the $$$3$$$-rd column because $$$|h_2 - h_3| = 3 > k$$$ and there is no way to decrease the gap.In the fifth case, the character is already on the $$$n$$$-th column from the start so the game is won instantly.

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

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

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

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

main = do
	t <- readInt
	replicateM_ t $ do
		[ n, m, k ] <- readInts
		hs <- readInts
		putStrLn $ which "YES" "NO" $ solve m k hs

solve _ _ [_] = True
solve m k (h1:h2:hs)
	| h1 >= max 0 ( h2 - k ) = let d = h1 - max 0 ( h2 - k ) in solve ( m + d ) k (h2:hs)
	| h1 + m >= max 0 ( h2 - k ) = let d = max 0 ( h2 - k ) - h1 in solve ( m - d ) k (h2:hs)
	| otherwise = False

import Control.Monad

data State = State { height :: Int, bag :: Int, canGo :: Bool }

continue :: State -> Int -> Int -> State
continue state@(State { height = h, bag = b, canGo = go }) step nextHeight
    | go == False = state
    | h + b + step < nextHeight = State { height = h, bag = b, canGo = False }
    | otherwise =
        let minHeight = max 0 (nextHeight - step)
            blockDiff = h - minHeight
        in State { height = nextHeight, bag = b + blockDiff, canGo = True }

canTraverse :: Int -> Int -> [Int] -> Bool
canTraverse blocks step heights =
    let start = State { height = (head heights), bag = blocks, canGo = True }
        columns = tail heights
        finalState = foldl (\state -> continue state step) start columns
    in canGo finalState

readAndSolve :: Int -> IO String
readAndSolve _ = do
    [cols, blocks, step] <- readInts
    heights <- readInts
    return (if (canTraverse blocks step heights) then "YES" else "NO")
    where readInts = map (\tok -> read tok :: Int) . words <$> getLine

main = do
    tests <- (\str -> read str :: Int) <$> getLine
    results <- forM [1..tests] readAndSolve
    putStrLn . unlines $ results

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

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

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

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

main = do
	t <- readInt
	replicateM_ t $ do
		[ n, m, k ] <- readInts
		hs <- readInts
		putStrLn $ which "YES" "NO" $ solve m k hs

solve m k [_] = True
solve m k (h1:h2:hs)
	| h1 >= h2 - k = let d = h1 - ( h2 - k ) in solve ( m + d ) k (h2:hs)
	| h1 + m >= h2 - k = let d = ( h2 - k ) - h1 in solve ( m - d ) k (h2:hs)
	| otherwise = False


After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size $$$n$$$. Let's call them $$$a$$$ and $$$b$$$.Note that a permutation of $$$n$$$ elements is a sequence of numbers $$$a_1, a_2, \ldots, a_n$$$, in which every number from $$$1$$$ to $$$n$$$ appears exactly once. The message can be decoded by an arrangement of sequence $$$a$$$ and $$$b$$$, such that the number of matching pairs of elements between them is maximum. A pair of elements $$$a_i$$$ and $$$b_j$$$ is said to match if:   $$$i = j$$$, that is, they are at the same index.  $$$a_i = b_j$$$ His two disciples are allowed to perform the following operation any number of times:   choose a number $$$k$$$ and cyclically shift one of the permutations to the left or right $$$k$$$ times. A single cyclic shift to the left on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_2, c_2:=c_3, \ldots, c_n:=c_1$$$ simultaneously. Likewise, a single cyclic shift to the right on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_n, c_2:=c_1, \ldots, c_n:=c_{n-1}$$$ simultaneously.Help Ishika and Hriday find the maximum number of pairs of elements that match after performing the operation any (possibly zero) number of times.

The first line of the input contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ — the size of the arrays. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \le a_i \le n)$$$ — the elements of the first permutation. The third line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ $$$(1 \le b_i \le n)$$$ — the elements of the second permutation.

Print the maximum number of matching pairs of elements after performing the above operations some (possibly zero) times.

NoteFor the first case: $$$b$$$ can be shifted to the right by $$$k = 1$$$. The resulting permutations will be $$$\{1, 2, 3, 4, 5\}$$$ and $$$\{1, 2, 3, 4, 5\}$$$.For the second case: The operation is not required. For all possible rotations of $$$a$$$ and $$$b$$$, the number of matching pairs won't exceed $$$1$$$.For the third case: $$$b$$$ can be shifted to the left by $$$k = 1$$$. The resulting permutations will be $$$\{1, 3, 2, 4\}$$$ and $$$\{2, 3, 1, 4\}$$$. Positions $$$2$$$ and $$$4$$$ have matching pairs of elements. For all possible rotations of $$$a$$$ and $$$b$$$, the number of matching pairs won't exceed $$$2$$$.

{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeApplications #-}

import Control.Monad
import Data.Array.Unboxed (array, elems, UArray)
import qualified Data.ByteString.Char8 as BS
import Data.IntMap.Strict (fromListWith)
import Data.Foldable (toList)

main :: IO ()
main = do
  [n] <- getInts
  a <- readPerm n <$> getInts
  b <- readPerm n <$> getInts
  let dist a b | a >= b = a - b
               | otherwise = n + a - b
      diffs = zipWith dist a b
      counts = fromListWith (+) $ zip diffs $ repeat 1
  print $ maximum $ toList counts

readPerm :: Int -> [Int] -> [Int]
readPerm n xs@(x : t) = elems $ array @UArray (1, n) $ zip xs [1 .. n]

getInts :: IO [Int]
getInts = go <$> BS.getLine
  where
    go s = case BS.readInt s of
      Nothing -> []
      Just (x, s') -> x : go (BS.drop 1 s')


On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.

The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.

Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.

NoteIn the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.

module Main where

main :: IO ()
main = do
    [n, l, v1, v2, k] <- fmap (map read . words) getLine
    print $ totalT n l v1 v2 k

totalT :: Float -> Float -> Float -> Float -> Float -> Float
totalT n l v1 v2 k = let {  alpha = fromIntegral $ ceiling (n / k);
                          beta  = (v2 - v1) / (v2 + v1);
                          t = l / (v2 + v1 * (alpha - 1) * (beta + 1));
                     } in t * (alpha + alpha * beta - beta)

main = do
    ps@[n, l, v1, v2, k] <- (map read . words) `fmap` getLine :: IO [Int]
    let ps' = map fromIntegral ps :: [Double]
    print $ solve ps'

solve :: [Double] -> Double
solve [n, l, v1, v2, k] = t1 + x where
    m = fromIntegral (ceiling (n / k)) :: Double
    v3 = (v2 - v1) / (v2 + v1)
    x = l / (v2 + (m-1)*(v1 * (1+ v3)))
    t1 = (l - v2*x) / v1

import Control.Applicative

solve :: Int -> Double -> Double
solve 1 v = 1
solve n v = let x = solve (n-1) v
            in (x*(v+1))/(2*x+v+1)

main :: IO ()
main = do
    [n,li,v1i,v2i,k] <- map read . words <$> getLine
    let l = realToFrac li
        v1 = realToFrac v1i
        v2 = realToFrac v2i
        v = v2/v1
        trips = (n+k-1) `div` k
        x = l * (solve trips v)
    putStrLn .show $ (x/v2) + ((l - x)/v1)
    -- putStrLn $ "trips = " ++ show trips ++ " v = " ++ show v
    -- putStrLn .show $ solve trips v

main = do
    ps@[n, l, v1, v2, k] <- (map read . words) `fmap` getLine :: IO [Int]
    let ps' = map fromIntegral ps :: [Double]
    print $ solve ps'

solve :: [Double] -> Double
solve [n, l, v1, v2, k] = t1 + x where
    m = fromIntegral (ceiling (n / k)) :: Double
    x = l / (v2 + (m-1)*(v1 + (v2-v1)/(v2+v1)))
    t1 = (m-1) * x * (1 + (v2-v1)/(v2+v1))

import Control.Applicative

solve :: Int -> Double -> Double
solve 1 v = 1
solve n v = let x = solve (n-1) v
            in (x*(v+1))/(2*x+v+1)

main :: IO ()
main = do
    [n,li,v1i,v2i,k] <- map read . words <$> getLine
    let l = realToFrac li
        v = (realToFrac v2i) / (realToFrac v1i)
        trips = (n+k-1) `div` k
        x = l * (solve trips v)
    putStrLn .show $ (x/v) + (l - x)


Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs.  Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is si = A + (i - 1) × B.For a given m, let's define an m-bite operation as decreasing the height of at most m distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero.Now SaDDas asks you n queries. In each query he gives you numbers l, t and m and you should find the largest number r such that l ≤ r and sequence sl, sl + 1, ..., sr can be eaten by performing m-bite no more than t times or print -1 if there is no such number r.

The first line of input contains three integers A, B and n (1 ≤ A, B ≤ 106, 1 ≤ n ≤ 105). Next n lines contain information about queries. i-th line contains integers l, t, m (1 ≤ l, t, m ≤ 106) for i-th query.

For each query, print its answer in a single line.

import Data.Int (Int64)
import Data.Maybe (fromJust)
import Control.Monad (sequence, replicateM)
import Control.Applicative (liftA, (<$>))
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8

solve :: Int64 -> Int64 -> [Int64] -> Int64
solve a b [l, t, m] = if fail l then -1 else loop l hi
    where
    fail r = t < a + (r - 1) * b || t * m < acc r
    acc r = (a + (l - 1) * b) * (r - l + 1) + b * (r - l) * (r - l + 1) `div` 2
    hi = head . dropWhile (not . fail) . fmap (l +) $ iterate (*2) 1
    loop lo hi
        | hi < lo + 2 = lo
        | fail i = loop lo i
        | otherwise = loop i hi
        where
        i = (lo + hi) `div` 2

parse :: B.ByteString -> [Int64]
parse line = fmap fromIntegral . fromJust . sequence $
    (liftA fst) <$> B8.readInt <$> B8.words line

main = parse <$> B.getLine >>= \[a, b, n] ->
    liftA parse <$> replicateM (fromIntegral n) B.getLine >>= \query ->
    mapM_ print $ (solve a b) <$> query

import Data.Int (Int64)
import Data.Maybe (fromJust)
import Control.Monad (sequence, replicateM)
import Control.Applicative (liftA, (<$>))
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8

solve :: Int -> Int -> [Int] -> Int
solve a b [l, t, m] = if fail l then -1 else loop l hi
    where
    fail r = t < a + (r - 1) * b || t * m < acc r
    acc r = (a + (l - 1) * b) * (r - l + 1) + b * (r - l) * (r - l + 1) `div` 2
    hi = head . dropWhile (not . fail) . fmap (l +) $ iterate (*2) 1
    loop lo hi
        | hi < lo + 2 = lo
        | fail i = loop lo i
        | otherwise = loop i hi
        where
        i = (lo + hi) `div` 2

parse :: B.ByteString -> [Int]
parse line = fromJust . sequence $ (liftA fst) <$> B8.readInt <$> B8.words line

main = parse <$> B.getLine >>= \[a, b, n] ->
    liftA parse <$> replicateM n B.getLine >>= \query ->
    mapM_ print $ (solve a b) <$> query


During a recent research Berland scientists found out that there were n cities in Ancient Berland, joined by two-way paths. Any two cities are joined by no more than one path. No path joins a city with itself. According to a well-known tradition, the road network was built so that it would be impossible to choose three cities from each of which one can get to any other one directly. That is, there was no cycle exactly as long as 3. Unfortunately, the road map has not been preserved till nowadays. Now the scientists are interested how much developed a country Ancient Berland was. Help them - find, what maximal number of roads could be in the country. You also have to restore any of the possible road maps.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of cities in Berland.

On the first line must be printed number m — the maximal number of roads in Berland. Then print m lines containing two numbers each — the numbers of cities that the given road joins. The cities are numbered with integers from 1 to n. If there are several variants of solving the problem, print any of them.

main = do
	a <- fmap (gao . read) getLine
	putStrLn $ show $ length a
	mapM_ (putStrLn . unwords . map show) a

gao n = [[i, j] | m <- [div n 2], i <- [1 .. m], j <- [m + 1 .. n]]

main = interact solve
solve input = output where
  n = read input :: Int
  output = unlines $ map (unwords.(map show)) $ [length a]:a
    where a = answer n
  answer n = [[x,y]|x<-[1..min (n-1) (div (n+3) 2)],
    y <- if x == 1 then [2..min n (div (n+3) 2)] else [div (n+5) 2..n]]

main = do
    n <- fmap read getLine :: IO Int
    if n == 1
        then print 0
        else do
            let m = n `div` 2
            print $ m * (n - m)
            putStrLn $ foldl1 (++) [(show x ++ " " ++ show y ++ "\n") | x <- [1..m], y <- [m+1..n]]

main = do
	a <- fmap (gao . read) getLine
	putStrLn $ show $ length a
	mapM_ (putStrLn . unwords . map show) a

gao 1 = []
gao 2 = [[1, 2]]
gao n = concat [[[1, i], [2, i]] | i <- [3 .. n]]

main = do
	a <- fmap (gao . read) getLine
	putStrLn $ show $ length a
	mapM_ (putStrLn . unwords . map (show . succ)) a

gao n = [[i, j] |
			d <- takeWhile (<n) $ scanl (*) 1 [4,4..],
			s <- takeWhile (<n) $ map (*(4*d)) [0..],
			(i, j) <- [(s, s + d), (s + d, s + d + d), (s + 2 * d, s + 3 * d), (s + 3 * d, s)],
			i < n,
			j < n]


Ridhiman challenged Ashish to find the maximum valued subsequence of an array $$$a$$$ of size $$$n$$$ consisting of positive integers. The value of a non-empty subsequence of $$$k$$$ elements of $$$a$$$ is defined as $$$\sum 2^i$$$ over all integers $$$i \ge 0$$$ such that at least $$$\max(1, k - 2)$$$ elements of the subsequence have the $$$i$$$-th bit set in their binary representation (value $$$x$$$ has the $$$i$$$-th bit set in its binary representation if $$$\lfloor \frac{x}{2^i} \rfloor \mod 2$$$ is equal to $$$1$$$). Recall that $$$b$$$ is a subsequence of $$$a$$$, if $$$b$$$ can be obtained by deleting some(possibly zero) elements from $$$a$$$.Help Ashish find the maximum value he can get by choosing some subsequence of $$$a$$$.

The first line of the input consists of a single integer $$$n$$$ $$$(1 \le n \le 500)$$$ — the size of $$$a$$$. The next line consists of $$$n$$$ space-separated integers — the elements of the array $$$(1 \le a_i \le 10^{18})$$$.

Print a single integer — the maximum value Ashish can get by choosing some subsequence of $$$a$$$.

NoteFor the first test case, Ashish can pick the subsequence $$$\{{2, 3}\}$$$ of size $$$2$$$. The binary representation of $$$2$$$ is 10 and that of $$$3$$$ is 11. Since $$$\max(k - 2, 1)$$$ is equal to $$$1$$$, the value of the subsequence is $$$2^0 + 2^1$$$ (both $$$2$$$ and $$$3$$$ have $$$1$$$-st bit set in their binary representation and $$$3$$$ has $$$0$$$-th bit set in its binary representation). Note that he could also pick the subsequence $$$\{{3\}}$$$ or $$$\{{2, 1, 3\}}$$$.For the second test case, Ashish can pick the subsequence $$$\{{3, 4\}}$$$ with value $$$7$$$.For the third test case, Ashish can pick the subsequence $$$\{{1\}}$$$ with value $$$1$$$.For the fourth test case, Ashish can pick the subsequence $$$\{{7, 7\}}$$$ with value $$$7$$$.

{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}

import Control.Monad
import Data.Bits
import qualified Data.ByteString.Char8 as BS
import Data.List (foldl', scanl', tails)

main :: IO ()
main = do
  BS.getLine
  ns <- getInts
  let ns' = 0:0:ns
      net = init . tails
      res = maximum [x .|. y .|. z | (x : tx) <- net ns', (y : ty) <- net tx, z <- ty]
  print res

getInts :: IO [Integer]
getInts = go <$> BS.getLine
  where
    go s = case BS.readInteger s of
      Nothing -> []
      Just (x, s') -> x : go (BS.drop 1 s')


Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for $$$n$$$ last days: $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ is the price of berPhone on the day $$$i$$$.Polycarp considers the price on the day $$$i$$$ to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if $$$n=6$$$ and $$$a=[3, 9, 4, 6, 7, 5]$$$, then the number of days with a bad price is $$$3$$$ — these are days $$$2$$$ ($$$a_2=9$$$), $$$4$$$ ($$$a_4=6$$$) and $$$5$$$ ($$$a_5=7$$$).Print the number of days with a bad price.You have to answer $$$t$$$ independent data sets.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of sets of input data in the test. Input data sets must be processed independently, one after another. Each input data set consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 150000$$$) — the number of days. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the price on the $$$i$$$-th day. It is guaranteed that the sum of $$$n$$$ over all data sets in the test does not exceed $$$150000$$$.

Print $$$t$$$ integers, the $$$j$$$-th of which should be equal to the number of days with a bad price in the $$$j$$$-th input data set.

import Control.Monad

type Test = [Int]

findBadDays :: [Test] -> [Int]
findBadDays [] = []
findBadDays (first:rest) = (process $ reverse first) : findBadDays rest

process :: Test -> Int
process test = _process test 10000000

_process :: Test -> Int -> Int
_process [] _ = 0
_process (first:rest) smallest = (if first > smallest
                                  then 1
                                  else 0) + _process rest (min first smallest)

getTests :: Int -> IO [Test]
getTests count = replicateM count readTest

readTest :: IO Test
readTest = do
    _ <- getLine
    days <- getLine
    return $ map read (words days)

main :: IO ()
main = do
    count <- getLine
    tests <- getTests $ read count
    let badDays = findBadDays tests
    mapM_ print badDays

import           Control.Arrow
import           Control.Monad (replicateM)
import           Prelude

main :: IO ()
main = do
  n <- read <$> getLine :: IO Int
  x <- replicateM n solve
  return ()

solve :: IO ()
solve = do
  n <- read <$> getLine :: IO Int
  xs <- (words >>> map read) <$> getLine :: IO [Int]
  print $ findSmall xs

findSmall :: [Int] -> Int
findSmall = reverse >>> findSmallWalk 1000001
  where
    findSmallWalk m [] = 0
    findSmallWalk m (y:ys) = findSmallWalk (min y m) ys +  if y > m then 1 else 0

import Control.Monad ( void, replicateM_ )

main = do
  n <- readLn
  replicateM_ n $ do
    void $ getLine
    a <- fmap (fmap (read :: String -> Int) . words) getLine
    print $ snd $ foldr (\next (min, cnt) -> (if next < min then next else min, if next > min then cnt + 1 else cnt)) (maxBound, 0) a

import Control.Monad ( void, replicateM_ )
import Data.Foldable ( foldr' )

main = do
  n <- readLn
  replicateM_ n $ do
    void $ getLine
    a <- fmap (fmap (read :: String -> Int) . words) getLine
    print $ snd $ foldr' (\next (min, cnt) -> (if next < min then next else min, if next > min then cnt + 1 else cnt)) (maxBound, 0) a

import Control.Monad

constructRising :: Int -> [Int] -> [Int]
constructRising n [] = [n]
constructRising n (x : xs)
  | n >= x = n : x : xs
  | otherwise = constructRising n xs

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    n <- readLn
    print =<< (n-) . length . foldl (flip ($)) [] . map (constructRising . (read :: String -> Int) ). words<$> getLine

import           Control.Arrow
import           Control.Monad (replicateM)
import           Prelude

main :: IO ()
main = do
  n <- read <$> getLine :: IO Int
  x <- replicateM n solve
  return ()

solve :: IO ()
solve = do
  n <- read <$> getLine :: IO Int
  xs <- (words >>> map read) <$> getLine :: IO [Int]
  print $ findSmall xs

findSmall :: [Int] -> Int
findSmall = reverse >>> findSmallWalk 150001
  where
    findSmallWalk m [] = 0
    findSmallWalk m (y:ys) = findSmallWalk (min y m) ys +  if y > m then 1 else 0


The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.

The single line contains integer a, written in the binary notation without leading zeroes. This number contains more than 1 and at most 105 digits.

In the single line print the number that is written without leading zeroes in the binary notation — the answer to the problem.

NoteIn the first sample the best strategy is to delete the second digit. That results in number 112 = 310.In the second sample the best strategy is to delete the third or fourth digits — that results in number 110102 = 2610.

removeFirstZero :: String -> String
removeFirstZero binary = if onlyOnes binary
                         then tail binary
                         else remove binary

onlyOnes :: String -> Bool
onlyOnes [] = True
onlyOnes (first:rest) = if first == '0'
                        then False
                        else onlyOnes rest

remove :: String -> String
remove [] = []
remove (first:rest) = if first == '1'
                      then first: remove rest
                      else rest

main :: IO ()
main = do
    binary <- getLine
    putStrLn $ removeFirstZero binary

module Main where
solve :: String -> String
solve "0" = ""
solve "1" = ""
solve ('0' : xs) = xs
solve ('1' : xs) = '1' : solve xs

main = getLine >>= (putStrLn . solve)

module Main where

solve :: String -> String
solve "0" = ""
solve "1" = ""
solve ('1':ls) = '1' : solve ls
solve ('0':ls) = ls

main = getLine >>= (putStrLn . solve)

import Data.Char

solve :: [Int] -> Int -> Int
solve [] k = 1
solve (0:xs) k = k
solve (1:ys) k = solve ys (k+1)

outt :: [Int] -> Int -> Int -> IO()
outt [] k n = return()
outt (x:xs) k n = do
    if k /= n then putChar $ chr $ (x+48) else return ()
    outt xs (k+1) n

convert :: [Char] -> [Int]
convert xs = foldr (\cur acc -> (digitToInt $ cur):acc) [] xs

main =  do
    str <- getLine
    outt (convert str) 1 (solve (convert str) 1)

solve :: String -> String
solve s
  | any (== '0') s  =  takeWhile (== '1') s ++ tail (dropWhile (== '1') s)
  | otherwise  =  tail s

main :: IO ()
main  =  getLine >>= putStrLn . solve

main :: IO ()
main = getLine >>= putStrLn . solve

solve :: String -> String
solve xs | all (=='1') xs = tail xs
         | otherwise = takeWhile (=='1') xs ++ tail (dropWhile (=='1') xs)

main=interact f
f(x:y)|x:y<"10"=y|0<1=x:f y

import Data.List
main = putStrLn . solve =<< getLine
solve s | all (== '1') s = tail s
        | otherwise = delete '0' s

main = getContents >>= putStr.solve

solve :: [Char] -> [Char]
solve [] = []
solve [a,'\n'] = ['\n']
solve s = if (head s) == '0' then (tail s) else (head s):(solve (tail s))

module Main where

solve :: String -> String
solve "0" = ""
solve "1" = ""
solve ('1':ls) = '1':(solve ls)
solve ('0':ls) = ls

main = getLine >>= (putStrLn . solve)

import Control.Applicative
import Data.List

main= do
	s<-getLine
	let s1 =  takeWhile (>'0') s
	let s2 = dropWhile (>'0') s
	let s3 = if s2 =="" then "" else tail s2
	putStrLn $  (if s2=="" then tail s1 else s1 )++s3

import Data.List
add0 "" = "0"
add0 x = x
main = interact $ add0 . \l -> dropWhile (=='0') . take (length l -2) $ delete '0' l

import Data.List
main = interact $ \l-> take (length l -2) $ delete '0' l

main = do
        str <- getLine
        putStrLn (doSolve str)

findPos :: String ->Int -> Int
findPos [] _ = 0
findPos (x:xs) n
        | x == '0' = n
        | otherwise = findPos xs n+1

doSolve :: String -> String
doSolve x = if pos > 0
               then
                                if pos == 1 then drop pos x
                                        else (take (pos-1) x) ++ (drop pos x)
                           else init x
                        where pos = findPos x 1

#!/usr/bin/env runghc
main = do
  c <- getContents
  putStrLn . solve . lines $ c

solve (s:ss) = f s
  where
    f (a:b:cs) = if b == '0' then a:cs else a:f (b:cs)
    f (a:cs) = cs

removeZero [] = []
removeZero (x:l) = if x == '0' then l else x:removeZero l

main = do
  bin <- getLine
  if any (\x -> x == '0') bin
    then putStrLn $ removeZero bin
    else putStrLn $ tail bin

import Data.Char

solve :: [Int] -> Int -> Int
solve [] k = 1
solve (0:xs) k = k
solve (1:ys) k = solve ys (k+1)

outt :: [Int] -> Int -> Int -> IO()
outt [] k n = return()
outt (x:xs) k n = do
    if k /= n then print $ x else return ()
    outt xs (k+1) n

convert :: [Char] -> [Int]
convert xs = foldl (\acc cur -> (digitToInt $ cur):acc) [] xs

main =  do
    str <- getLine
    outt (convert str) 1 (solve (convert str) 1)

import Data.Char

solve :: [Int] -> Int -> Int
solve [] k = 1
solve (0:xs) k = k
solve (1:ys) k = solve ys (k+1)

outt :: [Int] -> Int -> Int -> IO()
outt [] k n = return()
outt (x:xs) k n = do
    if k /= n then putChar $ chr $ (x+48) else return ()
    outt xs (k+1) n

convert :: [Char] -> [Int]
convert xs = foldl (\acc cur -> (digitToInt $ cur):acc) [] xs

main =  do
    str <- getLine
    outt (convert str) 1 (solve (convert str) 1)

import Data.List
main = interact solve
solve s | all (== '1') s = tail s
        | otherwise = reverse $ delete '0' $ reverse s

import Data.List
main = interact solve
solve s | all (== '1') s = tail s
        | otherwise = delete '0' s

main = getContents >>= print.solve

solve :: [Char] -> [Char]
solve [] = []
solve [a,'\n'] = ['\n']
solve s = if (head s) == '0' then (tail s) else (head s):(solve (tail s))

import Control.Applicative
import Data.List

main= do
	s<-getLine
	let s1 =  takeWhile (>'0') s
	let s2 = dropWhile (>'0') s
	let s3 = if s2 =="" then "" else tail s2
	putStrLn $  s1++s3

import Data.List
add0 "" = "0"
add0 x = x
main = interact $ add0 . \l -> dropWhile (=='0') . take (length l -1) $ delete '0' l

import Data.List
main = interact $ \l -> dropWhile (=='0') . take (length l -1) $ delete '0' l

import Data.List
main = interact $ \l -> take (length l -1) $ delete '0' l


Consider the insertion sort algorithm used to sort an integer sequence $$$[a_1, a_2, \ldots, a_n]$$$ of length $$$n$$$ in non-decreasing order.For each $$$i$$$ in order from $$$2$$$ to $$$n$$$, do the following. If $$$a_i \ge a_{i-1}$$$, do nothing and move on to the next value of $$$i$$$. Otherwise, find the smallest $$$j$$$ such that $$$a_i < a_j$$$, shift the elements on positions from $$$j$$$ to $$$i-1$$$ by one position to the right, and write down the initial value of $$$a_i$$$ to position $$$j$$$. In this case we'll say that we performed an insertion of an element from position $$$i$$$ to position $$$j$$$.It can be noticed that after processing any $$$i$$$, the prefix of the sequence $$$[a_1, a_2, \ldots, a_i]$$$ is sorted in non-decreasing order, therefore, the algorithm indeed sorts any sequence.For example, sorting $$$[4, 5, 3, 1, 3]$$$ proceeds as follows:   $$$i = 2$$$: $$$a_2 \ge a_1$$$, do nothing;  $$$i = 3$$$: $$$j = 1$$$, insert from position $$$3$$$ to position $$$1$$$: $$$[3, 4, 5, 1, 3]$$$;  $$$i = 4$$$: $$$j = 1$$$, insert from position $$$4$$$ to position $$$1$$$: $$$[1, 3, 4, 5, 3]$$$;  $$$i = 5$$$: $$$j = 3$$$, insert from position $$$5$$$ to position $$$3$$$: $$$[1, 3, 3, 4, 5]$$$. You are given an integer $$$n$$$ and a list of $$$m$$$ integer pairs $$$(x_i, y_i)$$$. We are interested in sequences such that if you sort them using the above algorithm, exactly $$$m$$$ insertions will be performed: first from position $$$x_1$$$ to position $$$y_1$$$, then from position $$$x_2$$$ to position $$$y_2$$$, ..., finally, from position $$$x_m$$$ to position $$$y_m$$$.How many sequences of length $$$n$$$ consisting of (not necessarily distinct) integers between $$$1$$$ and $$$n$$$, inclusive, satisfy the above condition? Print this number modulo $$$998\,244\,353$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le m < n$$$) — the length of the sequence and the number of insertions. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$2 \le x_1 < x_2 < \ldots < x_m \le n$$$; $$$1 \le y_i < x_i$$$). These lines describe the sequence of insertions in chronological order. It is guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. Note that there is no constraint on the sum of $$$n$$$ of the same kind.

For each test case, print the number of sequences of length $$$n$$$ consisting of integers from $$$1$$$ to $$$n$$$ such that sorting them with the described algorithm produces the given sequence of insertions, modulo $$$998\,244\,353$$$.

NoteIn the first test case, the algorithm performs no insertions — therefore, the initial sequence is already sorted in non-decreasing order. There are $$$10$$$ such sequences: $$$[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 2, 3], [1, 3, 3], [2, 2, 2], [2, 2, 3], [2, 3, 3], [3, 3, 3]$$$.In the second test case, the only sequence satisfying the conditions is $$$[3, 2, 1]$$$.In the third test case, $$$[4, 5, 3, 1, 3]$$$ is one of the sought sequences.

-- disable all optimization in this module
-- How slow is it, really?
{-# OPTIONS_GHC -O0 #-}

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

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.Semigroup
import Data.Functor.Identity

import Data.List
import qualified Data.Sequence as Seq
import Data.Sequence ((><), ViewL(..))
import Data.Array.Unboxed
import Data.Int

ineqsForced :: [(Int, Int)] -> Int
ineqsForced insxys = let
  step :: (Int, Seq.Seq Bool) -> (Int, Int) -> (Int, Seq.Seq Bool)
  step (ct, s) (xi, yi) = ct `seq` s `seq` let
    slen = Seq.length s
    tosplit = s >< Seq.replicate (xi - 1 - slen) False
    (pref, suff) = Seq.splitAt (yi - 1) tosplit
    in  case  Seq.viewl suff  of
    val :< rest
      -> (ct + if  val  then  0  else  1,
          pref >< Seq.fromList [False, True] >< rest)
    _ -> error "urk"
  (ans, _res) = foldl' step (0, Seq.empty) insxys
  in  ans -- filter too slow; no sum(n) constraint

p :: Int
p = 998244353

p64 :: Int64
p64 = fromIntegral p

(*!) :: Int -> Int -> Int
infixr 7 *!
x *! y = let
  x64 = fromIntegral x
  y64 = fromIntegral y
  in  fromIntegral (x64 * y64 `rem` p64)

newtype ProdP = ProdP { unProdP :: Int }
instance  Semigroup ProdP  where
  ProdP x <> ProdP y = ProdP (x *! y)
inv :: Int -> Int
inv = unProdP . stimes (p - 2) . ProdP

getFacts :: Int -> UArray Int Int
getFacts n = listArray (0, n) $ scanl' (*!) 1 [1 .. n]

getIFacts :: UArray Int Int -> UArray Int Int
getIFacts arr = let
  (0, n) = bounds arr
  step (ix, acc) = ix `seq` acc `seq` (ix - 1, acc *! ix)
  in  array (0, n) $ take (n+1) $ iterate step (n, inv (arr ! n))

main :: IO ()
main = (P.words <$> P.getContents >>=) $ evalStateT $ do
  [t] <- getInts 1
  let
    -- whoops, misread constraint, not OK to recompute these
    facts = getFacts (2 * 200000)
    ifacts = getIFacts facts
    choose x y = facts ! x *! ifacts ! y *! ifacts ! (x - y)
  replicateM_ t $ do
    [n, m] <- getInts 2
    xys <- liftPure $ replicateM m $ do
      ~[x, y] <- getInts 2
      pure (x, y)
    let maxOpts = n - 1 - ineqsForced xys
    --putInts [n, maxOpts]
    putInts [choose (n + maxOpts) maxOpts]

type SP = StateT [P.ByteString]
type SIO = SP IO

liftPure :: SP Identity t -> SIO t
liftPure = mapStateT (pure . runIdentity)

getNext :: Monad m => Int -> SP m [P.ByteString]
getNext = state . splitAt

getInts :: Monad m => Int -> SP m [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]

putInts :: [Int] -> SIO ()
putInts li = let
  spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec
  in  lift $ B.hPutBuilder stdout $ case  li  of
  [] -> B.char7 '\n'
  x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\n'

-- -fno-strictness might really hurts memory use and runtime
--  if it interacts badly with foldl'
{-# OPTIONS_GHC
-fno-strictness
-fno-enable-rewrite-rules
-fno-specialise
#-}

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

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.Semigroup
import Data.Functor.Identity

import Data.List
import qualified Data.Sequence as Seq
import Data.Sequence ((><), ViewL(..))
import Data.Array.Unboxed
import Data.Int

ineqsForced :: [(Int, Int)] -> Int
ineqsForced insxys = let
  step :: (Int, Seq.Seq Bool) -> (Int, Int) -> (Int, Seq.Seq Bool)
  step (ct, s) (xi, yi) = ct `seq` s `seq` let
    slen = Seq.length s
    tosplit = s >< Seq.replicate (xi - 1 - slen) False
    (pref, suff) = Seq.splitAt (yi - 1) tosplit
    in  case  Seq.viewl suff  of
    val :< rest
      -> (ct + if  val  then  0  else  1,
          pref >< Seq.fromList [False, True] >< rest)
    _ -> error "urk"
  (ans, _res) = foldl' step (0, Seq.empty) insxys
  in  ans -- filter too slow; no sum(n) constraint

p :: Int
p = 998244353

p64 :: Int64
p64 = fromIntegral p

(*!) :: Int -> Int -> Int
infixr 7 *!
x *! y = let
  x64 = fromIntegral x
  y64 = fromIntegral y
  in  fromIntegral (x64 * y64 `rem` p64)

newtype ProdP = ProdP { unProdP :: Int }
instance  Semigroup ProdP  where
  ProdP x <> ProdP y = ProdP (x *! y)
inv :: Int -> Int
inv = unProdP . stimes (p - 2) . ProdP

getFacts :: Int -> UArray Int Int
getFacts n = listArray (0, n) $ scanl' (*!) 1 [1 .. n]

getIFacts :: UArray Int Int -> UArray Int Int
getIFacts arr = let
  (0, n) = bounds arr
  step (ix, acc) = ix `seq` acc `seq` (ix - 1, acc *! ix)
  in  array (0, n) $ take (n+1) $ iterate step (n, inv (arr ! n))

main :: IO ()
main = (P.words <$> P.getContents >>=) $ evalStateT $ do
  [t] <- getInts 1
  let
    -- whoops, misread constraint, not OK to recompute these
    facts = getFacts (2 * 200000)
    ifacts = getIFacts facts
    choose x y = facts ! x *! ifacts ! y *! ifacts ! (x - y)
  replicateM_ t $ do
    [n, m] <- getInts 2
    xys <- liftPure $ replicateM m $ do
      ~[x, y] <- getInts 2
      pure (x, y)
    let maxOpts = n - 1 - ineqsForced xys
    --putInts [n, maxOpts]
    putInts [choose (n + maxOpts) maxOpts]

type SP = StateT [P.ByteString]
type SIO = SP IO

liftPure :: SP Identity t -> SIO t
liftPure = mapStateT (pure . runIdentity)

getNext :: Monad m => Int -> SP m [P.ByteString]
getNext = state . splitAt

getInts :: Monad m => Int -> SP m [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]

putInts :: [Int] -> SIO ()
putInts li = let
  spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec
  in  lift $ B.hPutBuilder stdout $ case  li  of
  [] -> B.char7 '\n'
  x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\n'

-- I intuitively don't expect these to have much effect here.
{-# OPTIONS_GHC
-fno-enable-rewrite-rules
-fno-specialise
#-}

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

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.Semigroup
import Data.Functor.Identity

import Data.List
import qualified Data.Sequence as Seq
import Data.Sequence ((><), ViewL(..))
import Data.Array.Unboxed
import Data.Int

ineqsForced :: [(Int, Int)] -> Int
ineqsForced insxys = let
  step :: (Int, Seq.Seq Bool) -> (Int, Int) -> (Int, Seq.Seq Bool)
  step (ct, s) (xi, yi) = ct `seq` s `seq` let
    slen = Seq.length s
    tosplit = s >< Seq.replicate (xi - 1 - slen) False
    (pref, suff) = Seq.splitAt (yi - 1) tosplit
    in  case  Seq.viewl suff  of
    val :< rest
      -> (ct + if  val  then  0  else  1,
          pref >< Seq.fromList [False, True] >< rest)
    _ -> error "urk"
  (ans, _res) = foldl' step (0, Seq.empty) insxys
  in  ans -- filter too slow; no sum(n) constraint

p :: Int
p = 998244353

p64 :: Int64
p64 = fromIntegral p

(*!) :: Int -> Int -> Int
infixr 7 *!
x *! y = let
  x64 = fromIntegral x
  y64 = fromIntegral y
  in  fromIntegral (x64 * y64 `rem` p64)

newtype ProdP = ProdP { unProdP :: Int }
instance  Semigroup ProdP  where
  ProdP x <> ProdP y = ProdP (x *! y)
inv :: Int -> Int
inv = unProdP . stimes (p - 2) . ProdP

getFacts :: Int -> UArray Int Int
getFacts n = listArray (0, n) $ scanl' (*!) 1 [1 .. n]

getIFacts :: UArray Int Int -> UArray Int Int
getIFacts arr = let
  (0, n) = bounds arr
  step (ix, acc) = ix `seq` acc `seq` (ix - 1, acc *! ix)
  in  array (0, n) $ take (n+1) $ iterate step (n, inv (arr ! n))

main :: IO ()
main = (P.words <$> P.getContents >>=) $ evalStateT $ do
  [t] <- getInts 1
  let
    -- whoops, misread constraint, not OK to recompute these
    facts = getFacts (2 * 200000)
    ifacts = getIFacts facts
    choose x y = facts ! x *! ifacts ! y *! ifacts ! (x - y)
  replicateM_ t $ do
    [n, m] <- getInts 2
    xys <- liftPure $ replicateM m $ do
      ~[x, y] <- getInts 2
      pure (x, y)
    let maxOpts = n - 1 - ineqsForced xys
    --putInts [n, maxOpts]
    putInts [choose (n + maxOpts) maxOpts]

type SP = StateT [P.ByteString]
type SIO = SP IO

liftPure :: SP Identity t -> SIO t
liftPure = mapStateT (pure . runIdentity)

getNext :: Monad m => Int -> SP m [P.ByteString]
getNext = state . splitAt

getInts :: Monad m => Int -> SP m [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]

putInts :: [Int] -> SIO ()
putInts li = let
  spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec
  in  lift $ B.hPutBuilder stdout $ case  li  of
  [] -> B.char7 '\n'
  x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\n'