"You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it?

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For every test case print one non-negative integer — the answer to the problem.

NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs.

import Control.Monad
import Control.Monad.ST
import Data.Array
import qualified Data.Array.ST.Safe as S
import qualified Data.Array.Unboxed as U
import Data.Foldable
import Data.List

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

solve' [] = (0, 0)
solve' [x] = (1, 0)
solve' (a : b : xs) =
  if a == b
    then (\(x, y) -> (x + 1, y)) next
    else (\(x, y) -> (1, y + (x * (x - 1) `div` 2))) next
  where
    next = solve' (b : xs)

solve v = f $ solve' v
  where
    f = (\(a, b) -> b + (a * (a - 1) `div` 2))

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    _ <- getLine
    v <- sort . map (lbit . read) . words <$> getLine
    print $ solve v

import Control.Monad
import Data.List
import Data.Bits
import Data.Int

c2 :: Int -> Int64
c2 v = let  v2 = fromIntegral v  in  div (v2 * (v2 - 1)) 2

solve :: [Int] -> Int64
solve li = let
  sli = group $ sort [countLeadingZeros x | x <- li, x > 0]
  in  sum $ map (c2 . length) sli

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    _n <- getLine
    a <- map read . words <$> getLine
    print $ solve a


As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.Let's consider a set of functions of the following form:  Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.

The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function.

Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.

import Data.Ratio
import Data.Maybe
import Data.Set hiding (map)
import qualified Data.ByteString.Char8 as C

main :: IO ()
main = do
  (_:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) $ C.getContents
  let f (0:_:t) = f t
      f (k:b:t) = b%k: f t
      f _       = []
  print $ size $ fromList $ f $ map toInteger a

import Data.Ratio
import Data.Maybe
import Data.Set hiding (map)
import qualified Data.ByteString.Char8 as C

main :: IO ()
main = do
  (_:a) <- fmap (map (fst . fromJust . C.readInteger) . C.words) $ C.getContents
  let f (0:_:t) = f t
      f (k:b:t) = b%k: f t
      f _       = []
  print $ size $ fromList $ f a

import Data.Ratio
import Data.Char
import qualified Data.Map as Map
p[k,b]=((-b)%k,abs k)
s=length . filter ((/=0) . snd) . Map.toList . Map.fromListWith (+)
rd ('-':t) = - rd t
rd x = fromIntegral $ foldl (\x c -> (+ (ord c - ord '0')).(*10) $ x) 0 x :: Integer
main=interact$show.s.map p.filter((/=0).head).map(map rd.words).tail.lines

import Data.Ratio
import Data.Maybe
import Data.Set hiding (map)
import qualified Data.ByteString.Char8 as C

main = do
  (_:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) $ C.getContents
  let f (0:_:t) = f t
      f (k:b:t) = b%k: f t
      f _       = []
  print $ size $ fromList $ f a

import Data.Ratio
import Data.Char
import qualified Data.Map as Map
p[k,b]=((-b)%k,abs k)
s=length . filter ((/=0) . snd) . Map.toList . Map.fromListWith (+) -- foldr (\(k,v) -> Map.insertWith'(+) k v) Map.empty
rd ('-':t) = - rd t
rd x = foldl (\x c -> (+ (ord c - ord '0')).(*10) $ x) 0 x
main=interact$show.s.map p.filter((/=0).head).map(map rd.words).tail.lines


Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems.For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends on the ratio of the number of participants who solved the problem to the total number of round participants. Everyone who made at least one submission is considered to be participating in the round.Pay attention to the range bounds. For example, if 40 people are taking part in the round, and 10 of them solve a particular problem, then the solvers fraction is equal to 1 / 4, and the problem's maximum point value is equal to 1500.If the problem's maximum point value is equal to x, then for each whole minute passed from the beginning of the contest to the moment of the participant's correct submission, the participant loses x / 250 points. For example, if the problem's maximum point value is 2000, and the participant submits a correct solution to it 40 minutes into the round, this participant will be awarded with 2000·(1 - 40 / 250) = 1680 points for this problem.There are n participants in the round, including Vasya and Petya. For each participant and each problem, the number of minutes which passed between the beginning of the contest and the submission of this participant to this problem is known. It's also possible that this participant made no submissions to this problem.With two seconds until the end of the round, all participants' submissions have passed pretests, and not a single hack attempt has been made. Vasya believes that no more submissions or hack attempts will be made in the remaining two seconds, and every submission will pass the system testing.Unfortunately, Vasya is a cheater. He has registered 109 + 7 new accounts for the round. Now Vasya can submit any of his solutions from these new accounts in order to change the maximum point values of the problems. Vasya can also submit any wrong solutions to any problems. Note that Vasya can not submit correct solutions to the problems he hasn't solved.Vasya seeks to score strictly more points than Petya in the current round. Vasya has already prepared the scripts which allow to obfuscate his solutions and submit them into the system from any of the new accounts in just fractions of seconds. However, Vasya doesn't want to make his cheating too obvious, so he wants to achieve his goal while making submissions from the smallest possible number of new accounts.Find the smallest number of new accounts Vasya needs in order to beat Petya (provided that Vasya's assumptions are correct), or report that Vasya can't achieve his goal.

The first line contains a single integer n (2 ≤ n ≤ 120) — the number of round participants, including Vasya and Petya. Each of the next n lines contains five integers ai, 1, ai, 2..., ai, 5 ( - 1 ≤ ai, j ≤ 119) — the number of minutes passed between the beginning of the round and the submission of problem j by participant i, or -1 if participant i hasn't solved problem j. It is guaranteed that each participant has made at least one successful submission. Vasya is listed as participant number 1, Petya is listed as participant number 2, all the other participants are listed in no particular order.

Output a single integer — the number of new accounts Vasya needs to beat Petya, or -1 if Vasya can't achieve his goal.

NoteIn the first example, Vasya's optimal strategy is to submit the solutions to the last three problems from two new accounts. In this case the first two problems will have the maximum point value of 1000, while the last three problems will have the maximum point value of 500. Vasya's score will be equal to 980 + 940 + 420 + 360 + 270 = 2970 points, while Petya will score just 800 + 820 + 420 + 440 + 470 = 2950 points.In the second example, Vasya has to make a single unsuccessful submission to any problem from two new accounts, and a single successful submission to the first problem from the third new account. In this case, the maximum point values of the problems will be equal to 500, 1500, 1000, 1500, 3000. Vasya will score 2370 points, while Petya will score just 2294 points.In the third example, Vasya can achieve his goal by submitting the solutions to the first four problems from 27 new accounts. The maximum point values of the problems will be equal to 500, 500, 500, 500, 2000. Thanks to the high cost of the fifth problem, Vasya will manage to beat Petya who solved the first four problems very quickly, but couldn't solve the fifth one.

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Data.List

main = do
  n <- fmap readInt B.getLine
  ks <- replicateM n $ fmap readInts B.getLine
  print $ solve n ks

solve n ks@(vts:pts:_) = maybe (-1) id $ find (\x -> (\mps -> point vts mps > point pts mps) $ zipWith3 (\vt pt s -> mpoint (n + x) $ if pt /= -1 && vt > pt then s + x else s) vts pts ss) $ [0..10000]
  where
    ss = map (length . filter (> (-1))) $ transpose ks

point = (sum .) . zipWith (\t mp -> if t == -1 then 0 else mp * (1 - fromIntegral t / 250))

mpoint n s
  | 2 * s > n = 500
  | 4 * s > n = 1000
  | 8 * s > n = 1500
  | 16 * s > n = 2000
  | 32 * s > n = 2500
  | otherwise = 3000

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words


Mainak has two positive integers $$$n$$$ and $$$m$$$.Mainak finds a sequence $$$a_1, a_2, \ldots, a_n$$$ of $$$n$$$ positive integers interesting, if for all integers $$$i$$$ ($$$1 \le i \le n$$$), the bitwise XOR of all elements in $$$a$$$ which are strictly less than $$$a_i$$$ is $$$0$$$. Formally if $$$p_i$$$ is the bitwise XOR of all elements in $$$a$$$ which are strictly less than $$$a_i$$$, then $$$a$$$ is an interesting sequence if $$$p_1 = p_2 = \ldots = p_n = 0$$$.For example, sequences $$$[1,3,2,3,1,2,3]$$$, $$$[4,4,4,4]$$$, $$$[25]$$$ are interesting, whereas $$$[1,2,3,4]$$$ ($$$p_2 = 1 \ne 0$$$), $$$[4,1,1,2,4]$$$ ($$$p_1 = 1 \oplus 1 \oplus 2 = 2 \ne 0$$$), $$$[29,30,30]$$$ ($$$p_2 = 29 \ne 0$$$) aren't interesting.Here $$$a \oplus b$$$ denotes bitwise XOR of integers $$$a$$$ and $$$b$$$.Find any interesting sequence $$$a_1, a_2, \ldots, a_n$$$ (or report that there exists no such sequence) such that the sum of the elements in the sequence $$$a$$$ is equal to $$$m$$$, i.e. $$$a_1 + a_2 \ldots + a_n = m$$$.As a reminder, the bitwise XOR of an empty sequence is considered to be $$$0$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Description of the test cases follows. The first line and the only line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le m \le 10^9$$$) — the length of the sequence and the sum of the elements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, if there exists some interesting sequence, output "Yes" on the first line, otherwise output "No". You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer). If the answer is "Yes", output $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i \ge 1$$$), forming an interesting sequence such that $$$a_1 + a_2 \ldots + a_n = m$$$. If there are multiple solutions, output any.

Note In the first test case, $$$[3]$$$ is the only interesting sequence of length $$$1$$$ having sum $$$3$$$. In the third test case, there is no sequence of length $$$2$$$ having sum of elements equal to $$$1$$$, so there is no such interesting sequence. In the fourth test case, $$$p_1 = p_2 = p_3 = 0$$$, because bitwise XOR of an empty sequence is $$$0$$$.

import Data.Array
import Control.Monad (replicateM_)
import Control.Applicative (liftA2)

main = read <$> getLine >>= flip replicateM_ scase
scase = map read . words <$> getLine >>=
        \[n, m] -> case isInteresting n m of
                     Nothing -> putStrLn "No"
                     Just as -> putStrLn "Yes" >>
                                mapM_ (\a -> putStr (show a ++ " ")) as >>
                                putStrLn ""

isInteresting :: Int -> Int -> Maybe [Int]
isInteresting n m = if (m < n) || (mod n 2 == 0 && mod m 2 == 1)
                    then Nothing
                    else if mod n 2 == 1
                         then Just $ (m-n+1):replicate (n-1) 1
                         else let e = div (m-n+2) 2 in
                                Just $ e:e:replicate (n-2) 1

import Data.Array
import Control.Monad (replicateM_)
import Control.Applicative (liftA2)

main = read <$> getLine >>= flip replicateM_ scase
scase = map read . words <$> getLine >>=
        \[n, m] -> case isInteresting n m False of
                     Nothing -> putStrLn "No"
                     Just as -> putStrLn "Yes" >>
                                mapM_ (\a -> putStr (show a ++ " ")) as >>
                                putStrLn ""

isInteresting :: Int -> Int -> Bool -> Maybe [Int]
isInteresting n m r = if (m < n) || (mod n 2 == 0 && mod m 2 == 1)
                      then Nothing
                      else if mod n 2 == 1 || r
                           then Just $ (m-n+1):replicate (n-1) 1
                           else let ha = isInteresting (div n 2) (div m 2) True
                                in liftA2 (++) ha ha

import Data.Array
import Control.Monad (replicateM_)
import Control.Applicative (liftA2)

main = read <$> getLine >>= flip replicateM_ scase
scase = map read . words <$> getLine >>=
        \[n, m] -> case isInteresting n m False of
                     Nothing -> putStrLn "No"
                     Just as -> putStrLn "Yes" >>
                                mapM_ (\a -> putStr (show a ++ " ")) as >>
                                putStrLn ""

isInteresting :: Int -> Int -> Bool -> Maybe [Int]
isInteresting n m r = if (m < n) || (mod n 2 == 0 && mod m 2 == 1)
                      then Nothing
                      else if mod n 2 == 1
                           then Just $ (m-n+1):replicate (n-1) 1
                           else if r
                                then let m2 = div m 2
                                         n2 = div n 2
                                         half = (m2-n2+1):replicate (n2-1) 1
                                     in Just (half ++ half)
                                else let ha = isInteresting (div n 2) (div m 2) True
                                     in liftA2 (++) ha ha

import Data.Array
import Control.Monad (replicateM_)
import Control.Applicative (liftA2)

main = read <$> getLine >>= flip replicateM_ scase
scase = map read . words <$> getLine >>=
        \[n, m] -> case isInteresting n m of
                     Nothing -> putStrLn "No"
                     Just as -> putStrLn "Yes" >>
                                mapM_ (\a -> putStr (show a ++ " ")) as >>
                                putStrLn ""

isInteresting :: Int -> Int -> Maybe [Int]
isInteresting n m = if (m < n) || (mod n 2 == 0 && mod m 2 == 1)
                    then Nothing
                    else if mod n 2 == 1
                         then Just $ (m-n+1):replicate (n-1) 1
                         else let ha = isInteresting (div n 2) (div m 2) in
                                liftA2 (++) ha ha


Monocarp is playing a computer game once again. He is a wizard apprentice, who only knows a single spell. Luckily, this spell can damage the monsters.The level he's currently on contains $$$n$$$ monsters. The $$$i$$$-th of them appears $$$k_i$$$ seconds after the start of the level and has $$$h_i$$$ health points. As an additional constraint, $$$h_i \le k_i$$$ for all $$$1 \le i \le n$$$. All $$$k_i$$$ are different.Monocarp can cast the spell at moments which are positive integer amounts of second after the start of the level: $$$1, 2, 3, \dots$$$ The damage of the spell is calculated as follows. If he didn't cast the spell at the previous second, the damage is $$$1$$$. Otherwise, let the damage at the previous second be $$$x$$$. Then he can choose the damage to be either $$$x + 1$$$ or $$$1$$$. A spell uses mana: casting a spell with damage $$$x$$$ uses $$$x$$$ mana. Mana doesn't regenerate.To kill the $$$i$$$-th monster, Monocarp has to cast a spell with damage at least $$$h_i$$$ at the exact moment the monster appears, which is $$$k_i$$$.Note that Monocarp can cast the spell even when there is no monster at the current second.The mana amount required to cast the spells is the sum of mana usages for all cast spells. Calculate the least amount of mana required for Monocarp to kill all monsters.It can be shown that it's always possible to kill all monsters under the constraints of the problem.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of monsters in the level. The second line of the testcase contains $$$n$$$ integers $$$k_1 < k_2 < \dots < k_n$$$ ($$$1 \le k_i \le 10^9$$$) — the number of second from the start the $$$i$$$-th monster appears at. All $$$k_i$$$ are different, $$$k_i$$$ are provided in the increasing order. The third line of the testcase contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le k_i \le 10^9$$$) — the health of the $$$i$$$-th monster. The sum of $$$n$$$ over all testcases doesn't exceed $$$10^4$$$.

For each testcase, print a single integer — the least amount of mana required for Monocarp to kill all monsters.

NoteIn the first testcase of the example, Monocarp can cast spells $$$3, 4, 5$$$ and $$$6$$$ seconds from the start with damages $$$1, 2, 3$$$ and $$$4$$$, respectively. The damage dealt at $$$6$$$ seconds is $$$4$$$, which is indeed greater than or equal to the health of the monster that appears.In the second testcase of the example, Monocarp can cast spells $$$3, 4$$$ and $$$5$$$ seconds from the start with damages $$$1, 2$$$ and $$$3$$$, respectively.In the third testcase of the example, Monocarp can cast spells $$$4, 5, 7, 8$$$ and $$$9$$$ seconds from the start with damages $$$1, 2, 1, 1$$$ and $$$2$$$, respectively.

{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}

module Main where

import Control.Monad
import Data.Bifunctor
import Data.Function
import Data.Functor
import Data.List
import Data.Maybe
import Data.Ord
import Debug.Trace

removeElem :: Int -> [a] -> [a]
removeElem i xs = take i xs <> tail (drop i xs)

readNumbers = fmap (read @Integer) . words <$> getLine

main = do
  [t] <- readNumbers
  replicateM (fromInteger t) $ do
    [n] <- readNumbers
    ks <- readNumbers
    hs <- readNumbers
    print $
      let go :: [((Integer, Integer), Integer)] -> [((Integer, Integer), Integer)]
          go [] = []
          go (((ki, hi), dki) : khs') =
            let findInShade zu =
                  let (inShade, rest) = partition ((\ki' -> ki - hi - zu < ki' && ki' < ki) . fst . fst) khs'
                      maximalÜberStehend =
                        maximum $
                          (0 :) $ fmap (\((ki', hi'), _) -> hi' - hi - zu + ki - ki') inShade
                   in if maximalÜberStehend == 0
                        then (zu, inShade, rest)
                        else findInShade (zu + maximalÜberStehend)
                (maximalÜberStehend, inShade, rest) = findInShade 0
             in ((ki, hi + maximalÜberStehend), dki) : go (fmap (first \(ki', _) -> (ki', maximalÜberStehend + hi + ki' - ki)) inShade <> rest)
          khs' =
            go $
              traceShowId $
                reverse $
                  zipWith (\khi@(ki, _) prki -> (khi, ki - prki)) (zip ks hs) (0 : ks)
       in traceShow khs' $
            sum $
              khs' <&> \((ki, hi), dki) ->
                if hi > dki
                  then ((2 * hi - dki + 1) * dki) `div` 2
                  else (hi * (hi + 1)) `div` 2

-- sortBy (\a b -> comparing (Down . snd . fst) a b <> comparing (Down . fst .fst) a b)

{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BlockArguments #-}

module Main where

import Control.Monad
import Data.Maybe
import Data.List
import Data.Function
import Data.Functor
import Data.Ord
import Data.Bifunctor
import Debug.Trace

removeElem :: Int -> [a] -> [a]
removeElem i xs = take i xs <> tail (drop i xs)

readNumbers = fmap (read @Integer) . words <$> getLine

main = do
  [t] <- readNumbers
  replicateM (fromInteger t) $ do
        void readNumbers
        ks <- readNumbers
        hs <- readNumbers
        print $ let go :: [((Integer, Integer), Integer)] -> [((Integer, Integer), Integer)]
                    go [] = []
                    go (((ki,hi), dki):khs') =
                      let (inShade, rest) = partition ((\ki' -> ki - hi < ki' && ki' < ki) . fst . fst) khs'
                          maximalüberStehend = maximum $
                            (0:) $ fmap snd $ filter ((>= 0) . snd) $ map (\khi'@((ki', hi'), _) -> (khi', hi'-hi+ki-ki')) inShade
                        in ((ki, hi+maximalüberStehend), dki)
                           : (go $ fmap (first \(ki' ,_) -> (ki', maximalüberStehend + hi+ki'-ki)) inShade <> rest)
                    khs' = go $ traceShowId $
                      sortBy (\a b -> comparing (Down . snd . fst) a b <> comparing (Down . fst .fst) a b)
                      $ zipWith (\khi@(ki,_) prki -> (khi,ki - prki)) (zip ks hs) (0 : ks)
                 in traceShow khs' $ sum $ khs' <&> \((ki, hi), dki) -> if hi > dki
                                                 then ((2*hi-dki+1)*dki) `div` 2
                                                 else (hi*(hi+1)) `div` 2

{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BlockArguments #-}

module Main where

import           Control.Monad
import           Data.Bifunctor
import           Data.Function
import           Data.Functor
import           Data.List
import           Data.Maybe
import           Data.Ord
import           Debug.Trace

removeElem :: Int -> [a] -> [a]
removeElem i xs = take i xs <> tail (drop i xs)

readNumbers = fmap (read @Integer) . words <$> getLine

main = do
  [t] <- readNumbers
  replicateM (fromInteger t) $ do
    void readNumbers
    ks <- readNumbers
    hs <- readNumbers
    print
      $ let
          go
            :: [((Integer, Integer), Integer)]
            -> [((Integer, Integer), Integer)]
          go [] = []
          go (((ki, hi), dki) : khs') =
            let (inShade, rest) = partition
                  ((\ki' -> ki - hi < ki' && ki' < ki) . fst . fst)
                  khs'
                maximalüberStehend =
                  maximum $ (0 :) $ fmap snd $ filter ((>= 0) . snd) $ map
                    (\khi'@((ki', hi'), _) -> (khi', hi' - hi + ki - ki'))
                    inShade
            in  ((ki, hi + maximalüberStehend), dki)
                  : (  go
                    $  fmap
                         (first \(ki', _) ->
                           (ki', maximalüberStehend + hi + ki' - ki)
                         )
                         inShade
                    <> rest
                    )
          khs' =
            go $ traceShowId $ sortOn (Down . snd . fst) $ reverse $ zipWith
              (\khi@(ki, _) prki -> (khi, ki - prki))
              (zip ks hs)
              (0 : ks)
        in
          traceShow khs' $ sum $ khs' <&> \((ki, hi), dki) -> if hi > dki
            then ((2 * hi - dki + 1) * dki) `div` 2
            else (hi * (hi + 1)) `div` 2

{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BlockArguments #-}

module Main where

import Control.Monad
import Data.Maybe
import Data.List
import Data.Function
import Data.Functor
import Data.Ord
import Data.Bifunctor
import Debug.Trace

removeElem :: Int -> [a] -> [a]
removeElem i xs = take i xs <> tail (drop i xs)

readNumbers = fmap (read @Integer) . words <$> getLine

main = do
  [t] <- readNumbers
  replicateM (fromInteger t) $ do
        void readNumbers
        ks <- readNumbers
        hs <- readNumbers
        print $ let go :: [((Integer, Integer), Integer)] -> [((Integer, Integer), Integer)]
                    go [] = []
                    go (((ki,hi), dki):khs') =
                      let (inShade, rest) = partition ((\ki' -> ki - hi < ki' && ki' < ki) . fst . fst) khs'
                          maximalüberStehend = maximum $ (0:) $ fmap snd $ filter ((>= 0) . snd) $ map (\khi'@((ki', hi'), _) -> (khi', hi'-hi+ki-ki')) inShade
                        in ((ki, hi+maximalüberStehend), dki)
                           : (go $ fmap (first \(ki' ,_) -> (ki', maximalüberStehend + hi+ki'-ki)) inShade <> rest)
                    khs' = go $ traceShowId $
                      sortOn (Down . snd . fst) $
                      reverse
                      $ zipWith (\khi@(ki,_) prki -> (khi,ki - prki)) (zip ks hs) (0 : ks)
                 in traceShow khs' $ sum $ khs' <&> \((ki, hi), dki) -> if hi > dki
                                                 then ((2*hi-dki+1)*dki) `div` 2
                                                 else (hi*(hi+1)) `div` 2

{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BlockArguments #-}

module Main where

import Control.Monad
import Data.Maybe
import Data.List
import Data.Function
import Data.Functor
import Data.Ord
import Data.Bifunctor
import Debug.Trace

removeElem :: Int -> [a] -> [a]
removeElem i xs = take i xs <> tail (drop i xs)

readNumbers = fmap (read @Integer) . words <$> getLine

main = do
  [t] <- readNumbers
  replicateM (fromInteger t) $ do
        void readNumbers
        ks <- readNumbers
        hs <- readNumbers
        print $ let go :: [((Integer, Integer), Integer)] -> [((Integer, Integer), Integer)]
                    go [] = []
                    go (((ki,hi), dki):khs') =
                      let (inShade, rest) = partition ((\ki' -> ki - hi < ki' && ki' < ki) . fst . fst) khs'
                          maximalüberStehend = maximum $ (0:) $ fmap snd $ filter ((>= 0) . snd) $ map (\khi'@((ki', hi'), _) -> (khi', hi'-hi+ki-ki')) inShade
                        in ((ki, hi+maximalüberStehend), dki)
                           : (go $ fmap (first \(ki' ,_) -> (ki', maximalüberStehend + hi+ki'-ki)) inShade <> rest)
                    khs' = go $ traceShowId $
                      sortOn (Down . snd . fst) $
                      reverse
                      $ zipWith (\khi@(ki,_) prki -> (khi,ki - prki)) (zip ks hs) (0 : ks)
                 in traceShow khs' $ sum $ khs' <&> \((ki, hi), dki) -> if hi > dki
                                                 then (2*hi-dki+1)*dki `div` 2
                                                 else hi*(hi+1) `div` 2

{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BlockArguments #-}

module Main where

import Control.Monad
import Data.Maybe
import Data.List
import Data.Function
import Data.Functor
import Data.Ord
import Data.Bifunctor
import Debug.Trace

removeElem :: Int -> [a] -> [a]
removeElem i xs = take i xs <> tail (drop i xs)

readNumbers = fmap (read @Integer) . words <$> getLine

main = do
  [t] <- readNumbers
  replicateM (fromInteger t) $ do
        void readNumbers
        ks <- readNumbers
        hs <- readNumbers
        print $ let go :: [((Integer, Integer), Integer)] -> [((Integer, Integer), Integer)]
                    go [] = []
                    go khs@(((ki,hi), dki):khs') =
                      let (l, rest) = partition ((\ki' -> ki - hi < ki' && ki' < ki) . fst . fst) khs'
                          grß = filter ((>= 0). snd) $ map (\khi'@((ki', hi'), _) -> (khi', hi'-hi+ki-ki')) l
                          m = if null grß then 0 else maximum . fmap snd $ grß
                        in ((ki, hi+m), dki) : (go $ fmap (first \(ki' ,_) -> (ki', m + hi+ki'-ki)) l <> rest)
                    khs' = go $ traceShowId $ sortOn (Down . snd . fst) $ reverse $ zipWith (\khi@(ki,_) prki -> (khi,ki - prki)) (zip ks hs) (0 : ks)
                 in traceShow khs' $ sum $ khs' <&> \((ki, hi), dki) -> if hi > dki
                                                 then (2*hi-dki+1)*dki `div` 2
                                                 else hi*(hi+1) `div` 2

{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BlockArguments #-}

module Main where

import Control.Monad
import Data.Maybe
import Data.List
import Data.Function
import Data.Functor
import Data.Ord
import Data.Bifunctor
import Debug.Trace

removeElem :: Int -> [a] -> [a]
removeElem i xs = take i xs <> tail (drop i xs)

readNumbers = fmap (read @Integer) . words <$> getLine

main = do
  [t] <- readNumbers
  replicateM (fromInteger t) $ do
        void readNumbers
        ks <- readNumbers
        hs <- readNumbers
        print $ let go :: [((Integer, Integer), Integer)] -> [((Integer, Integer), Integer)]
                    go [] = []
                    go khs@(((ki,hi), dki):khs') =
                      let (l, rest) = partition ((\ki' -> ki - hi < ki' && ki' < ki) . fst . fst) khs'
                          grß = filter ((>= 0). snd) $ map (\khi'@((ki', hi'), _) -> (khi', hi'-hi+ki-ki')) l
                          m = if null grß then 0 else maximum . fmap snd $ grß
                        in ((ki, hi+m), dki) : (go $ fmap (first \(ki' ,_) -> (ki', m + hi+ki'-ki)) l <> rest)
                    khs' = go $ sortOn (snd . fst) $ reverse $ zipWith (\khi@(ki,_) prki -> (khi,ki - prki)) (zip ks hs) (0 : ks)
                 in traceShow khs' $ sum $ khs' <&> \((ki, hi), dki) -> if hi > dki
                                                 then (2*hi-dki+1)*dki `div` 2
                                                 else hi*(hi+1) `div` 2

{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BlockArguments #-}

module Main where

import Control.Monad
import Data.Maybe
import Data.List
import Data.Function
import Data.Functor
import Data.Ord
import Data.Bifunctor
import Debug.Trace

removeElem :: Int -> [a] -> [a]
removeElem i xs = take i xs <> tail (drop i xs)

readNumbers = fmap (read @Integer) . words <$> getLine

main = do
  [t] <- readNumbers
  replicateM (fromInteger t) $ do
        void readNumbers
        ks <- readNumbers
        hs <- readNumbers
        print $ let go :: [((Integer, Integer), Integer)] -> [((Integer, Integer), Integer)]
                    go [] = []
                    go khs@(((ki,hi), dki):khs') =
                      let (l, rest) = partition ((\ki' -> ki - hi <= ki' && ki' < ki) . fst . fst) khs'
                          grß = filter ((>= 0). snd) $ map (\khi'@((ki', hi'), _) -> (khi', hi'-hi+ki-ki')) l
                          m = if null grß then 0 else maximum . fmap snd $ grß
                        in ((ki, hi+m), dki) : (go $ fmap (first \(ki' ,_) -> (ki', m + hi+ki'-ki)) l <> rest)
                    khs' = go $ sortOn (snd . fst) $ reverse $ zipWith (\khi@(ki,_) prki -> (khi,ki - prki)) (zip ks hs) (0 : ks)
                 in traceShow khs' $ sum $ khs' <&> \((ki, hi), dki) -> if hi > dki
                                                 then (2*hi-dki+1)*dki `div` 2
                                                 else hi*(hi+1) `div` 2

{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BlockArguments #-}

module Main where

import Control.Monad
import Data.Maybe
import Data.List
import Data.Function
import Data.Functor
import Data.Ord
import Data.Bifunctor

removeElem :: Int -> [a] -> [a]
removeElem i xs = take i xs <> tail (drop i xs)

readNumbers = fmap (read @Integer) . words <$> getLine

main = do
  [t] <- readNumbers
  replicateM (fromInteger t) $ do
        void readNumbers
        ks <- readNumbers
        hs <- readNumbers
        print $ let go :: [((Integer, Integer), Integer)] -> [((Integer, Integer), Integer)]
                    go [] = []
                    go khs@(((ki,hi), dki):khs') =
                      let (l, rest) = partition ((\ki' -> ki - hi <= ki' && ki' < ki) . fst . fst) khs'
                          grß = filter ((>= 0). snd) $ map (\khi'@((ki', hi'), _) -> (khi', hi+ki'-ki - hi')) l
                          m = if null grß
                                then 0
                                else maximum . fmap snd $ grß
                        in ((ki, hi+m), dki) : (go $ fmap (first \(ki' ,_) -> (ki', m + hi+ki'-ki)) l <> rest)
                    khs' = go $ sortOn (snd . fst) $ zipWith (\khi@(ki,_) prki -> (khi,ki - prki)) (zip ks hs) (0 : ks)
                 in sum $ khs' <&> \((ki, hi), dki) -> if hi > dki
                                                 then (2*hi-dki+1)*dki `div` 2
                                                 else hi*(hi+1) `div` 2


Creatnx has $$$n$$$ mirrors, numbered from $$$1$$$ to $$$n$$$. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The $$$i$$$-th mirror will tell Creatnx that he is beautiful with probability $$$\frac{p_i}{100}$$$ for all $$$1 \le i \le n$$$.Creatnx asks the mirrors one by one, starting from the $$$1$$$-st mirror. Every day, if he asks $$$i$$$-th mirror, there are two possibilities:  The $$$i$$$-th mirror tells Creatnx that he is beautiful. In this case, if $$$i = n$$$ Creatnx will stop and become happy, otherwise he will continue asking the $$$i+1$$$-th mirror next day;  In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the $$$1$$$-st mirror again. You need to calculate the expected number of days until Creatnx becomes happy.This number should be found by modulo $$$998244353$$$. Formally, let $$$M = 998244353$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$.

The first line contains one integer $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — the number of mirrors. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq 100$$$).

Print the answer modulo $$$998244353$$$ in a single line.

NoteIn the first test, there is only one mirror and it tells, that Creatnx is beautiful with probability $$$\frac{1}{2}$$$. So, the expected number of days until Creatnx becomes happy is $$$2$$$.

module Main where

mm :: Integer
mm = 998244353

(|>) = flip (.)

mulmod :: Integer -> Integer -> Integer
mulmod x y = rem (x * y) mm

fexp x 0 = 1
fexp x e | even e = k
         | otherwise = mulmod x k
         where k' = fexp x (e `div` 2)
               k  = mulmod k' k'

inv :: Integer -> Integer
inv x = fexp x (mm-2)

inv100 = inv 100

solve :: [Integer] -> Integer
solve ps = mulmod (solveNum ps) (inv $ solveDen ps)

solveNum :: [Integer] -> Integer
solveNum ps = solveNum' ps 1
    where solveNum' (p:[]) x = x
          solveNum' (p:ps) x = rem (x + (solveNum' ps (mulmod x p))) mm

solveDen :: [Integer] -> Integer
solveDen ps = foldr mulmod 1 ps

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

module Main where

mm :: Integer
mm = 998244353

(|>) = flip (.)

(*.) x y = rem (x * y) mm
(+.) x y = rem (x + y) mm

fexp x 0 = 1
fexp x e | even e = k
         | otherwise = x *. k
         where k' = fexp x (e `div` 2)
               k  = k' *. k'

inv :: Integer -> Integer
inv x = fexp x (mm-2)

inv100 = inv 100

solve :: [Integer] -> Integer
solve ps = (solveNum ps) *. (inv $ solveDen ps)

solveNum :: [Integer] -> Integer
solveNum ps = solveNum' ps 1
    where solveNum' (p:[]) x = x
          solveNum' (p:ps) x = x +. (solveNum' ps (x *. p))

solveDen = foldr (*.) 1

solveLine = words |> map read |> map (* inv100) |> solve

main = interact $
    lines |> drop 1 |> map (show . solveLine) |> unlines


Polycarp has n dice d1, d2, ..., dn. The i-th dice shows numbers from 1 to di. Polycarp rolled all the dice and the sum of numbers they showed is A. Agrippina didn't see which dice showed what number, she knows only the sum A and the values d1, d2, ..., dn. However, she finds it enough to make a series of statements of the following type: dice i couldn't show number r. For example, if Polycarp had two six-faced dice and the total sum is A = 11, then Agrippina can state that each of the two dice couldn't show a value less than five (otherwise, the remaining dice must have a value of at least seven, which is impossible).For each dice find the number of values for which it can be guaranteed that the dice couldn't show these values if the sum of the shown values is A.

The first line contains two integers n, A (1 ≤ n ≤ 2·105, n ≤ A ≤ s) — the number of dice and the sum of shown values where s = d1 + d2 + ... + dn. The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 106), where di is the maximum value that the i-th dice can show.

Print n integers b1, b2, ..., bn, where bi is the number of values for which it is guaranteed that the i-th dice couldn't show them.

NoteIn the first sample from the statement A equal to 8 could be obtained in the only case when both the first and the second dice show 4. Correspondingly, both dice couldn't show values 1, 2 or 3.In the second sample from the statement A equal to 3 could be obtained when the single dice shows 3. Correspondingly, it couldn't show 1, 2, 4 or 5.In the third sample from the statement A equal to 3 could be obtained when one dice shows 1 and the other dice shows 2. That's why the first dice doesn't have any values it couldn't show and the second dice couldn't show 3.

main=getContents>>=putStrLn.unwords.map show.f.map read.words
f(n:a:x)=[d-min d(a-n+1)+max 1(a-sum x+d)-1|d<-x]

main :: IO ()
main = getContents >>= putStrLn . unwords . map show . solve . map read . words

solve :: [Integer] -> [Integer]
solve (n:a:ds) = [ d - min d (a - n + 1) + max 1 (a - sum ds + d) - 1 | d <- ds ]
solve _ = undefined

import Control.Applicative

solve :: [Integer] -> Integer -> [Integer]
solve ds a = map go ds
  where
    go d = d - (myMax - myMin) - 1
      where
        myMin = max 1 $ a - (max' - d)
        myMax = min d $ a - min' + 1
    min' = toInteger $ length ds
    max' = sum ds

main :: IO ()
main = do
  [n, a] <- map read <$> words <$> getLine
  ds <- map read <$> words <$> getLine
  putStrLn . unwords . map show $ solve ds a

import Control.Applicative

solve :: [Int] -> Int -> [Int]
solve ds a = map go ds
  where
    go d = d - (myMax - myMin) - 1
      where
        myMin = max 1 $ a - (max' - d)
        myMax = min d $ a - min' + 1
    min' = length ds
    max' = sum ds

main :: IO ()
main = do
  [n, a] <- map read <$> words <$> getLine
  ds <- map read <$> words <$> getLine
  putStrLn . unwords . map show $ solve ds a


Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!

The first line of the input contains three space-separated integers l, r and k (1 ≤ l ≤ r ≤ 1018, 2 ≤ k ≤ 109).

Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).

NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.

-- module Main where

-- import Control.Applicative

-- main :: IO ()
-- main = do
--     [l, r, k] <- (map (\s -> read s::Int) . words) <$> getLine
--     let top = ceiling $ logBase (fromIntegral k) (fromIntegral r)
--         result = [res | n <- [0, 1 .. top], let res = k^n, res >= l, res <= r]
--     if null result
--         then putStrLn "-1"
--         else putStrLn $ unwords $ map show result

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

getIntList :: IO [Integer]
getIntList = fmap read . words <$> getLine

out :: Show a => [a] -> IO ()
out as = putStrLn $ bool (unwords $ map show as) "-1" (null as)

main :: IO ()
main = out =<< sol <$> getIntList

sol :: Integral a => [a] -> [a]
sol [l,r,k] = takeWhile (<=r) . dropWhile (<l) $ fmap (k^) [ll..rr]
  where
      ll = round $ log (fromIntegral l)/log (fromIntegral k)
      rr = round $ log (fromIntegral r)/log (fromIntegral k)

module Main where

calc :: (Integer, Integer, Integer, Integer) -> [Integer]
calc (a, b, k, cur)
         | cur > b = []
         | cur >= a = [cur]++calc(a, b, k, cur*k)
         | otherwise = calc(a, b, k, cur*k)

emptytoneg :: [Integer] -> [Integer]
emptytoneg [] = [-1]
emptytoneg xs = xs

main = do
        args <- getContents
        let
            (l:r:k:xs) = words args
        putStrLn $ unwords $ map show $ emptytoneg $ calc(read l, read r, read k, 1)

main :: IO()
main = putStrLn . unwords . map show . proof . solve . map read . words =<< getLine

proof :: [Integer] -> [Integer]
proof [] = [-1]
proof x = x

solve :: [Integer] -> [Integer]
solve [l, r, k] = solve' 1
    where solve' :: Integer -> [Integer]
          solve' x | x < l = solve' (x * k)
                   | x > r = []
                   | otherwise = x : solve' (x * k)

import Data.Functor
import Data.List

getIntegers :: IO [Integer]
getIntegers = map read <$> words <$> getLine

parsePairs [] = []
parsePairs (x:y:rs) = (x, y) : parsePairs rs

solve :: Integer -> Integer -> Integer -> [Integer]
solve l r k = takeWhile (<=r) $ dropWhile (<l) $ iterate (*k) 1

main = do
    [l, r, k] <- getIntegers
    putStrLn $ let xs = solve l r k in
        if null xs then "-1" else intercalate " " (map show $ xs)

main = do
    line <- getLine
    let l:r:k:xs = getInts 3 line
    let br = ceiling $ logBase (fromIntegral k) (fromIntegral r)
    putStrLn $ foldr1 (++) $ ans $ map ((' ':) . show) [p | x <- [0,1..br], let p = k^x, p >= l, p <= r]

getInts :: Int -> String -> [Integer]

getInts 0 _ = []
getInts _ [] = []
getInts x str = map stringToInt $ take x $ words str

stringToInt :: String -> Integer

stringToInt str = read str :: Integer

ans [] = ["-1"]
ans y = y

main = do
        line <- getLine
        let l:r:k:xs = getInts 3 line
        let br = ceiling $ logBase (fromIntegral k) (fromIntegral r)
        putStrLn $ unwords $ ans $ map show [p | x <- [0,1..br], let p = k^x, p >= l, p <= r]

getInts :: Int -> String -> [Integer]

getInts 0 _ = []
getInts _ [] = []
getInts x str = map stringToInt $ take x $ words str

stringToInt :: String -> Integer

stringToInt str = read str :: Integer

ans [] = ["-1"]
ans y = y

main = do
	line <- getLine
	let l:r:k:xs = getInts 3 line
	let br = ceiling $ logBase (fromIntegral k) (fromIntegral r)
	putStrLn $ foldr1 (++) $ ans $ map ((' ':) . show) [p | x <- [0,1..br], let p = k^x, p >= l, p <= r]

getInts :: Int -> String -> [Integer]

getInts 0 _ = []
getInts _ [] = []
getInts x str = map stringToInt $ take x $ words str

stringToInt :: String -> Integer

stringToInt str = read str :: Integer

ans [] = ["-1"]
ans x = x

    main = do
        line <- getLine
        let l:r:k:xs = getInts 3 line
        let br = ceiling $ logBase (fromIntegral k) (fromIntegral r)
        putStrLn $ unwords $ ans $ map show [p | x <- [0,1..br], let p = k^x, p >= l, p <= r]

    getInts :: Int -> String -> [Integer]

    getInts 0 _ = []
    getInts _ [] = []
    getInts x str = map stringToInt $ take x $ words str

    stringToInt :: String -> Integer

    stringToInt str = read str :: Integer

    ans [] = ["-1"]
    ans x = x

module Main where

getRangePowers :: Integer -> Integer -> Integer -> [Integer]
getRangePowers l r k = [k ^ a | a <- [0 .. (ceiling ((logBase (fromIntegral k) (fromIntegral r)) :: Float))], k^a >= l, k^a <=r]

emptytoneg [] = [-1]
emptytoneg xs = xs

main = do
        line <- getLine
        let ws = words line
        let l = read (ws !! 0)
        let r = read (ws !! 1)
        let k = read (ws !! 2)
        let powers = getRangePowers l r k
        putStrLn $ unwords $ map show $ emptytoneg powers

import Control.Applicative
import Data.List

main= do
	[l,r,k]<-   map read.words  <$> getLine::IO [Integer]
	let x =   takeWhile (<=r) $ dropWhile (<l) [k^i|i<-[0..]]
	if x==[] then print (-1) else putStrLn $ intercalate " " $ map show x

module Main where

import Control.Applicative

f l r k acc n
    | res < l = f l r k acc (n+1)
    | res >= l && res <= r = f l r k (acc ++ [res]) (n+1)
    | otherwise = acc
        where res = k^n

main :: IO ()
main = do
    [l, r, k] <- (map (\s -> read s::Int) . words) <$> getLine
    let result = f l r k [] 0
    if null result
        then putStrLn "-1"
        else putStrLn $ unwords $ map show result

module Main where

import Control.Applicative

main :: IO ()
main = do
    [l, r, k] <- (map (\s -> read s::Int) . words) <$> getLine
    let top = ceiling $ logBase (fromIntegral k) (fromIntegral r)
        result = [res | n <- [0, 1 .. top], let res = k^n, res >= l, res <= r]
    if null result
        then putStrLn "-1"
        else putStrLn $ unwords $ map show result

module Main where

import Control.Applicative

f l r k acc n
    | res >= l && res <= r = f l r k (acc ++ [res]) (n+1)
    | otherwise = acc
        where res = k^n

main :: IO ()
main = do
    [l, r, k] <- (map (\s -> read s::Int) . words) <$> getLine
    let result = f l r k [] 0
    if null result
        then putStrLn "-1"
        else putStrLn $ unwords $ map show result

module Main where

import Control.Applicative

f :: Int -> Int -> Int -> [Int] -> Integer -> [Int]
-- f :: (Num a, Num b) => a -> a -> a -> [a] -> b -> [a]
f l r k acc n
    | res < l = f l r k acc (n+1)
    | res >= l && res <= r = f l r k (acc ++ [res]) (n+1)
    | otherwise = acc
        where res = k^n

main :: IO ()
main = do
    [l, r, k] <- (map (\s -> read s::Int) . words) <$> getLine
    let result = f l r k [] 0
    if null result
        then putStrLn "-1"
        else putStrLn $ unwords $ map show result

module Main where

import Control.Applicative

f l r k acc n
    | res < l = f l r k acc (n+1)
    | res >= l && res <= r = f l r k (acc ++ [res]) (n+1)
    | res > r = acc
        where res = k^n

main :: IO ()
main = do
    [l, r, k] <- (map (\s -> read s::Int) . words) <$> getLine
    let result = f l r k [] 0
    if null result
        then putStrLn "-1"
        else putStrLn $ unwords $ map show result

module Main where

calc :: (Int, Int, Int, Int) -> [Int]
calc (a, b, k, cur)
         | cur > b = []
         | cur >= a = [cur]++calc(a, b, k, cur*k)
         | otherwise = calc(a, b, k, cur*k)

emptytoneg :: [Int] -> [Int]
emptytoneg [] = [-1]
emptytoneg xs = xs

main = do
        args <- getContents
        let
            (l:r:k:xs) = words args
        putStrLn $ unwords $ map show $ emptytoneg $ calc(read l, read r, read k, 1)

import Data.Functor
import Data.List

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

parsePairs [] = []
parsePairs (x:y:rs) = (x, y) : parsePairs rs

solve :: Int -> Int -> Int -> [Int]
solve l r k = takeWhile (<=r) $ dropWhile (<l) $ iterate (*k) 1

main = do
    [l, r, k] <- getInts
    putStrLn $ let xs = solve l r k in
        if null xs then "-1" else intercalate " " (map show $ xs)

import Control.Applicative

main= do
	[l,r,k]<-   map read.words  <$> getLine::IO [Int]
	let x =  length $takeWhile (<=r) $ dropWhile (<l) [k^i|i<-[1..]]
	print $ if x==0 then (-1) else x

import Control.Applicative
import Data.List

main= do
	[l,r,k]<-   map read.words  <$> getLine::IO [Int]
	let x =   takeWhile (<=r) $ dropWhile (<l) [k^i|i<-[0..]]
	if x==[] then print (-1) else putStrLn $ intercalate " " $ map show x


The robot is placed in the top left corner of a grid, consisting of $$$n$$$ rows and $$$m$$$ columns, in a cell $$$(1, 1)$$$.In one step, it can move into a cell, adjacent by a side to the current one:   $$$(x, y) \rightarrow (x, y + 1)$$$;  $$$(x, y) \rightarrow (x + 1, y)$$$;  $$$(x, y) \rightarrow (x, y - 1)$$$;  $$$(x, y) \rightarrow (x - 1, y)$$$. The robot can't move outside the grid.The cell $$$(s_x, s_y)$$$ contains a deadly laser. If the robot comes into some cell that has distance less than or equal to $$$d$$$ to the laser, it gets evaporated. The distance between two cells $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ is $$$|x_1 - x_2| + |y_1 - y_2|$$$.Print the smallest number of steps that the robot can take to reach the cell $$$(n, m)$$$ without getting evaporated or moving outside the grid. If it's not possible to reach the cell $$$(n, m)$$$, print -1.The laser is neither in the starting cell, nor in the ending cell. The starting cell always has distance greater than $$$d$$$ to the laser.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The only line of each testcase contains five integers $$$n, m, s_x, s_y, d$$$ ($$$2 \le n, m \le 1000$$$; $$$1 \le s_x \le n$$$; $$$1 \le s_y \le m$$$; $$$0 \le d \le n + m$$$) — the size of the grid, the cell that contains the laser and the evaporating distance of the laser. The laser is neither in the starting cell, nor in the ending cell ($$$(s_x, s_y) \neq (1, 1)$$$ and $$$(s_x, s_y) \neq (n, m)$$$). The starting cell $$$(1, 1)$$$ always has distance greater than $$$d$$$ to the laser ($$$|s_x - 1| + |s_y - 1| > d$$$).

For each testcase, print a single integer. If it's possible to reach the cell $$$(n, m)$$$ from $$$(1, 1)$$$ without getting evaporated or moving outside the grid, then print the smallest amount of steps it can take the robot to reach it. Otherwise, print -1.

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}

{-# options_ghc -Wno-safe                        #-}     -- no warning if inferred as safe
{-# options_ghc -Wno-all-missed-specialisations  #-}     -- "Could not specialise..." when -O1
{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  cat -- input.txt | ./a.out  &&  cat -- laser.hs | xclip -selection clipboard  &&  echo COPIED  ||  echo ERROR)

import           Prelude               hiding (getLine)
import           Control.Arrow
import           Control.Monad
import qualified Data.ByteString.Char8 as B
import           Data.Char
import           Data.List

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        ri
    mapM_ (putStrLn.show.solve) tcs

solve [h,w,r,c,d] = answer
  where
    touchLe = (c - d <= 1)
    touchRi = (c + d >= w)
    touchUp = (r - d <= 1)
    touchDo = (r + d >= h)

    touchEnd = (md (h,w) (r,c) <= d)

    isBlocked = touchEnd || ((touchLe||touchDo) && (touchUp||touchRi))

    answer | isBlocked  = -1
           | otherwise  = md (1,1) (h,w)

md (ay,ax) (by,bx) = abs (ay - by) + abs (ax - bx)

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}

{-# options_ghc -Wno-safe                        #-}     -- no warning if inferred as safe
{-# options_ghc -Wno-all-missed-specialisations  #-}     -- "Could not specialise..." when -O1
{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  cat -- input.txt | ./a.out  &&  cat -- laser.hs | xclip -selection clipboard  &&  echo COPIED  ||  echo ERROR)

import           Prelude               hiding (getLine)
import           Control.Arrow
import           Control.Monad
import qualified Data.ByteString.Char8 as B
import           Data.Char
import           Data.List

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        ri
    mapM_ (putStrLn.show.solve) tcs

solve [h,w,r,c,d] = answer
  where
    touchLe = (c - d <= 1)
    touchRi = (c + d >= w)
    touchUp = (r - d <= 1)
    touchDo = (r + d >= h)

    touchEnd = (md (h,w) (r,c) <= d)

    isBlocked = touchEnd || (touchLe && touchUp) || (touchRi && touchDo)

    answer | isBlocked  = -1
           | otherwise  = md (1,1) (h,w)

md (ay,ax) (by,bx) = abs (ay - by) + abs (ax - bx)


The hero is addicted to glory, and is fighting against a monster. The hero has $$$n$$$ skills. The $$$i$$$-th skill is of type $$$a_i$$$ (either fire or frost) and has initial damage $$$b_i$$$. The hero can perform all of the $$$n$$$ skills in any order (with each skill performed exactly once). When performing each skill, the hero can play a magic as follows:   If the current skill immediately follows another skill of a different type, then its damage is doubled.  In other words,   If a skill of type fire and with initial damage $$$c$$$ is performed immediately after a skill of type fire, then it will deal $$$c$$$ damage;  If a skill of type fire and with initial damage $$$c$$$ is performed immediately after a skill of type frost, then it will deal $$$2c$$$ damage;  If a skill of type frost and with initial damage $$$c$$$ is performed immediately after a skill of type fire, then it will deal $$$2c$$$ damage;  If a skill of type frost and with initial damage $$$c$$$ is performed immediately after a skill of type frost , then it will deal $$$c$$$ damage. Your task is to find the maximum damage the hero can deal.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$), indicating the number of skills.  The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 1$$$), where $$$a_i$$$ indicates the type of the $$$i$$$-th skill. Specifically, the $$$i$$$-th skill is of type fire if $$$a_i = 0$$$, and of type frost if $$$a_i = 1$$$.  The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$), where $$$b_i$$$ indicates the initial damage of the $$$i$$$-th skill.  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output the maximum damage the hero can deal.

NoteIn the first test case, we can order the skills by $$$[3, 1, 4, 2]$$$, and the total damage is $$$100 + 2 \times 1 + 2 \times 1000 + 10 = 2112$$$.In the second test case, we can order the skills by $$$[1, 4, 2, 5, 3, 6]$$$, and the total damage is $$$3 + 2 \times 6 + 2 \times 4 + 2 \times 7 + 2 \times 5 + 2 \times 8 = 63$$$.In the third test case, we can order the skills by $$$[1, 2, 3]$$$, and the total damage is $$$1000000000 + 1000000000 + 1000000000 = 3000000000$$$.In the fourth test case, there is only one skill with initial damage $$$1$$$, so the total damage is $$$1$$$.

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

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

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

data TC = TC {n :: Int, as :: [Int], bs :: [Int64]}

type Output = Int64

input :: Scanner TC
input = do
  n <- int
  as <- n >< int
  bs <- n >< int64
  return TC {..}

solve :: TC -> Output
solve TC {..} = sum bs + extra fire frost + extra frost fire - too_much
  where
    [fire, frost] = [sort [x | (t', x) <- zip as bs, t' == t] | t <- [0, 1]]
    extra xs ys = xs >$> reverse >>> take (length ys) >>> sum
    too_much
      | length fire == length frost = minimum bs
      | otherwise = 0

output :: Int -> Output -> C.ByteString
output ix = showB

-------------------------- Template ------------------------------------------
-- Debug
debug :: Show a => a -> a

#ifdef ONLINE_JUDGE
debug = id
#else
debug a = trace (show a) a
#endif

-- helpers
(>$>) = flip ($)

infixl 0 >$>

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

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

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

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

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

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

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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

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

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

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

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

(><) = times

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

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

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

import Control.Monad (replicateM_)
import Data.List (sort)
main = read <$> getLine >>= flip replicateM_ scase
readI :: IO [Int]
readI = map read . words <$> getLine
scase = read <$> getLine >>=
        \n -> readI >>= \as -> readI >>= \bs -> print (maxDamage n as bs)

maxDamage :: Int -> [Int] -> [Int] -> Int
maxDamage n as bs = let (fires, ices) = partition as bs ([], [])
                        fl = length fires
                        il = length ices
                        (a, al, b, bl) = case compare fl il of
                                           EQ -> (ices, il, fires, fl)
                                           LT -> (ices, il, fires, fl)
                                           GT -> (fires, fl, ices, il)
                        partition [] [] (fs, is) = (reverse (sort fs), reverse (sort is))
                        partition (0:as) (f:bs) (fires, ices) =
                          partition as bs (f:fires, ices)
                        partition (1:as) (i:bs) (fires, ices) =
                          partition as bs (fires, i:ices)

                    in
                      if (al == bl)
                      then 2*(sum a + sum b) - minimum (a++b)
                      else let xs = take (al-1) a
                               x = last a
                           in
                             2*(sum b + sum (take bl xs)) + x + sum (drop bl xs)

import Control.Monad
import Data.List

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let n = read  input ::Int
        input <- getLine
        let a = map read . words $ input ::[Int]
        input <- getLine
        let b = map read . words $ input ::[Int]
        let a1 = sortBy (flip compare) . map snd .filter ((0==).fst) .zip a $ b
        let a2 = sortBy (flip compare) . map snd .filter ((1==).fst) .zip a $ b
        let mi = min (length a1) (length a2)
        let s1 = (sum $ zipWith (\x y -> 2*(x+y)) a1 a2)
        let s2 = (sum.drop mi $ a1) + (sum.drop mi $ a2)
        putStrLn .show. (s1+) $ if s2==0 then negate .minimum$ b else s2
    return ()


Little Masha loves arranging her toys into piles on the floor. And she also hates it when somebody touches her toys. One day Masha arranged all her n toys into several piles and then her elder brother Sasha came and gathered all the piles into one. Having seen it, Masha got very upset and started crying. Sasha still can't calm Masha down and mom is going to come home soon and punish Sasha for having made Masha crying. That's why he decides to restore the piles' arrangement. However, he doesn't remember at all the way the toys used to lie. Of course, Masha remembers it, but she can't talk yet and can only help Sasha by shouting happily when he arranges the toys in the way they used to lie. That means that Sasha will have to arrange the toys in every possible way until Masha recognizes the needed arrangement. The relative position of the piles and toys in every pile is irrelevant, that's why the two ways of arranging the toys are considered different if can be found two such toys that when arranged in the first way lie in one and the same pile and do not if arranged in the second way. Sasha is looking for the fastest way of trying all the ways because mom will come soon. With every action Sasha can take a toy from any pile and move it to any other pile (as a result a new pile may appear or the old one may disappear). Sasha wants to find the sequence of actions as a result of which all the pile arrangement variants will be tried exactly one time each. Help Sasha. As we remember, initially all the toys are located in one pile.

The first line contains an integer n (1 ≤ n ≤ 10) — the number of toys.

In the first line print the number of different variants of arrangement of toys into piles. Then print all the ways of arranging toys into piles in the order in which Sasha should try them (i.e. every next way must result from the previous one through the operation described in the statement). Every way should be printed in the following format. In every pile the toys should be arranged in ascending order of the numbers. Then the piles should be sorted in ascending order of the numbers of the first toys there. Output every way on a single line. Cf. the example to specify the output data format. If the solution is not unique, output any of them.

main = interact solve
solve input = output where
  n = read input :: Int
  output = unlines $ (show $ length xs):xs where
    xs = map (out2.partition) $ codes n
  codes 1 = [ [0] ]
  codes x = concat [ [s++[j]|j<-(xs i s)] | (i,s) <- (zip [1..] (codes (x-1)))]
    where
      xs y z = if odd y then (0:[m,m-1..1]) else ([1..m]++[0])
        where m = foldl1 max z + 1
  partition xs = [[y|(y,z)<-zip [1..] xs,z==x]|x<-[0..foldl1 max xs]]
  out1 [x] = (show x) ++ "}"
  out1 (x:xs) = (show x) ++ "," ++ (out1 xs)
  out2 [x] = '{':(out1 x)
  out2 (x:xs) = (out2 [x]) ++ "," ++ (out2 xs)


You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence.

The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct.

In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence.  Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them.

NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing.

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.List
import Data.Function
import Data.Graph
import Data.Tree

main = putStr . evalState app . B.words =<< B.getContents

app = do
  n <- poi
  xs <- replicateM n poi
  let r = solve n xs
  return $ unlines $ show (length r):map (\k -> unwords $ map show $ length k:k) r
  where
    pop = state $ \(x:xs) -> (x, xs)
    poi = fmap int pop
    int = maybe undefined fst . B.readInt

solve n = map flatten . scc . buildG (1, n) . zip [1..] . map fst . sortBy (compare `on` snd) . zip [1..]


You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.

The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.

Print minimal r so that each city will be covered by cellular network.

import Data.Maybe
import Data.Array
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
--import Debug.Trace

getInt = read `fmap` getLine :: IO Int
getInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]

main = do
    [n, m] <- getInts
    cities <- getInts
    towers <- getInts
    let thresholds = if m == 1 then listArray (1,1) [1000000000 + 1] else listArray (1,m-1) (getThresholds towers) :: Array Int Int
    let towers' = listArray (1,m) towers
    print $ solve thresholds towers' cities

getThresholds :: [Int] -> [Int]
getThresholds towers = zipWith (\x y -> (x + y) `div` 2) towers (tail towers)

solve thresholds towers cities = f cities 0 where
    numThresholds = length (elems thresholds)
    f [] soln = soln
    f (x:xs) soln = f xs (max (abs (nearest x - x)) soln)
    nearest x = towers ! (bin x 1 numThresholds)
    bin x i j
        | x > thresholds ! j        = j + 1
        | i >= j                    = j
        | thresholds ! mid == x     = mid
        | thresholds ! mid > x      = bin x i mid
        | otherwise                 = bin x (mid+1) j
        where mid = (i + j) `div` 2

import Control.Applicative
import Data.List
import Data.Maybe
import qualified Data.Map as Map

inf = 10 ^ 18

main = do
    _ <- getLine
    x <- sort . map read . words <$> getLine :: IO [Integer]
    y <- ((-inf) : ) . (++ [inf]) . sort . map read . words <$> getLine :: IO [Integer]
    print $ solve x y

solve [] _ = 0
solve (x:xs) (y1:y2:ys)
    | y2 < x    = solve (x:xs) (y2:ys)
    | otherwise = max (min (x - y1) (y2 - x)) (solve xs (y1:y2:ys))


You are given an array $$$a$$$ of length $$$2^n$$$. You should process $$$q$$$ queries on it. Each query has one of the following $$$4$$$ types:   $$$Replace(x, k)$$$ — change $$$a_x$$$ to $$$k$$$;  $$$Reverse(k)$$$ — reverse each subarray $$$[(i-1) \cdot 2^k+1, i \cdot 2^k]$$$ for all $$$i$$$ ($$$i \ge 1$$$);  $$$Swap(k)$$$ — swap subarrays $$$[(2i-2) \cdot 2^k+1, (2i-1) \cdot 2^k]$$$ and $$$[(2i-1) \cdot 2^k+1, 2i \cdot 2^k]$$$ for all $$$i$$$ ($$$i \ge 1$$$);  $$$Sum(l, r)$$$ — print the sum of the elements of subarray $$$[l, r]$$$. Write a program that can quickly process given queries.

The first line contains two integers $$$n$$$, $$$q$$$ ($$$0 \le n \le 18$$$; $$$1 \le q \le 10^5$$$) — the length of array $$$a$$$ and the number of queries. The second line contains $$$2^n$$$ integers $$$a_1, a_2, \ldots, a_{2^n}$$$ ($$$0 \le a_i \le 10^9$$$). Next $$$q$$$ lines contains queries — one per line. Each query has one of $$$4$$$ types:    "$$$1$$$ $$$x$$$ $$$k$$$" ($$$1 \le x \le 2^n$$$; $$$0 \le k \le 10^9$$$) — $$$Replace(x, k)$$$;  "$$$2$$$ $$$k$$$" ($$$0 \le k \le n$$$) — $$$Reverse(k)$$$;  "$$$3$$$ $$$k$$$" ($$$0 \le k < n$$$) — $$$Swap(k)$$$;  "$$$4$$$ $$$l$$$ $$$r$$$" ($$$1 \le l \le r \le 2^n$$$) — $$$Sum(l, r)$$$.  It is guaranteed that there is at least one $$$Sum$$$ query.

Print the answer for each $$$Sum$$$ query.

{-# LANGUAGE BangPatterns #-}

import Data.Bits
import Data.Int ( Int64 )
import Control.Monad ( replicateM, forM_ )

data SegTree t
  = Two { isum :: t,
          lst :: SegTree t,
          rst :: SegTree t }
  | One { isum :: t }
  deriving Show

readST :: Num t => Int -> [t] -> ([t], SegTree t)
readST 0 (x:xs) = (xs, One x)
readST n xs = let
  (xs',  lv) = readST (n-1) xs
  (xs'', rv) = readST (n-1) xs'
  in  (xs'',  Two (isum lv + isum rv) lv rv)

querySum :: Num t => SegTree t -> Int -> Int -> Int -> t
querySum st size mask count
  | count == 0  = 0
  | count == size  = isum st
  | otherwise = let
  nextBit = shiftR size 1
  (lv, rv) = if  nextBit .&. mask == 0
    then  (lst st, rst st)
    else  (rst st, lst st)
  in case  nextBit .&. count  of
  0 -> querySum lv nextBit mask count
  _ -> isum lv + querySum rv nextBit mask (xor count nextBit)

updateST :: Num t => SegTree t -> Int -> Int -> t -> SegTree t
updateST (One _oldVal) 1 0 newVal = One newVal
updateST (Two _ lv rv) size ix newVal = let
  nextBit = shiftR size 1
  (nlv, nrv) = case  nextBit .&. ix  of
    0 -> (updateST lv nextBit ix newVal, rv)
    _ -> (lv, updateST rv nextBit (xor ix nextBit) newVal)
  in  Two (isum nlv + isum nrv) nlv nrv
updateST _ _ _ _ = error "updateST: a bit of a problem? No? Not funny? OK."

data Query
  = Replace Int Int64
  | Reverse Int
  | Swap Int
  | Sum Int Int

processQueries :: SegTree Int64 -> Int -> Int -> [Query] -> [Int64]
processQueries = let
  step (!st, !size, !currMask, _) currQuery = case  currQuery  of
    Replace oneBasedIx val -> let
      origIx = xor currMask (oneBasedIx - 1)
      in (updateST st size origIx val, size, currMask, Nothing)
    Reverse k
      -> (st, size, xor currMask (shiftL 1 k - 1), Nothing)
    Swap k
      -> (st, size, xor currMask (shiftL 1 k), Nothing)
    Sum lep rep -> let
      [lsum, rsum] = map (querySum st size currMask) [lep - 1, rep]
      in (st, size, currMask, Just (rsum - lsum))
  in  \st size currMask qs ->
  [x | (_, _, _, Just x) <- scanl step (st, size, currMask, Nothing) qs]

toQuery :: [Int64] -> Query
toQuery li = let  fi = fromIntegral  in  case  li  of
  [1, x, k] -> Replace (fi x) k
  [2, k] -> Reverse (fi k)
  [3, k] -> Swap (fi k)
  [4, l, r] -> Sum (fi l) (fi r)
  _ -> error "invalid query format"

main :: IO ()
main = do
  [n, q] <- map read . words <$> getLine
  a <- map read . words <$> getLine
  let
    (xsas, st) = readST n a
    size = shiftL 1 n
  if  null xsas  then  pure ()  else  print "format error"
  queries <- replicateM q (toQuery . map read . words <$> getLine)
  forM_ (processQueries st size 0 queries) print

{-# LANGUAGE BangPatterns #-}

import Data.Bits
import Data.Int ( Int64 )
import Control.Monad ( replicateM, forM_ )

data SegTree t
  = Two { isum :: t,
          lst :: SegTree t,
          rst :: SegTree t }
  | One { isum :: t }
  deriving Show

readST :: Num t => Int -> [t] -> ([t], SegTree t)
readST 0 (x:xs) = (xs, One x)
readST n xs = let
  (xs',  lv) = readST (n-1) xs
  (xs'', rv) = readST (n-1) xs'
  in  (xs'',  Two (isum lv + isum rv) lv rv)

querySum :: Num t => SegTree t -> Int -> Int -> Int -> t
querySum st size mask count
  | count == 0  = 0
  | count == size  = isum st
  | otherwise = let
  nextBit = shiftR size 1
  (lv, rv) = if  nextBit .&. mask == 0
    then  (lst st, rst st)
    else  (rst st, lst st)
  in case  nextBit .&. count  of
  0 -> querySum lv nextBit mask count
  _ -> isum lv + querySum rv nextBit mask (xor count nextBit)

updateST :: Num t => SegTree t -> Int -> Int -> t -> SegTree t
updateST (One _oldVal) 1 0 newVal = One newVal
updateST (Two _ lv rv) size ix newVal = let
  nextBit = shiftR size 1
  (nlv, nrv) = case  nextBit .&. ix  of
    0 -> (updateST lv nextBit ix newVal, rv)
    _ -> (lv, updateST rv nextBit (xor ix nextBit) newVal)
  in  Two (isum nlv + isum nrv) nlv nrv
updateST _ _ _ _ = error "updateST: a bit of a problem? No? Not funny? OK."

data Query
  = Replace Int Int64
  | Reverse Int
  | Swap Int
  | Sum Int Int

processQueries :: SegTree Int64 -> Int -> Int -> [Query] -> [Int64]
processQueries = let
  step (!st, !size, !currMask, _) currQuery = case  currQuery  of
    Replace oneBasedIx val
      -> (updateST st size (oneBasedIx-1) val, size, currMask, Nothing)
    Reverse k
      -> (st, size, xor currMask (shiftL 1 k - 1), Nothing)
    Swap k
      -> (st, size, xor currMask (shiftL 1 k), Nothing)
    Sum lep rep -> let
      [lsum, rsum] = map (querySum st size currMask) [lep - 1, rep]
      in (st, size, currMask, Just (rsum - lsum))
  in  \st size currMask qs ->
  [x | (_, _, _, Just x) <- scanl step (st, size, currMask, Nothing) qs]

toQuery :: [Int64] -> Query
toQuery li = let  fi = fromIntegral  in  case  li  of
  [1, x, k] -> Replace (fi x) k
  [2, k] -> Reverse (fi k)
  [3, k] -> Swap (fi k)
  [4, l, r] -> Sum (fi l) (fi r)
  _ -> error "invalid query format"

main :: IO ()
main = do
  [n, q] <- map read . words <$> getLine
  a <- map read . words <$> getLine
  let
    (xsas, st) = readST n a
    size = shiftL 1 n
  if  null xsas  then  pure ()  else  print "format error"
  queries <- replicateM q (toQuery . map read . words <$> getLine)
  forM_ (processQueries st size 0 queries) print


The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts $$$h$$$ hours and each hour lasts $$$m$$$ minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from $$$0$$$ to $$$h-1$$$ and minutes are numbered from $$$0$$$ to $$$m-1$$$.  That's how the digits are displayed on the clock. Please note that digit $$$1$$$ is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day).The image of the clocks in the mirror is reflected against a vertical axis.  The reflection is not a valid time.The reflection is a valid time with $$$h=24$$$, $$$m = 60$$$. However, for example, if $$$h=10$$$, $$$m=60$$$, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment $$$s$$$ and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid.It can be shown that with any $$$h$$$, $$$m$$$, $$$s$$$ such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest.You are asked to solve the problem for several test cases.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. The next $$$2 \cdot T$$$ lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers $$$h$$$, $$$m$$$ ($$$1 \le h, m \le 100$$$). The second line contains the start time $$$s$$$ in the described format HH:MM.

For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct.

NoteIn the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct.

import Control.Monad
import Data.Maybe
import Text.Printf
import qualified Data.ByteString.Char8 as C

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

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    [hh, mm] <- getInts
    [h0, m0] <- map (fst . fromJust . C.readInt) . C.split ':' <$> C.getLine
    let
      rev '0' = Just '0'
      rev '1' = Just '1'
      rev '2' = Just '5'
      rev '5' = Just '2'
      rev '8' = Just '8'
      rev _ = Nothing
      revTwo [c1, c2] = do
        c1' <- rev c1
        c2' <- rev c2
        return [c2', c1']
      revTime h m = do
        s' <- revTwo $ printf "%02d" h
        t' <- revTwo $ printf "%02d" m
        guard $ read t' < hh && read s' < mm
        return $ printf "%02d" h ++ ":" ++ printf "%02d" m
      toRev o = revTime h' m'
        where
        o' = o `mod` (hh * mm)
        h' = o' `quot` mm
        m' = o' `mod` mm
      result = fromJust $ toRev $ head $ filter (isJust . toRev) [h0 * mm + m0 .. ]
    C.putStrLn $ C.pack result

-- Michael V. Antosha
-- 2021
-- Michael.Antosha@gmail.com

-- http://codeforces.com/contest/1493/problem/B   (mirror clock)

import qualified Data.List as List

import Text.Printf (printf)

main = interact $ unlines . map solveTC . linePairs . tail . lines

solveTC (hh, mm, strTime) = goodStrTime
  where
    (Just goodStrTime) = (List.find isGoodStrTime . map toStrTime) [toMinutes strTime ..]

    isGoodStrTime tm
        | '?' `elem` rev     = False
        | hours   rev >= hh  = False
        | minutes rev >= mm  = False
        | otherwise          = True
      where
        rev = (map mirrorChar . reverse) tm

    toMinutes tm = minutes tm + (mm * hours tm)

    toStrTime tmMinutes = printf "%02d:%02d" (m `div` mm) (m `mod` mm)
      where
        m = tmMinutes `mod` (hh * mm)

hours   [ hiH,  loH, ':', _hiM, _loM] = readI [hiH, loH]
minutes [_hiH, _loH, ':',  hiM,  loM] = readI [hiM, loM]

mirrorChar = f
  where
    f '0' = '0'
    f '1' = '1'
    f '2' = '5'
    f '5' = '2'
    f '8' = '8'
    f ':' = ':'
    f _ch = '?'

linePairs [] = []
linePairs [_line] = error "bad input (no pair)"
linePairs (strHM:strTime:ls) = (hh, mm, strTime) : linePairs ls
  where
    [hh, mm] = (map readI . words) strHM

readI s = read s :: Int

module Main where

import Control.Monad
import Data.Maybe

main :: IO ()
main = do
    n <- ((read :: String -> Int) <$> getLine)
--    putStrLn (show n)
    replicateM_ n action

action :: IO ()
action = do
    [h, m] <- (map (read :: String -> Int) . words) <$> getLine
    time <- getLine
    let res = dropWhile (not . mirror h m) (flow h m time)
    putStrLn $ head res

flow :: Int -> Int -> String -> [String]
flow h m initial@([h1,h2,_,m1,m2]) = map (\(_, _, r) -> r) $ iterate inc (read [h1,h2], read [m1,m2], initial)
  where
    show2 x
        | x < 10 = '0':show x
        | otherwise = show x
    showTime ch cm = show2 ch ++ ':' : show2 cm
    maxM = m - 1
    maxH = h - 1
    inc :: (Int, Int, String) -> (Int, Int, String)
    inc (ch, cm, _)
        | cm < maxM = (ch, cm + 1, showTime ch (cm + 1))
        | ch < maxH = (ch + 1, 0, showTime (ch + 1) 0)
        | otherwise = (0, 0, "00:00")

mirror :: Int -> Int -> String -> Bool
mirror h m time = fromMaybe False (checkTime <$> (mir time))
  where
    checkTime :: String -> Bool
    checkTime (m2:m1:_:h2:h1:[]) = (read [h1,h2]) < h && (read [m1,m2]) < m
    mir :: String -> Maybe String
    mir s = mapM mi s
    mi :: Char -> Maybe Char
    mi c = case c of
        '0' -> Just c
        '1' -> Just c
        '8' -> Just c
        ':' -> Just c
        '2' -> Just '5'
        '5' -> Just '2'
        otherwise -> Nothing

import Control.Monad
import Data.Maybe
import Text.Printf
import qualified Data.ByteString.Char8 as C

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

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    [hh, mm] <- getInts
    [h0, m0] <- map (fst . fromJust . C.readInt) . C.split ':' <$> C.getLine
    let
      rev '0' = Just '0'
      rev '1' = Just '1'
      rev '2' = Just '2'
      rev '5' = Just '5'
      rev '8' = Just '8'
      rev _ = Nothing
      revTwo [c1, c2] = do
        c1' <- rev c1
        c2' <- rev c2
        return [c2', c1']
      revTime h m = do
        s' <- revTwo $ printf "%02d" h
        t' <- revTwo $ printf "%02d" m
        guard $ read t' < hh && read s' < mm
        return $ printf "%02d" h ++ ":" ++ printf "%02d" m
      toRev o = revTime h' m'
        where
        o' = o `mod` (hh * mm)
        h' = o' `quot` mm
        m' = o' `mod` mm
      result = fromJust $ toRev $ head $ filter (isJust . toRev) [h0 * mm + m0 .. ]
    C.putStrLn $ C.pack result