You are given an array $$$a[0 \ldots n - 1] = [a_0, a_1, \ldots, a_{n - 1}]$$$ of zeroes and ones only. Note that in this problem, unlike the others, the array indexes are numbered from zero, not from one.In one step, the array $$$a$$$ is replaced by another array of length $$$n$$$ according to the following rules:   First, a new array $$$a^{\rightarrow d}$$$ is defined as a cyclic shift of the array $$$a$$$ to the right by $$$d$$$ cells. The elements of this array can be defined as $$$a^{\rightarrow d}_i = a_{(i + n - d) \bmod n}$$$, where $$$(i + n - d) \bmod n$$$ is the remainder of integer division of $$$i + n - d$$$ by $$$n$$$.  It means that the whole array $$$a^{\rightarrow d}$$$ can be represented as a sequence $$$$$$a^{\rightarrow d} = [a_{n - d}, a_{n - d + 1}, \ldots, a_{n - 1}, a_0, a_1, \ldots, a_{n - d - 1}]$$$$$$  Then each element of the array $$$a_i$$$ is replaced by $$$a_i \,\&\, a^{\rightarrow d}_i$$$, where $$$\&$$$ is a logical "AND" operator. For example, if $$$a = [0, 0, 1, 1]$$$ and $$$d = 1$$$, then $$$a^{\rightarrow d} = [1, 0, 0, 1]$$$ and the value of $$$a$$$ after the first step will be $$$[0 \,\&\, 1, 0 \,\&\, 0, 1 \,\&\, 0, 1 \,\&\, 1]$$$, that is $$$[0, 0, 0, 1]$$$.The process ends when the array stops changing. For a given array $$$a$$$, determine whether it will consist of only zeros at the end of the process. If yes, also find the number of steps the process will take before it finishes.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases.  The first line of each test case description contains two integers: $$$n$$$ ($$$1 \le n \le 10^6$$$) — array size and $$$d$$$ ($$$1 \le d \le n$$$) — cyclic shift offset. The second line of the description contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$0 \le a_i \le 1$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be a single integer — the number of steps after which the array will contain only zeros for the first time. If there are still elements equal to $$$1$$$ in the array after the end of the process, print -1.

NoteIn the third sample test case the array will change as follows:   At the beginning $$$a = [1, 1, 0, 1, 0]$$$, and $$$a^{\rightarrow 2} = [1, 0, 1, 1, 0]$$$. Their element-by-element "AND" is equal to $$$$$$[1 \,\&\, 1, 1 \,\&\, 0, 0 \,\&\, 1, 1 \,\&\, 1, 0 \,\&\, 0] = [1, 0, 0, 1, 0]$$$$$$  Now $$$a = [1, 0, 0, 1, 0]$$$, then $$$a^{\rightarrow 2} = [1, 0, 1, 0, 0]$$$. Their element-by-element "AND" equals to $$$$$$[1 \,\&\, 1, 0 \,\&\, 0, 0 \,\&\, 1, 1 \,\&\, 0, 0 \,\&\, 0] = [1, 0, 0, 0, 0]$$$$$$  And finally, when $$$a = [1, 0, 0, 0, 0]$$$ we get $$$a^{\rightarrow 2} = [0, 0, 1, 0, 0]$$$. Their element-by-element "AND" equals to $$$$$$[1 \,\&\, 0, 0 \,\&\, 0, 0 \,\&\, 1, 0 \,\&\, 0, 0 \,\&\, 0] = [0, 0, 0, 0, 0]$$$$$$  Thus, the answer is $$$3$$$ steps.In the fourth sample test case, the array will not change as it shifts by $$$2$$$ to the right, so each element will be calculated as $$$0 \,\&\, 0$$$ or $$$1 \,\&\, 1$$$ thus not changing its value. So the answer is -1, the array will never contain only zeros.

{-# LANGUAGE ViewPatterns #-}
import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State

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

solve :: UArray Int Int -> Int -> Int
solve arr d = let
  (0, (+ 1) -> n) = bounds arr
  numOrbits = gcd n d
  orbitSize = n `div` numOrbits
  step incr ix = if  ix + incr >= n  then  ix + incr - n  else  ix + incr
  getOrbitTwice k = map (arr !) $ take (2 * orbitSize) $ iterate (step d) k
  evalOne orbit -- Do not traverse an in-memory linked list: It's slow.
    = foldl' max 0 [length vs | vs@(1:_) <- group orbit]
  allOrbitsTwice = map getOrbitTwice [0 .. numOrbits - 1]
  ans = foldl' max 0 $ map evalOne allOrbitsTwice
  in  if  ans >= orbitSize
  then  0-1
  else  ans

mainFun :: SO
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n, d] <- getInts 2
    a <- listArray (0, n-1) <$> getInts n
    pure $ putInts [solve a d]

type SP = State [P.ByteString]
type SO = SP Builder

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

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

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

{-# LANGUAGE ViewPatterns #-}
import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State

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

solve :: UArray Int Int -> Int -> Int
solve arr d = let
  (0, (+ 1) -> n) = bounds arr
  numOrbits = gcd n d
  orbitSize = n `div` numOrbits
  step incr ix = if  ix + incr >= n  then  ix + incr - n  else  ix + incr
  getOrbit k = map (arr !) $ take orbitSize $ iterate (step d) k
  evalOne orbit = if  foldl' (+) 0 orbit == orbitSize
    then  maxBound
    else  foldl' max 0 [length vs | vs@(1:_) <- group (orbit ++ orbit)]
  allOrbits = map getOrbit [0 .. numOrbits - 1]
  ans = foldl' max 0 $ map evalOne allOrbits
  in  if  ans == maxBound
  then  0-1
  else  ans

mainFun :: SO
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n, d] <- getInts 2
    a <- listArray (0, n-1) <$> getInts n
    pure $ putInts [solve a d]

type SP = State [P.ByteString]
type SO = SP Builder

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

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

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


Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells.  Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.

For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice.  Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.

NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F

import Control.Arrow ((>>>))
import Data.Maybe (catMaybes)

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

process :: [String] -> [String]
process [] = []
process (nn : xs) = show (length ys) : ys ++ process (drop n xs)
  where
    n = read nn
    ys = solve n (take n xs)

solve :: Int -> [String] -> [String]
solve n xs = map (\(x, y) -> show x ++ " " ++ show y) . catMaybes $ go (at 2 1) (at 1 2) (at n (n - 1)) (at (n - 1) n)
  where
    at i j = xs !! (i - 1) !! (j - 1)
    go l1 l2 r1 r2
      | l1 == l2 = [get (l1 == r1) (n, n - 1), get (l1 == r2) (n - 1, n)]
      | r1 == r2 = [get (r1 == l1) (2, 1), get (r1 == l2) (1, 2)]
      | otherwise = [get True (1, 2), get (l1 == r1) (n, n - 1), get (l1 == r2) (n - 1, n)]
    get b x = if b then Just x else Nothing

import Control.Monad
import Data.Bits
import Data.Char

printPair :: Int -> Int -> IO ()
printPair x y = putStrLn . unwords $ map show [x, y]

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    n <- read <$> getLine
    a <- replicateM n getLine
    let
      ra = reverse $ map reverse a
      pc = (a !! 0) !! 1
      qc = (a !! 1) !! 0
      xc = (ra !! 0) !! 1
      yc = (ra !! 1) !! 0
      [p, q, x, y] = map (\v -> ord v - ord '0') [pc, qc, xc, yc]
      sw = p + q - x - y
      c = 2 - abs sw
    print c
    when (xor (sw >= 0) (p > 0)) (printPair 1 2)
    when (xor (sw >= 0) (q > 0)) (printPair 2 1)
    when (xor (sw >= 0) (x == 0)) (printPair n (n-1))
    when (xor (sw >= 0) (y == 0)) (printPair (n-1) n)

import Control.Monad
import Data.Char

printPair :: Int -> Int -> IO ()
printPair x y = putStrLn . unwords $ map show [x, y]

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    n <- read <$> getLine
    a <- replicateM n getLine
    let
      ra = reverse $ map reverse a
      pc = (a !! 0) !! 1
      qc = (a !! 1) !! 0
      xc = (ra !! 0) !! 1
      yc = (ra !! 1) !! 0
      [p, q, x, y] = map (\v -> ord v - ord '0') [pc, qc, xc, yc]
      sw = p + q - x - y
      c = 2 - abs sw
    print c
    when (sw >= 0 && p > 0) (printPair 1 2)
    when (sw >= 0 && q > 0) (printPair 2 1)
    when (sw < 0 && x == 0) (printPair n (n-1))
    when (sw < 0 && y == 0) (printPair (n-1) n)


You have an array of integers $$$a$$$ of size $$$n$$$. Initially, all elements of the array are equal to $$$1$$$. You can perform the following operation: choose two integers $$$i$$$ ($$$1 \le i \le n$$$) and $$$x$$$ ($$$x > 0$$$), and then increase the value of $$$a_i$$$ by $$$\left\lfloor\frac{a_i}{x}\right\rfloor$$$ (i.e. make $$$a_i = a_i + \left\lfloor\frac{a_i}{x}\right\rfloor$$$).After performing all operations, you will receive $$$c_i$$$ coins for all such $$$i$$$ that $$$a_i = b_i$$$.Your task is to determine the maximum number of coins that you can receive by performing no more than $$$k$$$ operations.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3; 0 \le k \le 10^6$$$) — the size of the array and the maximum number of operations, respectively. The second line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^3$$$). The third line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 10^6$$$). The sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.

For each test case, print one integer — the maximum number of coins that you can get by performing no more than $$$k$$$ operations.

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

chunk n xs = take n xs : if length xs > n then chunk n (drop n xs) else []

f = (map res [0 ..] !!)
    where res 0 = 0
          res 1 = 0
          res x = minimum [f y + 1 | y <- [x `div` 2..x-1], check y (x-y)]

check :: Int -> Int -> Bool
check y d = or [y `div` a == d | a <- reverse [(y `div` (d+1))..y `div` d], a > 0]

p xs =
    let ((n : k : _) : bs : cs : _) = fmap (fmap read . words) xs :: [[Int]]
        costs = [f x | x <- bs]
        maxk = sum costs + 1
        in show $ last $ dpIters n (dpIter costs cs) $ replicate (minimum [maxk, k+1]) 0

dpIters n f val = foldl (\s e -> e s) val [f x | x <- [0..n-1]]

dpIter costs cs i res = let cost = costs !! i
                            score = cs !! i
                        in g cost score res

zipWith' f l1 l2 = [ f e1 e2 | (e1, e2) <- zipWith k l1 l2 ]
            where
                k x y = x `seq` y `seq` (x,y)

g cost score res = take cost res ++ zipWith' (\ x y -> if (y + score) > x then y + score else x) (drop cost res) res

import Data.Array
import Control.Monad (replicateM_, foldM)
import Data.Array.ST
import Control.Monad.ST (ST, runST)
main = read <$> getLine >>= flip replicateM_ (scase $ minOpsGen 1000)
scase costs = rln >>=
              \[n, k] -> rln >>=
              \bs -> rln >>=
              \cs -> print $
                     maxCoins (min k (12*n)) costs (listArray (1, n) bs)
                     (listArray (1, n) cs)
  where rln = map read . words <$> getLine
minOpsGen :: Int -> Array Int Int
minOpsGen n = let m = n
                  aS = newArray (1, n) m  :: ST s (STArray s Int Int)
              in
                runSTArray $
                aS >>=
                \a -> writeArray a 1 0 >>
                      foldM f a [(i, i + i `div` j) | i <- [1..n], j <- [1..i],
                                  i+div i j <= n]
  where f :: STArray s Int Int -> (Int, Int) -> ST s (STArray s Int Int)
        f a (from, to) = readArray a from >>=
                         \af -> readArray a to >>=
                         \at -> if af + 1 < at
                                then writeArray a to (af+1) >> return a
                                else return a
maxCoins :: Int -> Array Int Int -> Array Int Int -> Array Int Int -> Int
maxCoins k costs b c = knapsack01 k (fmap (costs!) b) c
knapsack01 :: Int -> Array Int Int -> Array Int Int -> Int
knapsack01 wt wa va =
  let (1, n) = bounds wa
  in runST $
     (newArray ((0, 0), (n, wt)) 0 :: ST s (STUArray s (Int, Int) Int)) >>=
     \m -> foldM f m (range ((1, 0), (n, wt))) >>= flip readArray (n, wt)
  where f ::STUArray s (Int, Int) Int -> (Int, Int)
          -> ST s (STUArray s (Int, Int) Int)
        f m (i, w) =  readArray m (i-1, w) >>=
                      \mi1w -> ( if (wa!i) > w
                                  then writeArray m (i, w) mi1w
                                  else readArray m (i-1, w - wa!i) >>=
                                       \mi1w1 -> writeArray m (i, w)
                                                 (max mi1w (mi1w1+(va!i)))
                               ) >> return m


A Russian space traveller Alisa Selezneva, like any other schoolgirl of the late 21 century, is interested in science. She has recently visited the MIT (Moscow Institute of Time), where its chairman and the co-inventor of the time machine academician Petrov told her about the construction of a time machine.During the demonstration of the time machine performance Alisa noticed that the machine does not have high speed and the girl got interested in the reason for such disadvantage. As it turns out on closer examination, one of the problems that should be solved for the time machine isn't solved by an optimal algorithm. If you find a way to solve this problem optimally, the time machine will run faster and use less energy.A task that none of the staff can solve optimally is as follows. There exists a matrix a, which is filled by the following rule:The cells are consecutive positive integers, starting with one. Besides, ai, j < at, k (i, j, t, k ≥ 1), if:  max(i, j) < max(t, k);  max(i, j) = max(t, k) and j < k;  max(i, j) = max(t, k), j = k and i > t. So, after the first 36 numbers are inserted, matrix a will look as follows:  To solve the problem, you should learn to find rather quickly for the given values of x1, y1, x2 and y2 (x1 ≤ x2, y1 ≤ y2) the meaning of expression:As the meaning of this expression can be large enough, it is sufficient to know only the last 10 digits of the sought value.So, no one in MTI can solve the given task. Alice was brave enough to use the time machine and travel the past to help you.Your task is to write a program that uses the given values x1, y1, x2 and y2 finds the last 10 digits of the given expression.

The first input line contains a single integer t (1 ≤ t ≤ 105) — the number of test sets for which you should solve the problem.  Each of the next t lines contains the description of a test — four positive integers x1, y1, x2 and y2 (1 ≤ x1 ≤ x2 ≤ 109, 1 ≤ y1 ≤ y2 ≤ 109), separated by spaces.

For each query print the meaning of the expression if it contains at most 10 characters. Otherwise, print three characters "." (without the quotes), and then ten last digits of the time expression. Print the answer to each query on a single line. Follow the format, given in the sample as closely as possible.

import Control.Applicative((<$>), (<*>))
import Control.Monad(liftM, mapM)
import qualified Data.ByteString.Char8 as B
import Data.Maybe(fromJust)
dsum n k = foldl (*) 1 [(n-k+1)..n]
ssq = (\n -> ((dsum n 3) `div` 3) + ((dsum n 2) `div` 2)) . ((+)1)
snum n = div (n * (n + 1)) 2
ssq2 x y = ssq y - ssq (x - 1)

ssum x y
    | x == y = snum $ x * x
    | x > y = ssum y y - (x - y) * snum (y - 1) + y * ssq2 (y + 1) x
    -- x < y
    | otherwise = (ssum x x) + (y - x) * snum x + x * ssq2 x (y - 1)

mzero = return ()

sshow x
    | x < 10^10 = show x
    | otherwise = "..." ++ takel 10 (show x)
        where takel n = reverse . (take n) . reverse

rectsum [x1, y1, x2, y2] = ssum x2 y2 - ssum (x1-1) y2 - ssum x2 (y1-1) + ssum (x1-1) (y1-1)

main = do
    n <- (read :: [Char] -> Int) `liftM` getLine
    foldl (>>) mzero $ take n $ repeat $ (ffunc `liftM` B.getLine) >>= B.putStrLn
    where ffunc = B.pack . sshow . rectsum . map (fst . fromJust . B.readInteger) . B.words

import Control.Applicative((<$>), (<*>))
import Control.Monad(liftM, mapM)

dsum n k = foldl (*) 1 [(n-k+1)..n]
ssq = (\n -> ((dsum n 3) `div` 3) + ((dsum n 2) `div` 2)) . ((+)1)
snum n = div (n * (n + 1)) 2
ssq2 x y = ssq y - ssq (x - 1)

ssum x y
    | x == y = snum $ x * x
    | x > y = ssum y y - (x - y) * snum (y - 1) + y * ssq2 (y + 1) x
    -- x < y
    | otherwise = (ssum x x) + (y - x) * snum x + x * ssq2 x (y - 1)

mzero = return ()

sshow x
    | x < 10^10 = show x
    | otherwise = "..." ++ (show $ x `mod` (10^10))

rectsum [x1, y1, x2, y2] = ssum x2 y2 - ssum (x1-1) y2 - ssum x2 (y1-1) + ssum (x1-1) (y1-1)

--readi = read :: [Char] -> Integer

main = do
    n <- (read :: [Char] -> Int) `liftM` getLine
    foldl (>>) mzero $ take n $ repeat $ (ffunc `liftM` getLine) >>= putStrLn
    where ffunc = sshow . rectsum . map (read :: [Char] -> Integer) . words

import Control.Applicative((<$>), (<*>))
import Control.Monad(liftM, mapM)

dsum n k = foldl (*) 1 [(n-k+1)..n]
ssq = (\n -> ((dsum n 3) `div` 3) + ((dsum n 2) `div` 2)) . ((+)1)
snum n = div (n * (n + 1)) 2
ssq2 x y = ssq y - ssq (x - 1)

ssum x y
    | x == y = snum $ x * x
    | x > y = ssum y y - (x - y) * snum (y - 1) + y * ssq2 (y + 1) x
    -- x < y
    | otherwise = (ssum x x) + (y - x) * snum x + x * ssq2 x (y - 1)

mzero = return ()

sshow x
    | x < 10^10 = show x
    | otherwise = "..." ++ take 10 (show x)

rectsum [x1, y1, x2, y2] = ssum x2 y2 - ssum (x1-1) y2 - ssum x2 (y1-1) + ssum (x1-1) (y1-1)

--readi = read :: [Char] -> Integer

main = do
    n <- (read :: [Char] -> Int) `liftM` getLine
    foldl (>>) mzero $ take n $ repeat $ (ffunc `liftM` getLine) >>= putStrLn
    where ffunc = sshow . rectsum . map (read :: [Char] -> Integer) . words


On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k.Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task?

The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs.

On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs.

NoteIn the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items.In the second example, he can buy all items as they will cost him [5, 10, 17, 22].In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it.

{-# OPTIONS_GHC -O2 -optc-O2 #-}
module Main where

import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.Int
import Data.List
import Text.Printf
import qualified Data.ByteString.Lazy.Char8 as L

getCost :: [Int64] -> Int -> Int64
getCost as k = c
    where k' = fromIntegral k
          combine a i = a + i * k'
          candidates = take k . sort $ zipWith combine as ([1 ..] :: [Int64])
          c = sum candidates

solve :: [Int64] -> Int64 -> (Int, Int64)
solve as s | s >= cmax = (n, cmax)
           | otherwise = go 0 n
    where n = length as
          cmax = getCost as n

          go l r | l + 1 == r = (l, c)
                 | s >= c = go m r
                 | otherwise = go l m
              where m = (l + r) `div` 2
                    c = getCost as m

type Tokenizer = State [L.ByteString]

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

nextInt64 :: Tokenizer Int64
nextInt64 = fromIntegral <$> nextInt

go :: Tokenizer (Int, Int64)
go = do
  n <- nextInt
  s <- nextInt64
  as <- replicateM n nextInt64
  return $ solve as s

main :: IO ()
main = do
  input <- L.words <$> L.getContents
  let (k, c) = evalState go input
  printf "%d %d\n" k c

{-# OPTIONS_GHC -O2 -optc-O2 #-}
{-# LANGUAGE BangPatterns #-}
module Main where

import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.Int
import Data.List
import Text.Printf
import qualified Data.ByteString.Lazy.Char8 as L

getCost :: [Int64] -> Int -> Int64
getCost as k = c
    where ! k' = fromIntegral k
          combine a i = a + i * k'
          candidates = take k . sort $ zipWith combine as ([1 ..] :: [Int64])
          ! c = sum candidates

solve :: [Int64] -> Int64 -> (Int, Int64)
solve as s | s >= cmax = (n, cmax)
           | otherwise = go 0 n
    where n = length as
          cmax = getCost as n

          go l r | l + 1 == r = (l, c)
                 | s >= c = go m r
                 | otherwise = go l m
              where m = (l + r) `div` 2
                    c = getCost as m

type Tokenizer = State [L.ByteString]

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

nextInt64 :: Tokenizer Int64
nextInt64 = fromIntegral <$> nextInt

go :: Tokenizer (Int, Int64)
go = do
  n <- nextInt
  s <- nextInt64
  as <- replicateM n nextInt64
  return $ solve as s

main :: IO ()
main = do
  input <- L.words <$> L.getContents
  let (k, c) = evalState go input
  printf "%d %d\n" k c

module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Data.Int

readInt = maybe undefined (fromIntegral . fst) . B.readInt
readInts = (readInt <$>) . B.words

solve :: Int64 -> Int64 -> [Int64] -> (Int64, Int64)
solve s n as = go 0 (n + 1)
  where
    cost k = sum $ take (fromIntegral k) $ sort $ map (\(i, a) -> a + i * k) $ zip [1..] as
    go l r
      | r - l > 1 = if c > s then go l m else go m r
      | otherwise = (l, c)
      where
        m = (l + r) `div` 2
        c = cost m

main = do
  n:s:_ <- readInts <$> B.getLine
  as <- readInts <$> B.getLine
  let (k, t) = solve s n as
  putStr $ show k ++ " " ++ show t

{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Data.Int

readInt = maybe undefined (fromIntegral . fst) . B.readInt
readInts = (readInt <$>) . B.words

solve :: Int64 -> Int64 -> [Int64] -> (Int64, Int64)
solve s n as = go 0 (n + 1)
  where
    cost k = sum $ take (fromIntegral k) $ sort $ map (\(i, a) -> a + i * k) $ zip [1..] as
    go !l !r
      | r - l > 1 = if c > s then go l m else go m r
      | otherwise = (l, c)
      where
        m = (l + r) `div` 2
        c = cost m

main = do
  n:s:_ <- readInts <$> B.getLine
  as <- readInts <$> B.getLine
  let (k, t) = solve s n as
  putStr $ show k ++ " " ++ show t

{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List

readInt = maybe undefined fst . B.readInt
readInts = (readInt <$>) . B.words

solve s n as = go 0 (n + 1)
  where
    cost k = sum $ take k $ sort $ map (\(i, a) -> a + i * k) $ zip [1..] as
    go !l !r
      | r - l > 1 = if c > s then go l m else go m r
      | otherwise = (l, c)
      where
        m = (l + r) `div` 2
        c = cost m

main = do
  n:s:_ <- readInts <$> B.getLine
  as <- readInts <$> B.getLine
  let (k, t) = solve s n as
  putStr $ show k ++ " " ++ show t


Geometric progression with the first element a and common ratio b is a sequence of numbers a, ab, ab2, ab3, ....You are given n integer geometric progressions. Your task is to find the smallest integer x, that is the element of all the given progressions, or else state that such integer does not exist.

The first line contains integer (1 ≤ n ≤ 100) — the number of geometric progressions.  Next n lines contain pairs of integers a, b (1 ≤ a, b ≤ 109), that are the first element and the common ratio of the corresponding geometric progression.

If the intersection of all progressions is empty, then print  - 1, otherwise print the remainder of the minimal positive integer number belonging to all progressions modulo 1000000007 (109 + 7).

NoteIn the second sample test one of the progressions contains only powers of two, the other one contains only powers of three.

import Data.Functor
import Data.List (nub, zip4)
import Data.Bits
import Debug.Trace

modNum = 1000000007 :: Integer

modIt :: Integer -> Integer
modIt a = mod a modNum

(//) = div
(%%) = mod
(/|) :: Integer -> Integer -> Bool
a /| b = mod b a == 0

(***) :: Integer -> Integer -> Integer
a *** b = modIt $ a * b

(^^^) :: Integer -> Integer -> Integer
a ^^^ 0 = 1
a ^^^ b = cur *** ((a *** a) ^^^ (div b 2))
    where cur = if b .&. 1 == 1 then a else 1

extGCD :: Integer -> Integer -> (Integer, Integer, Integer)
extGCD a 0 = (a, 1, 0)
extGCD a b = (d, ny, nx - (a // b) * ny)
    where (d, nx, ny) = extGCD b (a %% b)

main :: IO ()
main = getInts >>= putStrLn . show . solve . parsePairs . tail where
    getInts = map read <$> words <$> getContents
    parsePairs [] = []
    parsePairs (x:y:rs) = (x, y) : parsePairs rs
--main = putStrLn . show $ modPow (123::Integer) (321::Integer)
--main = putStrLn . show $ factorize (modNum::Integer)

---------------------------------------------------------------------
solve :: [Pair] -> Integer
solve (p:[]) = fst p
solve (p:rs) = case sol of Multi (i, _) (_, _) -> answer i
                           Single (i, _) -> answer i
                           All -> answer 0
                           None -> -1
    where sol = foldl intersect All . map projToX $ map (solve0 p) rs
          answer i = (fst p) *** ((snd p) ^^^ i)

-- (a1,b1), (a2,b2) -> (i,j) s.t. a1*b1^i = a2*b2^j
solve0 :: Pair -> Pair -> Solution
solve0 (a1, b1) (a2, b2) =
    --trace ("go " ++ show (a1,b1) ++ " " ++ show (a2,b2) ++ " " ++ show ans) $
        ans
    where primes = nub . concat . map factorize $ [a1, a2, b1, b2]
          [a1', b1', a2', b2'] = map (toVec primes) [a1, b1, a2, b2]
          f' (x1, y1, x2, y2) = f (x1, x2) (y1, y2)
          ans = foldl intersect All . map f' $ zip4 a1' b1' a2' b2'

factorize :: Integer -> [Integer]
factorize 1 = []
factorize n = let xs = filter (/| n) [2 .. floor . sqrt $ fromIntegral n] in
    if xs == [] then [n] else let x = head xs in x:factorize (n // x)

toVec [] n = []
toVec (p:rs) n = getNum p n : toVec rs n where
    getNum p n = if p /| n then 1 + getNum p (n // p) else 0

---------------------------------------------------------------------
-- (a1,a2), (b1,b2) -> (i,j) s.t. a1+b1*i = a2+b2*j
-- a, b -> t=(i,j) s.t. a+bt is on line x=y
f :: Pair -> Pair -> Solution
f (a1, a2) (0, 0) = if a1 == a2 then All else None
f (a1, a2) (0, b2) = let (x, y) = (a1-a2, b2) in
    if mod x y /= 0 || div x y < 0 then None else Multi (0, div x y) (1, 0)
f (a1, a2) (b1, 0) = let (x, y) = (a2-a1, b1) in
    if mod x y /= 0 || div x y < 0 then None else Multi (div x y, 0) (0, 1)
f (a1, a2) (b1, b2) =
    --trace ("f " ++ show (g,i0',j0',i0,j0,di,dj) ++ " "++ show (a1,a2) ++ " " ++ show (b1,b2) ++ " " ++ show ans) $
    ans
    where (g, i0', j0'') = extGCD b1 b2
          j0' = -j0''
          d = (a2 - a1) // g
          (i0, j0) = (i0' * d, j0' * d)
          (di, dj) = (b2 // g, b1 // g)
          val = simplify i0 j0 di dj
          ans = if g /| (a2-a1) then val else None

---------------------------------------------------------------------
type Pair = (Integer, Integer)

parallel :: Pair -> Pair -> Bool
parallel (x1, y1) (x2, y2) = x1 * y2 == x2 * y1

data Solution = Multi Pair Pair | Single Pair | None | All deriving (Show, Eq)
getSrc (Multi p _) = p
getDir (Multi _ p) = p

projToX :: Solution -> Solution
projToX s = case s of Multi (i, _) (di, _) -> Multi (i, 0) (di, 0)
                      Single (i, _) -> Single (i, 0)
                      None -> None
                      All -> Multi (0, 0) (1, 0)

simplify i0 j0 di dj = Multi (i0'', j0'') (di, dj)
    where
        t1 = max 0 $ max (div (-i0-1) di) (div (-j0-1) dj) + 1
        i0' = i0 + t1 * di
        j0' = j0 + t1 * dj
        t2 = max 0 $ min (div i0 di) (div j0 dj)
        i0'' = i0' - t2 * di
        j0'' = j0' - t2 * dj

contains :: Pair -> Solution -> Bool
contains _ All = True
contains _ None = False
contains p (Single a) = p == a
contains (x, y) (Multi (i, j) (di, dj)) =
    (i<=x && j<=y && parallel (di,dj) (dx,dy) && (v/|u) && (u//v)>=0)
    where (dx, dy) = (x-i, y-j)
          (u, v) = (dx+dy, di+dj)

intersect :: Solution -> Solution -> Solution
intersect None _ = None
intersect _ None = None
intersect a All = a
intersect All a = a
intersect (Single p) a = if contains p a then Single p else None
intersect a (Single p) = if contains p a then Single p else None
intersect m1@(Multi s1 d1) m2@(Multi s2 d2) = if parallel d1 d2 then res1 else res2
    where
        res1 =
            if not (parallel (dx,dy) d1) then None else if tmp == None then None else ans
            where (dx, dy) = (fst s1 - fst s2, snd s1 - snd s2)
                  tmp = if fst d1 > 0 then f (fst s1, fst s2) (fst d1, fst d2)
                                      else f (snd s1, snd s2) (snd d1, snd d2)
                  ((i, _), (di, _)) = (getSrc tmp, getDir tmp)
                  s = (fst s1 + fst d1 * i, snd s1 + snd d1 * i)
                  d = (fst d1 * di, snd d1 * di)
                  ans = Multi s d
        makeLine x1 y1 x2 y2 = (a, b, -(a*x1+b*y1))
            where a = y2 - y1
                  b = x1 - x2
        res2 =
            --trace ("res2: " ++ show (x,y)) $
            if (t/|x0) && (t/|y0) && contains (x,y) m1 && contains (x,y) m2
                 then Single (x, y)
                 else None
            where (a1, b1, c1) = makeLine (fst s1) (snd s1) (fst s1 + fst d1) (snd s1 + snd d1)
                  (a2, b2, c2) = makeLine (fst s2) (snd s2) (fst s2 + fst d2) (snd s2 + snd d2)
                  t = a1*b2-a2*b1
                  x0 = b1*c2-c1*b2
                  y0 = c1*a2-a1*c2
                  (x, y) = (x0//t, y0//t)

import Data.Functor
import Data.List (nub, zip4)
import Data.Bits
import Debug.Trace
import Control.Monad.ST

modNum = 1000000007 :: Integer

modIt :: Integer -> Integer
modIt a = mod a modNum

(//) = div
(%%) = mod
(/|) :: Integer -> Integer -> Bool
a /| b = mod b a == 0

(***) :: Integer -> Integer -> Integer
a *** b = modIt $ a * b

(^^^) :: Integer -> Integer -> Integer
a ^^^ 0 = 1
a ^^^ b = cur *** ((a *** a) ^^^ (div b 2))
    where cur = if b .&. 1 == 1 then a else 1

extGCD :: Integer -> Integer -> (Integer, Integer, Integer)
extGCD a 0 = (a, 1, 0)
extGCD a b = (d, ny, nx - (a // b) * ny)
    where (d, nx, ny) = extGCD b (a %% b)

main :: IO ()
main = getInts >>= putStrLn . show . solve . parsePairs . tail where
    getInts = map read <$> words <$> getContents
    parsePairs [] = []
    parsePairs (x:y:rs) = (x,y) : parsePairs rs

---------------------------------------------------------------------
solve :: [Pair] -> Integer
solve (p:[]) = fst p
solve (p:rs) = case sol of Multi (i, _) (_, _) -> answer i
                           Single (i, _) -> answer i
                           All -> answer 0
                           None -> -1
    where sol = foldl intersect All . map projToX $ map (solve0 p) rs
          answer i = (fst p) *** ((snd p) ^^^ i)

-- (a1,b1), (a2,b2) -> (i,j) s.t. a1*b1^i = a2*b2^j
solve0 :: Pair -> Pair -> Solution
solve0 (a1, b1) (a2, b2) = ans
    where primes = nub . concat . map factorize $ [a1, a2, b1, b2]
          [a1', b1', a2', b2'] = map (toVec primes) [a1, b1, a2, b2]
          f' (x1, y1, x2, y2) = f (x1, x2) (y1, y2)
          ans = foldl intersect All . map f' $ zip4 a1' b1' a2' b2'

factorize :: Integer -> [Integer]
factorize 1 = []
factorize n = let xs = filter (/| n) [2 .. floor . sqrt $ fromIntegral n] in
    if xs == [] then [n] else let x = head xs in x:factorize (n // x)

toVec [] n = []
toVec (p:rs) n = getNum p n : toVec rs n where
    getNum p n = if p /| n then 1 + getNum p (n // p) else 0

---------------------------------------------------------------------
-- (a1,a2), (b1,b2) -> (i,j) s.t. a1+b1*i = a2+b2*j
-- a, b -> t=(i,j) s.t. a+bt is on line x=y
f :: Pair -> Pair -> Solution
f (a1, a2) (0, 0) = if a1 == a2 then All else None
f (a1, a2) (0, b2) = let (x, y) = (a1-a2, b2) in
    if mod x y /= 0 || div x y < 0 then None else Multi (0, div x y) (1, 0)
f (a1, a2) (b1, 0) = let (x, y) = (a2-a1, b1) in
    if mod x y /= 0 || div x y < 0 then None else Multi (div x y, 0) (0, 1)
f (a1, a2) (b1, b2) = runST $ do
    (g, i0, j0) <- return $ extGCD b1 b2
    if g /| (a2-a1)
        then do
          d <- return $ (a2 - a1) // g
          (i, j) <- return $ (i0 * d, -j0 * d)
          (di, dj) <- return $ (b2 // g, b1 // g)
          return $ simplify i j di dj
        else return None

---------------------------------------------------------------------
type Pair = (Integer, Integer)

parallel :: Pair -> Pair -> Bool
parallel (x1, y1) (x2, y2) = x1 * y2 == x2 * y1

data Solution = Multi Pair Pair | Single Pair | None | All deriving (Show, Eq)
getSrc (Multi p _) = p
getDir (Multi _ p) = p

projToX :: Solution -> Solution
projToX s = case s of Multi (i, _) (di, _) -> Multi (i, 0) (di, 0)
                      Single (i, _) -> Single (i, 0)
                      None -> None
                      All -> Multi (0, 0) (1, 0)

simplify i0 j0 di dj = Multi (i0'', j0'') (di, dj)
    where
        t1 = max 0 $ max (div (-i0-1) di) (div (-j0-1) dj) + 1
        i0' = i0 + t1 * di
        j0' = j0 + t1 * dj
        t2 = max 0 $ min (div i0 di) (div j0 dj)
        i0'' = i0' - t2 * di
        j0'' = j0' - t2 * dj

contains :: Pair -> Solution -> Bool
contains _ All = True
contains _ None = False
contains p (Single a) = p == a
contains (x, y) (Multi (i, j) (di, dj)) =
    (i<=x && j<=y && parallel (di,dj) (dx,dy) && (v/|u) && (u//v)>=0)
    where (dx, dy) = (x-i, y-j)
          (u, v) = (dx+dy, di+dj)

intersect :: Solution -> Solution -> Solution
intersect None _ = None
intersect _ None = None
intersect a All = a
intersect All a = a
intersect (Single p) a = if contains p a then Single p else None
intersect a (Single p) = if contains p a then Single p else None
intersect m1@(Multi s1 d1) m2@(Multi s2 d2) = if parallel d1 d2 then res1 else res2
    where
        res1 =
            if not (parallel (dx,dy) d1) then None else if tmp == None then None else ans
            where (dx, dy) = (fst s1 - fst s2, snd s1 - snd s2)
                  tmp = if fst d1 > 0 then f (fst s1, fst s2) (fst d1, fst d2)
                                      else f (snd s1, snd s2) (snd d1, snd d2)
                  ((i, _), (di, _)) = (getSrc tmp, getDir tmp)
                  s = (fst s1 + fst d1 * i, snd s1 + snd d1 * i)
                  d = (fst d1 * di, snd d1 * di)
                  ans = Multi s d
        makeLine x1 y1 x2 y2 = (a, b, -(a*x1+b*y1))
            where a = y2 - y1
                  b = x1 - x2
        res2 = if (t/|x0) && (t/|y0) && contains (x,y) m1 && contains (x,y) m2
                 then Single (x, y)
                 else None
            where (a1, b1, c1) = makeLine (fst s1) (snd s1) (fst s1 + fst d1) (snd s1 + snd d1)
                  (a2, b2, c2) = makeLine (fst s2) (snd s2) (fst s2 + fst d2) (snd s2 + snd d2)
                  t = a1*b2-a2*b1
                  x0 = b1*c2-c1*b2
                  y0 = c1*a2-a1*c2
                  (x, y) = (x0//t, y0//t)

import Data.Functor
import Data.List (nub, zip4)
import Data.Bits
import Debug.Trace
import Control.Monad.ST

modNum = 1000000007 :: Integer

modIt :: Integer -> Integer
modIt a = mod a modNum

(//) = div
(%%) = mod
(/|) :: Integer -> Integer -> Bool
a /| b = mod b a == 0

(***) :: Integer -> Integer -> Integer
a *** b = modIt $ a * b

(^^^) :: Integer -> Integer -> Integer
a ^^^ 0 = 1
a ^^^ b = cur *** ((a *** a) ^^^ (div b 2))
    where cur = if b .&. 1 == 1 then a else 1

extGCD :: Integer -> Integer -> (Integer, Integer, Integer)
extGCD a 0 = (a, 1, 0)
extGCD a b = (d, ny, nx - (a // b) * ny)
    where (d, nx, ny) = extGCD b (a %% b)

main :: IO ()
main = getInts >>= putStrLn . show . solve . parsePairs . tail where
    getInts = map read <$> words <$> getContents
    parsePairs [] = []
    parsePairs (x:y:rs) = (x,y) : parsePairs rs

---------------------------------------------------------------------
solve :: [Pair] -> Integer
solve (p:[]) = fst p
solve (p:rs) = case sol of Multi (i, _) (_, _) -> answer i
                           Single (i, _) -> answer i
                           All -> answer 0
                           None -> -1
    where sol = foldl intersect All . map projToX $ map (solve0 p) rs
          answer i = (fst p) *** ((snd p) ^^^ i)

-- (a1,b1), (a2,b2) -> (i,j) s.t. a1*b1^i = a2*b2^j
solve0 :: Pair -> Pair -> Solution
solve0 (a1, b1) (a2, b2) = ans
    where primes = nub . concat . map factorize $ [a1, a2, b1, b2]
          [a1', b1', a2', b2'] = map (toVec primes) [a1, b1, a2, b2]
          f' (x1, y1, x2, y2) = f (x1, x2) (y1, y2)
          ans = foldl intersect All . map f' $ zip4 a1' b1' a2' b2'

factorize :: Integer -> [Integer]
factorize 1 = []
factorize n = let xs = filter (/| n) [2 .. floor . sqrt $ fromIntegral n] in
    if xs == [] then [n] else let x = head xs in x:factorize (n // x)

toVec [] n = []
toVec (p:rs) n = getNum p n : toVec rs n where
    getNum p n = if p /| n then 1 + getNum p (n // p) else 0

---------------------------------------------------------------------
-- (a1,a2), (b1,b2) -> (i,j) s.t. a1+b1*i = a2+b2*j
-- a, b -> t=(i,j) s.t. a+bt is on line x=y
f :: Pair -> Pair -> Solution
f (a1, a2) (0, 0) = if a1 == a2 then All else None
f (a1, a2) (0, b2) = let (x, y) = (a1-a2, b2) in
    if mod x y /= 0 || div x y < 0 then None else Multi (0, div x y) (1, 0)
f (a1, a2) (b1, 0) = let (x, y) = (a2-a1, b1) in
    if mod x y /= 0 || div x y < 0 then None else Multi (div x y, 0) (0, 1)
f (a1, a2) (b1, b2) =
    if g /| (a2-a1)
        then let d = (a2-a1)//g
                 (i, j, di, dj) = (i0*d, -j0*d, b2//g, b1//g)
             in simplify i j di dj
        else None
    where (g, i0, j0) = extGCD b1 b2

---------------------------------------------------------------------
type Pair = (Integer, Integer)

parallel :: Pair -> Pair -> Bool
parallel (x1, y1) (x2, y2) = x1 * y2 == x2 * y1

data Solution = Multi Pair Pair | Single Pair | None | All deriving (Show, Eq)
getSrc (Multi p _) = p
getDir (Multi _ p) = p

projToX :: Solution -> Solution
projToX s = case s of Multi (i, _) (di, _) -> Multi (i, 0) (di, 0)
                      Single (i, _) -> Single (i, 0)
                      None -> None
                      All -> Multi (0, 0) (1, 0)

simplify i0 j0 di dj = Multi (i0'', j0'') (di, dj)
    where
        t1 = max 0 $ max (div (-i0-1) di) (div (-j0-1) dj) + 1
        i0' = i0 + t1 * di
        j0' = j0 + t1 * dj
        t2 = max 0 $ min (div i0 di) (div j0 dj)
        i0'' = i0' - t2 * di
        j0'' = j0' - t2 * dj

contains :: Pair -> Solution -> Bool
contains _ All = True
contains _ None = False
contains p (Single a) = p == a
contains (x, y) (Multi (i, j) (di, dj)) =
    (i<=x && j<=y && parallel (di,dj) (dx,dy) && (v/|u) && (u//v)>=0)
    where (dx, dy) = (x-i, y-j)
          (u, v) = (dx+dy, di+dj)

intersect :: Solution -> Solution -> Solution
intersect None _ = None
intersect _ None = None
intersect a All = a
intersect All a = a
intersect (Single p) a = if contains p a then Single p else None
intersect a (Single p) = if contains p a then Single p else None
intersect m1@(Multi s1 d1) m2@(Multi s2 d2) = if parallel d1 d2 then res1 else res2
    where
        res1 =
            if not (parallel (dx,dy) d1) then None else if tmp == None then None else ans
            where (dx, dy) = (fst s1 - fst s2, snd s1 - snd s2)
                  tmp = if fst d1 > 0 then f (fst s1, fst s2) (fst d1, fst d2)
                                      else f (snd s1, snd s2) (snd d1, snd d2)
                  ((i, _), (di, _)) = (getSrc tmp, getDir tmp)
                  s = (fst s1 + fst d1 * i, snd s1 + snd d1 * i)
                  d = (fst d1 * di, snd d1 * di)
                  ans = Multi s d
        makeLine x1 y1 x2 y2 = (a, b, -(a*x1+b*y1))
            where a = y2 - y1
                  b = x1 - x2
        res2 = if (t/|x0) && (t/|y0) && contains (x,y) m1 && contains (x,y) m2
                 then Single (x, y)
                 else None
            where (a1, b1, c1) = makeLine (fst s1) (snd s1) (fst s1 + fst d1) (snd s1 + snd d1)
                  (a2, b2, c2) = makeLine (fst s2) (snd s2) (fst s2 + fst d2) (snd s2 + snd d2)
                  t = a1*b2-a2*b1
                  x0 = b1*c2-c1*b2
                  y0 = c1*a2-a1*c2
                  (x, y) = (x0//t, y0//t)

import Data.Functor
import Data.List (nub, zip4)
import Data.Bits
import Debug.Trace
import Control.Monad.ST

modNum = 1000000007 :: Integer

modIt :: Integer -> Integer
modIt a = mod a modNum

(//) = div
(%%) = mod
(/|) :: Integer -> Integer -> Bool
a /| b = mod b a == 0

(***) :: Integer -> Integer -> Integer
a *** b = modIt $ a * b

(^^^) :: Integer -> Integer -> Integer
a ^^^ 0 = 1
a ^^^ b = cur *** ((a *** a) ^^^ (div b 2))
    where cur = if b .&. 1 == 1 then a else 1

extGCD :: Integer -> Integer -> (Integer, Integer, Integer)
extGCD a 0 = (a, 1, 0)
extGCD a b = (d, ny, nx - (a // b) * ny)
    where (d, nx, ny) = extGCD b (a %% b)

main :: IO ()
main = getInts >>= putStrLn . show . solve . parsePairs . tail where
    getInts = map read <$> words <$> getContents
    parsePairs [] = []
    parsePairs (x:y:rs) = (x,y) : parsePairs rs

---------------------------------------------------------------------
solve :: [Pair] -> Integer
solve (p:[]) = fst p
solve (p:rs) = case sol of Multi (i, _) (_, _) -> answer i
                           Single (i, _) -> answer i
                           All -> answer 0
                           None -> -1
    where sol = foldl intersect All . map projToX $ map (solve0 p) rs
          answer i = (fst p) *** ((snd p) ^^^ i)

-- (a1,b1), (a2,b2) -> (i,j) s.t. a1*b1^i = a2*b2^j
solve0 :: Pair -> Pair -> Solution
solve0 (a1, b1) (a2, b2) = ans
    where primes = nub . concat . map factorize $ [a1, a2, b1, b2]
          [a1', b1', a2', b2'] = map (toVec primes) [a1, b1, a2, b2]
          f' (x1, y1, x2, y2) = f (x1, x2) (y1, y2)
          ans = foldl intersect All . map f' $ zip4 a1' b1' a2' b2'

factorize :: Integer -> [Integer]
factorize 1 = []
factorize n = let xs = filter (/| n) [2 .. floor . sqrt $ fromIntegral n] in
    if xs == [] then [n] else let x = head xs in x:factorize (n // x)

toVec [] n = []
toVec (p:rs) n = getNum p n : toVec rs n where
    getNum p n = if p /| n then 1 + getNum p (n // p) else 0

---------------------------------------------------------------------
-- (a1,a2), (b1,b2) -> (i,j) s.t. a1+b1*i = a2+b2*j
-- a, b -> t=(i,j) s.t. a+bt is on line x=y
f :: Pair -> Pair -> Solution
f (a1, a2) (0, 0) = if a1 == a2 then All else None

f (a1, a2) (0, b2) = let (x, y) = (a1-a2, b2) in
    if mod x y /= 0 || div x y < 0 then None else Multi (0, div x y) (1, 0)

f (a1, a2) (b1, 0) = let (x, y) = (a2-a1, b1) in
    if mod x y /= 0 || div x y < 0 then None else Multi (div x y, 0) (0, 1)

f (a1, a2) (b1, b2) = let (g, i0, j0) = extGCD b1 b2 in
    if g /| (a2-a1)
        then let d = (a2-a1)//g
                 (i, j, di, dj) = (i0*d, -j0*d, b2//g, b1//g)
             in simplify i j di dj
        else None

---------------------------------------------------------------------
type Pair = (Integer, Integer)

parallel :: Pair -> Pair -> Bool
parallel (x1, y1) (x2, y2) = x1 * y2 == x2 * y1

data Solution = Multi Pair Pair | Single Pair | None | All deriving (Show, Eq)
getMulti (Multi (i,j) (di,dj)) = (i, j, di, dj)

projToX :: Solution -> Solution
projToX s = case s of Multi (i, _) (di, _) -> Multi (i, 0) (di, 0)
                      Single (i, _) -> Single (i, 0)
                      None -> None
                      All -> Multi (0, 0) (1, 0)

simplify i0 j0 di dj = Multi (i0'', j0'') (di, dj)
    where
        t1 = max 0 $ max (div (-i0-1) di) (div (-j0-1) dj) + 1
        i0' = i0 + t1 * di
        j0' = j0 + t1 * dj
        t2 = max 0 $ min (div i0 di) (div j0 dj)
        i0'' = i0' - t2 * di
        j0'' = j0' - t2 * dj

contains :: Pair -> Solution -> Bool
contains _ All = True
contains _ None = False
contains p (Single a) = p == a
contains (x, y) (Multi (i, j) (di, dj)) =
    (i<=x && j<=y && parallel (di,dj) (dx,dy) && (v/|u) && (u//v)>=0)
    where (dx, dy) = (x-i, y-j)
          (u, v) = (dx+dy, di+dj)

intersect :: Solution -> Solution -> Solution
intersect None _ = None
intersect _ None = None
intersect a All = a
intersect All a = a
intersect (Single p) a = if contains p a then Single p else None
intersect a (Single p) = if contains p a then Single p else None
intersect m1@(Multi s1 d1) m2@(Multi s2 d2) = if parallel d1 d2 then res1 else res2
    where
        res1 = let (dx, dy) = (fst s1 - fst s2, snd s1 - snd s2) in
            if not (parallel (dx,dy) d1)
                then None
                else let tmp = if fst d1 > 0 then f (fst s1, fst s2) (fst d1, fst d2)
                                             else f (snd s1, snd s2) (snd d1, snd d2)
                     in if tmp == None
                          then None
                          else let (i, _, di, _) = getMulti tmp
                                   s = (fst s1 + fst d1 * i, snd s1 + snd d1 * i)
                                   d = (fst d1 * di, snd d1 * di)
                               in Multi s d
        makeLine x1 y1 x2 y2 = (a, b, -(a*x1+b*y1))
            where a = y2 - y1
                  b = x1 - x2
        res2 = if (t/|x0) && (t/|y0) && contains (x,y) m1 && contains (x,y) m2
                 then Single (x, y)
                 else None
            where (a1, b1, c1) = makeLine (fst s1) (snd s1) (fst s1 + fst d1) (snd s1 + snd d1)
                  (a2, b2, c2) = makeLine (fst s2) (snd s2) (fst s2 + fst d2) (snd s2 + snd d2)
                  t = a1*b2-a2*b1
                  x0 = b1*c2-c1*b2
                  y0 = c1*a2-a1*c2
                  (x, y) = (x0//t, y0//t)

import Data.Functor
import Data.List (nub, zip4)
import Data.Bits

modNum = 1000000007 :: Integer

modIt :: Integer -> Integer
modIt a = mod a modNum

(//) = div
(%%) = mod

(***) :: Integer -> Integer -> Integer
a *** b = modIt $ a * b

(^^^) :: Integer -> Integer -> Integer
a ^^^ 0 = 1
a ^^^ b = cur *** ((a *** a) ^^^ (div b 2))
    where cur = if b .&. 1 == 1 then a else 1

(|||) :: Integer -> Integer -> Bool
a ||| b = mod b a == 0

extGCD :: Integer -> Integer -> (Integer, Integer, Integer)
extGCD a 0 = (a, 1, 0)
extGCD a b = (d, ny, nx - (a // b) * ny)
    where (d, nx, ny) = extGCD b (a %% b)

main :: IO ()
main = getInts >>= putStrLn . show . solve . parsePairs . tail where
    getInts = map read <$> words <$> getContents
    parsePairs [] = []
    parsePairs (x:y:rs) = (x, y) : parsePairs rs
--main = putStrLn . show $ modPow (123::Integer) (321::Integer)
--main = putStrLn . show $ factorize (modNum::Integer)

---------------------------------------------------------------------
solve :: [Pair] -> Integer
solve (p:[]) = modIt $ fst p
solve (p:rs) = case sol of Multi (i, _) (_, _) -> answer i
                           Single (i, _) -> answer i
                           All -> answer 0
                           None -> -1
    where sol = foldl intersect All . map projToX $ map (solve0 p) rs
          answer i = modIt $ fst p * ((snd p) ^^^ i)

-- (a1,b1), (a2,b2) -> (i,j) s.t. a1*b1^i = a2*b2^j
solve0 :: Pair -> Pair -> Solution
solve0 (a1, b1) (a2, b2) = foldl intersect All . map f' $ zip4 a1' b1' a2' b2'
    where primes = nub . concat . map factorize $ [a1, a2, b1, b2]
          [a1', b1', a2', b2'] = map (toVec primes) [a1, b1, a2, b2]
          f' (x1, y1, x2, y2) = f (x1, x2) (y1, y2)

factorize :: Integer -> [Integer]
factorize 1 = []
factorize n = let xs = filter (||| n) [2 .. floor . sqrt $ fromIntegral n] in
    if xs == [] then [n] else let x = head xs in x:factorize (n // x)

toVec [] n = []
toVec (p:rs) n = getNum p n : toVec rs n where
    getNum p n = if p ||| n then 1 + getNum p (n // p) else 0

---------------------------------------------------------------------
-- (a1,a2), (b1,b2) -> (i,j) s.t. a1+b1*i = a2+b2*j
-- a, b -> t=(i,j) s.t. a+bt is on line x=y
f :: Pair -> Pair -> Solution
f (a1, a2) (0, 0) = if a1 == a2 then All else None
f (a1, a2) (0, b2) = let (x, y) = (a1-a2, b2) in
    if mod x y /= 0 || div x y < 0 then None else Multi (0, div x y) (1, 0)
f (a1, a2) (b1, 0) = let (x, y) = (a2-a1, b1) in
    if mod x y /= 0 || div x y < 0 then None else Multi (div x y, 0) (0, 1)
f (a1, a2) (b1, b2) = if g ||| (a2-a1) then val else None
    where (g, i0', j0') = extGCD b1 (-b2)
          d = (a2 - a1) // g
          (i0, j0) = (i0' * d, j0' * d)
          (di, dj) = (b2 // g, b1 // g)
          val = simplify i0 j0 di dj

---------------------------------------------------------------------
type Pair = (Integer, Integer)

parallel :: Pair -> Pair -> Bool
parallel (x1, y1) (x2, y2) = x1 * y2 == x2 * y1

data Solution = Multi Pair Pair | Single Pair | None | All
getSrc (Multi p _) = p
getDir (Multi _ p) = p

projToX :: Solution -> Solution
projToX s = case s of Multi (i, _) (di, _) -> Multi (i, 0) (di, 0)
                      Single (i, _) -> Single (i, 0)
                      None -> None
                      All -> Multi (0, 0) (1, 0)

simplify i0 j0 di dj = Multi (i0'', j0'') (di, dj) -- TODO
    where
        t1 = max 0 $ max (div (-i0-1) di) (div (-j0-1) dj) + 1
        i0' = i0 + t1 * di
        j0' = j0 + t1 * dj
        t2 = max 0 $ min (div i0 di) (div j0 dj)
        i0'' = i0' - t2 * di
        j0'' = j0' - t2 * dj

contains :: Pair -> Solution -> Bool
contains _ All = True
contains _ None = False
contains p (Single a) = p == a
contains (x, y) (Multi (i, j) (di, dj)) =
    (i<=x && j<=y && parallel (di,dj) (dx,dy) && (v|||u) && (u//v)>0)
    where (dx, dy) = (x-i, y-j)
          (u, v) = (dx+dy, di+dj)

intersect :: Solution -> Solution -> Solution
intersect None _ = None
intersect _ None = None
intersect a All = a
intersect All a = a
intersect (Single p) a = if contains p a then Single p else None
intersect a (Single p) = if contains p a then Single p else None
intersect m1@(Multi s1 d1) m2@(Multi s2 d2) = if parallel d1 d2 then res1 else res2
    where
        res1 = if not (parallel (dx,dy) d1) then None else ans
            where (dx, dy) = (fst s1 - fst s2, snd s1 - snd s2)
                  tmp = if fst d1 > 0 then f (fst s1, fst s2) (fst d1, fst d2)
                                      else f (snd s1, snd s2) (snd d1, snd d2)
                  ((i, _), (di, _)) = (getSrc tmp, getDir tmp)
                  s = (fst s1 + fst d1 * i, snd s1 + snd d1 * i)
                  d = (fst d1 * di, snd d1 * di)
                  ans = Multi s d
        makeLine x1 y1 x2 y2 = (a, b, -(a*x1+b*y1))
            where a = y2 - y1
                  b = x1 - x2
        res2 = if (t|||x0) && (t|||y0) && contains (x,y) m1 && contains (x,y) m2
                 then Single (x, y)
                 else None
            where (a1, b1, c1) = makeLine (fst s1) (snd s1) (fst s1 + fst d1) (snd s1 + snd d1)
                  (a2, b2, c2) = makeLine (fst s2) (snd s2) (fst s2 + fst d2) (snd s2 + snd d2)
                  t = a1*b2-a2*b1
                  x0 = b1*c2-c1*b2
                  y0 = c1*a2-a1*c2
                  (x, y) = (x0//t, y0//t)


There is a special offer in Vasya's favourite supermarket: if the customer buys $$$a$$$ chocolate bars, he or she may take $$$b$$$ additional bars for free. This special offer can be used any number of times.Vasya currently has $$$s$$$ roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs $$$c$$$ roubles. Help Vasya to calculate the maximum possible number of chocolate bars he can get!

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases. Each of the next $$$t$$$ lines contains four integers $$$s, a, b, c~(1 \le s, a, b, c \le 10^9)$$$ — the number of roubles Vasya has, the number of chocolate bars you have to buy to use the special offer, the number of bars you get for free, and the cost of one bar, respectively.

Print $$$t$$$ lines. $$$i$$$-th line should contain the maximum possible number of chocolate bars Vasya can get in $$$i$$$-th test.

NoteIn the first test of the example Vasya can buy $$$9$$$ bars, get $$$3$$$ for free, buy another bar, and so he will get $$$13$$$ bars.In the second test Vasya buys $$$1000000000$$$ bars and gets $$$1000000000000000000$$$ for free. So he has $$$1000000001000000000$$$ bars.

{-# LANGUAGE Safe #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE MultiWayIf #-}

import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Control.Applicative
import Control.Arrow
import Data.List
import Data.Array
import Data.Array.IO.Safe
import Data.Array.ST.Safe
import Data.IORef
import Data.STRef
import Data.Maybe
import Data.Bits
import Data.Ord
import Data.Ratio
import Data.Int
import Data.Char
import qualified Data.IntMap as IM
import qualified Data.ByteString.Char8 as BS
import qualified Data.Set as Set
import qualified Data.Sequence as Sq
import Data.Tuple
import Data.Function
import Text.Printf
import Numeric

readIntBS = fst . fromJust . BS.readInt

main = do
  t <- readLn :: IO Int
  replicateM_ t $ do
    [s,a,b,c] <- map read . words <$> getLine :: IO [Integer]
    let n = s `div` c
    print $ n + (n`div`a)*b

f::[String]->[String]
f []=[]
f (e:es)=let (n:a:b:c:[])=map read (words e)::[Integer]
             t1=n `div` c
             t2=(t1 `div` a)*b
         in (show (t1+t2)):f es

main = do
       e<-getLine
       es<-getContents
       mapM_ putStrLn $ f (lines es)

count :: Integer -> Integer -> Integer -> Integer -> Integer
count s a b c = n + b*(n `div` a)
  where n = s `div` c

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

readInteger :: String -> Integer
readInteger s = read s

readIntegerList :: String -> [Integer]
readIntegerList line = map readInteger $ words line

solve :: IO ()
solve = do
  (s:a:b:c:[]) <- fmap readIntegerList getLine
  putStrLn $ show $ count s a b c

main :: IO ()
main = do
  t <- fmap readInt getLine
  sequence_ $ replicate t solve

import Data.Int
main = interact $ unlines . map show . go . map read . tail . words
go [] = []
go (s:a:b:c:xs) = (paid + paid `div` a * b) : go xs where
  paid = s `div` c :: Int64

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

onecase = do
		[s,a,b,c]<-map read <$> words <$> getLine ::IO [Integer]
		let x = div s c
		print $ x + (div x a)*b

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

process :: Integral a => a -> a -> a -> a -> a
process s a b c = d * (a + b) + (m `div` c)
    where (d,m) = divMod s (a*c)

readInt :: String -> Integer
readInt = read

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

import Control.Monad
import Data.Foldable (traverse_)

solve :: [Integer] -> Integer
solve [s, a, b, c] = (s `div` ac) * (a + b) + ((s `mod` ac) `div` c)
	where ac = a * c

main :: IO ()
main = do
	a <- getLine
	tests <- replicateM (read a) getLine
	traverse_ (putStrLn . show .solve) $ map ((map read) . words) tests

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

onecase = do
		[s,a,b,c]<-map read <$> words <$> getLine ::IO [Integer]
		print $ (div s c) + (div s a)*b

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


Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad.Vladik knows n airports. All the airports are located on a straight line. Each airport has unique id from 1 to n, Vladik's house is situated next to the airport with id a, and the place of the olympiad is situated next to the airport with id b. It is possible that Vladik's house and the place of the olympiad are located near the same airport. To get to the olympiad, Vladik can fly between any pair of airports any number of times, but he has to start his route at the airport a and finish it at the airport b.Each airport belongs to one of two companies. The cost of flight from the airport i to the airport j is zero if both airports belong to the same company, and |i - j| if they belong to different companies.Print the minimum cost Vladik has to pay to get to the olympiad.

The first line contains three integers n, a, and b (1 ≤ n ≤ 105, 1 ≤ a, b ≤ n) — the number of airports, the id of the airport from which Vladik starts his route and the id of the airport which he has to reach.  The second line contains a string with length n, which consists only of characters 0 and 1. If the i-th character in this string is 0, then i-th airport belongs to first company, otherwise it belongs to the second.

Print single integer — the minimum cost Vladik has to pay to get to the olympiad.

NoteIn the first example Vladik can fly to the airport 2 at first and pay |1 - 2| = 1 (because the airports belong to different companies), and then fly from the airport 2 to the airport 4 for free (because the airports belong to the same company). So the cost of the whole flight is equal to 1. It's impossible to get to the olympiad for free, so the answer is equal to 1. In the second example Vladik can fly directly from the airport 5 to the airport 2, because they belong to the same company.

main :: IO ()
main = do
  s1 <- getLine
  let [n, a, b] = map read $ words s1
  s <- getLine
  let va = s!!(a - 1)
  let vb = s!!(b - 1)
  if va == vb
    then putStrLn "0"
    else putStrLn "1"

#!/usr/bin/env stack
{- stack
  --resolver lts-2.22
  runghc
  --package array
  --package base
  --package bytestring
  --package containers
  --package mtl
  --package parsec
  --package vector
  --
  -hide-all-packages
-}
{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}
module Main
( main
) where

import           Prelude hiding (interact, lines, unlines, words, unwords,
                                 sequence, foldr)
import           Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,
                                        unlines, unwords, interact, readInt,
                                        readInteger)
import qualified Data.ByteString.Char8 as BS
import           Data.List (foldl', sort, sortBy, group, groupBy, inits, tails)
import qualified Data.List as L
import qualified Data.IntSet as IS
import           Data.IntSet (IntSet)
import qualified Data.IntMap.Strict as IM
import           Data.IntMap.Strict (IntMap)
import qualified Data.Map.Strict as M
import           Data.Map.Strict (Map)
import qualified Data.Set as S
import           Data.Set (Set)
import qualified Data.Array.IArray as A
import           Data.Array.IArray ((!), Array, listArray, array)
import           Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,
                             catMaybes)
import           Data.Either (either)
import           Control.Applicative (Applicative, pure,
                                      (<$>), (<*>), liftA2, liftA3)
import           Control.Monad (unless, when, void, filterM, ap)
import           Control.Arrow ((***), (&&&), first, second)
import           Data.Traversable (sequence, sequenceA, traverse,
                                   Traversable)
import           Data.Ord (comparing, Down(..))
import           Data.Function (on)
import           Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,
                            bit, shiftR, shiftL, Bits)
import qualified Data.Bits as B
import           Data.Word (Word32)
import           Control.Monad.State (State, get, put, gets, modify,
                                      evalState, execState, runState)
import           Text.Parsec (char, space, parse, Parsec)
import qualified Text.Parsec as P
import           Data.Tuple (swap)
import           Data.Foldable (Foldable, foldr)
import           Data.Monoid ((<>), Monoid, mappend, mempty)

type N = Int
toNum = toInt

answer :: N -> N -> [Char] -> N
answer i j xs = if xs !! (i-1) == xs !! (j-1)
                  then 0 else 1

handleInput :: ByteString -> ByteString
handleInput = words & drop 1
            & coerceInput answer
            & show & pack
            -- & map (show & pack) & unlines

toInt = readInt & fromJust & fst
toInte = readInteger & fromJust & fst
toX :: Read a => ByteString -> a
toX = unpack & read

coerceInput f (a:b:c:xs) = f (toNum a) (toNum b) (unpack c)
coerceInput _ _ = error "invalid input"

main :: IO ()
main = interact handleInput

-- Util stuff --
(&) :: (a -> b) -> (b -> c) -> a -> c
(&) = flip (.)
infixl 9 &

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

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

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

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

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

  main :: IO()
  main = do
    [n, a, b] <- getLine >>= return . (map readInt) . words
    xs <- getLine
    let p = xs !! (a - 1)
        q = xs !! (b - 1)
    case p == q of
      True -> print 0
      False -> print 1

module Main where

    main :: IO ()
    main = do
        l <- getLine
        let [_, a, b] = map (\x -> read x :: Int) $ words l
        s <- getLine
        print $ if s !! (a - 1) == s !! (b - 1) then 0 else 1

module Main where

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

type Tokenizer = State [L.ByteString]

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

nextWord :: Tokenizer [Char]
nextWord = state $ \(s:ss) -> (L.unpack s, ss)

solve :: Tokenizer Int
solve = do
    [n, a, b] <- replicateM 3 nextInt
    s <- nextWord
    if s!!(a - 1) == s!!(b - 1) then return 0
    else return 1

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

{-# LANGUAGE FlexibleInstances #-}
module Main (printShit, printShitV, readShit, main, yN, iif) where
import Data.ByteString.Builder
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Maybe

-- Meat
solve :: Int -> Int -> String -> Int
solve a b s = iif 0 1 (s !! a == s !! b)

-- Shit
main :: IO ()
main = do
        [_,a,b]  <- readShit
        s <- readShit
        printShit $ solve (a - 1) (b - 1) s

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

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

iif :: x -> x -> Bool-> x
iif a b c = if c then a else b

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

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

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

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

instance Shit [[Double]] where
    printShit = printShit . (fmap.fmap) show
    readShit = fmap (fmap.fmap $ read) readShit

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

instance Shit String where
    printShit = putStrLn
    printShitV = putStrLn
    readShit = getLine

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

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

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

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

{-# LANGUAGE FlexibleInstances #-}
module Main (printShit, printShitV, readShit, main, yN, iif) where
import Data.ByteString.Builder
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Maybe
import Control.Arrow

-- Meat
solve :: Int -> Int -> String -> Int
solve a b s
    | ours == theirs = 0
    | otherwise = findOurs ours . (reverse *** tail) . splitAt b $ s
        where ours = s !! a
              theirs = s !! b

findOurs :: Char -> (String, String) -> Int
findOurs c ([], y:ys) = if c == y then 1  else 1 + findOurs c ([], ys)
findOurs c (x:xs, []) = if c == x then 1 else 1 + findOurs c (xs, [])
findOurs c (x:xs, y:ys) = if c == y || c == x then 1 else 1 + findOurs c (xs, ys)
findOurs _ ([], []) = error "You suck"

-- Shit
main :: IO ()
main = do
        [_,a,b]  <- readShit
        s <- readShit
        printShit $ solve (a - 1) (b - 1) s

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

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

iif :: Bool -> x -> x -> x
iif True a _ = a
iif _ _ b = b

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

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

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

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

instance Shit [[Double]] where
    printShit = printShit . (fmap.fmap) show
    readShit = fmap (fmap.fmap $ read) readShit

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

instance Shit String where
    printShit = putStrLn
    printShitV = putStrLn
    readShit = getLine

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

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

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

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


Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters "x" and "y", and uses two following operations at runtime:  Find two consecutive characters in the string, such that the first of them equals "y", and the second one equals "x" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string.  Find in the string two consecutive characters, such that the first of them equals "x" and the second one equals "y". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. The input for the new algorithm is string s, and the algorithm works as follows:  If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string.  If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm. Now Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string s.

The first line contains a non-empty string s.  It is guaranteed that the string only consists of characters "x" and "y". It is guaranteed that the string consists of at most 106 characters. It is guaranteed that as the result of the algorithm's execution won't be an empty string.

In the only line print the string that is printed as the result of the algorithm's work, if the input of the algorithm input receives string s.

NoteIn the first test the algorithm will end after the first step of the algorithm, as it is impossible to apply any operation. Thus, the string won't change.In the second test the transformation will be like this:  string "yxyxy" transforms into string "xyyxy";  string "xyyxy" transforms into string "xyxyy";  string "xyxyy" transforms into string "xxyyy";  string "xxyyy" transforms into string "xyy";  string "xyy" transforms into string "y". As a result, we've got string "y". In the third test case only one transformation will take place: string "xxxxxy" transforms into string "xxxx". Thus, the answer will be string "xxxx".

-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html
-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html

import Data.List

getAns :: Int -> Char -> String
getAns 0 _ = []
getAns n c = c : getAns (n - 1) c

main :: IO()
main = do
	str <- getLine
	let xlen = length (filter (== 'x') str)
	let ylen = length (filter (== 'y') str)
	if (xlen > ylen)
		then putStrLn (getAns (xlen - ylen) 'x')
		else putStrLn (getAns (ylen - xlen) 'y')

solve l = replicate x 'x' ++ replicate (-x) 'y'
  where x = length (filter (=='x') l) - length (filter (=='y') l)

main = interact $ solve

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

main :: IO ()
main = do l <- B.getLine
          B.putStrLn $ solve l

solve :: B.ByteString -> B.ByteString
solve l = mkStr (B.count 'x' l,B.count 'y' l)

mkStr (x,y)
    | x > y    = B.replicate (x-y) 'x'
    | otherwise = B.replicate (y-x) 'y'

import Data.List
main = do
    str <- getLine
    let (x, y) = partition (\c -> c == 'x') str
        delta = (length x) - (length y)
    putStrLn $ sq $ show (if (delta > 0)
                        then take delta x
                        else take (abs delta) y )

sq :: String -> String
sq s@[c]                     = s
sq ('"':s)  | last s == '"'  = init s
            | otherwise      = s
sq ('\'':s) | last s == '\'' = init s
            | otherwise      = s
sq s                         = s

solve :: String -> String
solve s
  | x <= y  =  replicate (y-x) 'y'
  | otherwise  =  replicate (x-y) 'x'
  where
    x  =  length $ filter (== 'x') s
    y  =  length $ filter (== 'y') s

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

solve xs = solve' xs []
  where solve' [] ans = ans
        solve' ('x':'y':xs) ans = solve' xs ans
        solve' ('y':'x':xs) ans = solve' xs ans
        solve' (x:xs) [] = solve' xs [x]
        solve' (x:xs) (y:ys)
          | x == y    = solve' xs (x:y:ys)
          | otherwise = solve' xs ys

main = do xs <- getLine
          putStrLn $ solve xs

solve xs = solve' xs []
  where solve' [] ans = reverse ans
        solve' ('x':'y':xs) ans = solve' xs ans
        solve' ('y':'x':xs) ans = solve' xs ans
        solve' (x:xs) [] = solve' xs [x]
        solve' (x:xs) (y:ys)
          | x == y    = solve' xs (x:y:ys)
          | otherwise = solve' xs ys

main = do xs <- getLine
          putStrLn $ solve xs

module Main where

countDiff :: String -> Int
countDiff s = countDiff' s 0
        where
        countDiff' "" d = d
        countDiff' ('x':s) d = countDiff' s (d+1)
        countDiff' ('y':s) d = countDiff' s (d-1)

solve :: String -> String
solve s = if d > 0
          then replicate d 'x'
          else replicate (-d) 'y'
               where
               d = countDiff s

main = getLine >>= (putStrLn . solve)

import qualified Data.ByteString.Char8 as B
main = B.getLine >>= B.putStrLn .solve

solve bs
  | cntx < cnty = B.replicate (cnty-cntx) 'y'
  | otherwise   = B.replicate (cntx-cnty) 'x'
   where
     cntx = B.count 'x' bs
     cnty = B.count 'y' bs

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

solve (s:ss) = f 0 'x' s
  where
    f 0 a (c:cs) =  f 1 c cs
    f n a []  = replicate n a
    f n a (c:cs) = if c == a then f (n+1) a cs else f (n-1) a cs

main :: IO()
main = do
        l <- getLine
        putStrLn $ func l

func :: String -> String
func l = replicate nc ch
    where
        (nc,ch)=df ( map f ['x','y'])
        f c = length [ x | x <- l, x == c]
        df [nx,ny]
            | nx > ny = ((nx-ny),'x')
            | otherwise = ((ny-nx),'y')

import Data.List
main = interact $ f. map length . group . sort . (++ "xy") where
    f (_:x:y:_)
        | x < y = replicate (y - x) 'y'
        | otherwise = replicate (x - y) 'x'

reduce [] = []
reduce ('y':'x':rest) = reduce rest
reduce ('x':'y':rest) = reduce rest
reduce (x:xs) = x:reduce xs

solve xs = iterate reduce xs !! 250

main = interact solve

import qualified Data.ByteString.Char8 as BS

solve xs = solve' xs []
  where solve' [] ans = ans
        solve' ('x':'y':xs) ans = solve' xs ans
        solve' ('y':'x':xs) ans = solve' xs ans
        solve' (x:xs) [] = solve' xs [x]
        solve' (x:xs) (y:ys)
          | x == y    = solve' xs (x:y:ys)
          | otherwise = solve' xs ys

main = do xs <- fmap BS.unpack BS.getLine
          putStrLn $ solve xs

solve [] = []
solve ('y':'x':rest) = solve rest
solve ('x':'y':rest) = solve rest
solve (x:xs) = x:solve xs

main = interact solve

solve xs = solve' xs []
  where solve' [] ans = reverse ans
        solve' ('x':'y':xs) ans = solve' xs ans
        solve' ('y':'x':xs) ans = solve' xs ans
        solve' (x:xs) [] = solve' xs [x]
        solve' (x:xs) (y:ys)
          | x == y    = solve' xs (x:y:ys)
          | otherwise = solve' xs ys

main = interact solve

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

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


For the New Year, Polycarp decided to send postcards to all his $$$n$$$ friends. He wants to make postcards with his own hands. For this purpose, he has a sheet of paper of size $$$w \times h$$$, which can be cut into pieces.Polycarp can cut any sheet of paper $$$w \times h$$$ that he has in only two cases:   If $$$w$$$ is even, then he can cut the sheet in half and get two sheets of size $$$\frac{w}{2} \times h$$$;  If $$$h$$$ is even, then he can cut the sheet in half and get two sheets of size $$$w \times \frac{h}{2}$$$; If $$$w$$$ and $$$h$$$ are even at the same time, then Polycarp can cut the sheet according to any of the rules above.After cutting a sheet of paper, the total number of sheets of paper is increased by $$$1$$$.Help Polycarp to find out if he can cut his sheet of size $$$w \times h$$$ at into $$$n$$$ or more pieces, using only the rules described above.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing three integers $$$w$$$, $$$h$$$, $$$n$$$ ($$$1 \le w, h \le 10^4, 1 \le n \le 10^9$$$) — the width and height of the sheet Polycarp has and the number of friends he needs to send a postcard to.

For each test case, output on a separate line:    "YES", if it is possible to cut a sheet of size $$$w \times h$$$ into at least $$$n$$$ pieces;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

NoteIn the first test case, you can first cut the $$$2 \times 2$$$ sheet into two $$$2 \times 1$$$ sheets, and then cut each of them into two more sheets. As a result, we get four sheets $$$1 \times 1$$$. We can choose any three of them and send them to our friends.In the second test case, a $$$3 \times 3$$$ sheet cannot be cut, so it is impossible to get two sheets.In the third test case, you can cut a $$$5 \times 10$$$ sheet into two $$$5 \times 5$$$ sheets.In the fourth test case, there is no need to cut the sheet, since we only need one sheet.In the fifth test case, you can first cut the $$$1 \times 4$$$ sheet into two $$$1 \times 2$$$ sheets, and then cut each of them into two more sheets. As a result, we get four sheets $$$1 \times 1$$$.

solve [a,b,c] = s a b c 1
 where s a b c x | even a && even b =  s (a `div` 2) (b`div`2) c (x*2*2)
                 | even a && odd b  =  s (a `div` 2) b c (x*2)
                 | odd a  && even b =  s a (b`div`2) c (x*2)
                 | odd a  && odd b  =  if x >= c then "YES" else "NO"
main = interact  $ unlines . map ( solve  . map (read :: String -> Int) . words)  . tail . lines

import Control.Monad
import Data.List
import Data.Array

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

readInts :: IO [Integer]
readInts = readArray

readInt :: IO Integer
readInt = readLn

kp2 :: Integer -> Integer
kp2 n
  | n `mod` 2 == 0 = 2 * kp2 (n `div` 2)
  | otherwise = 1

solve :: [Integer] -> String
solve [w, h, n]
  | kp2 w * kp2 h >= n = "YES"
  | otherwise = "NO"

solveCase :: IO String
solveCase = fmap solve readInts

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

main = interact $ unlines . map (ans . map read . words) . tail . lines

ans [w,h,n]
    | solve (w * h) >= n = "YES"
    | otherwise = "No"

solve = product . (2 <$) . takeWhile even . iterate (`div` 2)

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

solve [w,h,n]
    | 2 ^ (f w + f h) >= n = "YES"
    | otherwise = "NO"

f x
    | even x = 1 + f (div x 2)
    | otherwise = 0

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

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

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

solve :: [Int] -> String
solve [w,h,n] = if mx2pow w * mx2pow h >=n then "YES" else "NO" where
  mx2pow x = last $ takeWhile (\p->x `mod` p == 0) [2^k | k<-[0..]]

import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Set as S

import qualified Data.Array as A

import qualified Control.Monad.State.Strict as State
import Control.Monad.ST

import Data.Bits(xor, (.&.), (.|.))
import qualified Data.Array.MArray as MA
import Data.Array.ST(runSTArray, STArray)

import Data.Array((!))
import Control.Monad(replicateM, foldM, mapM, filterM) -- foldM est un foldl
import Data.Maybe

numOcc :: Ord a => [a] -> M.Map a Integer
numOcc (x:xs) = let m = numOcc xs in case M.lookup x m of
	Just i -> M.insert x (i+1) m
	Nothing -> M.insert x 1 m
numOcc [] = M.empty

numOcc' :: A.Ix a => (a, a) -> [a] -> A.Array a Integer
numOcc' size list = runSTArray $ do
	array <- MA.newArray size 0
	foldM (addElem array) () list
	return array

	where
		addElem :: A.Ix a=> STArray s a Integer -> () -> a -> ST s ()
		addElem array action a = do
			i <- MA.readArray array a
			MA.writeArray array a (i+1)

insertWithList :: Ord a => a -> b -> M.Map a [b] -> M.Map a [b]
insertWithList a b m = case M.lookup a m of
	Just l -> M.insert a (b:l) m
	Nothing -> M.insert a [b] m

deleteWithList :: Ord a => a -> M.Map a [b] -> M.Map a [b]
deleteWithList a m = case M.lookup a m of
	Just (x:y:xs) -> M.insert a (y:xs) m
	Just [x] -> M.delete a m

solve :: Integer -> Integer -> Integer -> Bool

solve w h n = (1 + aux w) * (1 + aux h) >= n where
	aux k
		| mod k 2 == 0 = 1 + 2 * aux (div k 2)
		| otherwise = 0

plotResult True = putStrLn "Yes"
plotResult False = putStrLn "No"

main = do
	t <- getLine >>= return . read :: IO Integer
	replicateM (fromInteger t) $ do
		[w, h, n] <- fmap ((fmap read) . words) getLine :: IO [Integer]
		plotResult $ solve w h n

{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Array
import Data.Char
import Data.List
import Data.Int
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Control.Applicative
import System.IO
import Data.Bits

-- import qualified Data.Set as Set

readInt :: String -> Int
readInt = read

printArr :: (Show a) => String -> [a] -> IO ()
printArr sep arr = do
    putStrLn . intercalate sep $ (show <$> arr)

print2DArr :: (Show a) => String -> [[a]] -> IO ()
print2DArr sep arr = sequence_ (printArr sep <$> arr)

every n xs = case drop (n-1) xs of
            (y:ys) -> y : every n ys
            [] -> []

yon True = "YES"
yon False = "NO"

main = do
    -- input <- openFile "in" ReadMode
    let input = stdin
    hSetBuffering input (BlockBuffering (Just 4096))
    hSetBuffering stdout (BlockBuffering (Just 4096))
    contents <- hGetContents input
    -- printArr (readIntArr $ head q) " "
    solve contents

solve inp = sequence do
    [x, y, n] <- (readInt <$>) . words <$> tail (lines inp)
    let x' = 1 `shift` countTrailingZeros x
        y' = 1 `shift` countTrailingZeros y
    [putStrLn $ yon (x'*y' >= n)]

module Main where

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

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

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

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

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

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

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

main :: IO ()
main = tCase process

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

process :: IO ()
process = do
    [w, h, n] <- getIntList
    putStrLn $ yesOrNo $ (n <= (f w * f h))

f :: Int -> Int
f x | odd x = 1
    | otherwise = 2 * f (x `div` 2)

count :: Int -> Int
count x | x `mod` 2 == 0 = 1 +  count ( x `div` 2)
        | otherwise = 0

fn :: [Int] -> String
fn x | (2^(count (x!!0)))*(2^(count (x!!1))) >= (x!!2) = "Yes"
     | otherwise = "No"

func::[Int] -> [[Int]]
func [] = []
func x = [take 3 x] ++ func (drop 3 x)
out::[[Int]] -> [String]
out x = [fn y | y <- x]
parsei::String -> [Int]
parsei x = [read k :: Int | k <- tail(words x)]

parseo::[String] -> String
parseo x = concat ([k ++ "\n" | k <- x])
totalfun::String -> String
totalfun x = parseo(out(func(parsei(x))))

main = interact $ totalfun

import Control.Arrow
main = interact $ lines >>> drop 1 >>> map (words >>> map read >>> solve) >>> unlines

solve :: [Int] -> String
solve [w, h, n]
  | ((two (w*h)) >= n) = "YES"
  | otherwise = "NO"

two :: Int -> Int
two x
  | (mod x 2 == 0) = 2 * two (div x 2)
  | otherwise = 1

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

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

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

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

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

solve :: Int -> Int -> Int -> Bool
solve w h n = cntTwo w h >= n
    where
        cntTwo w h
            | even w    = 2 * cntTwo (w `div` 2) h
            | even h    = 2 * cntTwo w (h `div` 2)
            | otherwise = 1

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [w, h, n] <- B8.getLine <&> map readIntB8 . B8.words
        let answer = solve w h n
        printf "%s\n" ((if answer then "YES" else "NO")::String)

{-# LANGUAGE
    BangPatterns
  , BlockArguments
  , DataKinds
  , DeriveGeneric
  , DerivingStrategies
  , DerivingVia
  , FlexibleContexts
  , FlexibleInstances
  , GADTs
  , GeneralizedNewtypeDeriving
  , KindSignatures
  , LambdaCase
  , MultiParamTypeClasses
  , MultiWayIf
  , NPlusKPatterns
  , NegativeLiterals
  , OverloadedLabels
  , OverloadedStrings
  , ParallelListComp
  , PolyKinds
  , RankNTypes
  , ScopedTypeVariables
  , StrictData
  , TupleSections
  , TypeApplications
  , TypeFamilies
  , TypeOperators
  , UndecidableInstances
  , ViewPatterns
  #-}

module Main where

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Control.Monad.ST
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import           Data.Foldable
import           Data.Functor
import           Data.Int
import           Data.List
import           Data.Maybe
import           Data.Monoid
import           Data.Ord
import           Data.Semigroup                 ( Max(..)
                                                , Min(..)
                                                , All(..)
                                                , Arg(..)
                                                )
import           Data.Ratio
-- import           Data.Vector.Unboxing.Mutable   ( Unboxable )
-- import qualified Data.Vector.Unboxing.Mutable  as V
import           System.IO
import           Data.Proxy
import           GHC.TypeLits
import           GHC.Generics                   ( Generic )
import           Data.Function
-- import           Data.List.HT                   ( mapAdjacent
--                                                 , isAscending
--                                                 )
-- import           Control.Monad.Primitive        ( PrimMonad(PrimState) )
import qualified Data.Set                      as S
-- import qualified Data.Vector.Algorithms.Radix  as VA
-- import           Text.Parsec.ByteString

-- #if defined(LOCAL_ZER0STAR)
-- {-# ANN module ("Hlint: ignore Unused LANGUAGE pragma" :: String) #-}
-- {-# ANN module ("Hlint: ignore Reduce duplication" :: String) #-}
-- #endif

twice :: (a -> a -> b) -> a -> b
twice f x = f x x

both :: Arrow a => a b c -> a (b, b) (c, c)
both = twice (***)

both2 f (a1, b1) (a2, b2) = (f a1 a2, f b1 b2)

readsLn :: Read a => IO [a]
readsLn = mapM readIO . words =<< getLine

getInt :: IO Int
getInt = fst . fromJust . BS.readInt <$> BS.getLine

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

getInteger :: IO Integer
getInteger = fst . fromJust . BS.readInteger <$> BS.getLine

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

main = do
  t <- getInt
  replicateM_
    t
    do
      [w, h, n] <- getIntegers
      let
        f = toInteger . length . takeWhile ((== 0) . (`mod` 2)) . iterate
          (`div` 2)
        ww = f w
        hh = f h
      putStrLn if 2 ^ (ww + hh) >= n then "Yes" else "No"

import Control.Monad

cont :: Int -> Int
cont = go 1  where
  go x y
    | odd y      = x
    | otherwise  = go (2*x) (div y 2)

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [w, h, n] <- map read . words <$> getLine :: IO [Int]
    putStrLn $ if  cont w * cont h >= n
      then  "YES"
      else  "NO"

import Control.Monad
import Data.List
import Data.Array

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

readInts :: IO [Integer]
readInts = readArray

readInt :: IO Integer
readInt = readLn

kp2 :: Integer -> Integer
kp2 n
  | n `mod` 2 == 0 = 1 + kp2 (n `div` 2)
  | otherwise = 1

solve :: [Integer] -> String
solve [w, h, n]
  | kp2 w * kp2 h >= n = "YES"
  | otherwise = "NO"

solveCase :: IO String
solveCase = fmap solve readInts

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