Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade ai for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write bi essays. He can raise the exam grade multiple times.What is the minimum number of essays that Vanya needs to write to get scholarship?

The first line contains three integers n, r, avg (1 ≤ n ≤ 105, 1 ≤ r ≤ 109, 1 ≤ avg ≤ min(r, 106)) — the number of exams, the maximum grade and the required grade point average, respectively. Each of the following n lines contains space-separated integers ai and bi (1 ≤ ai ≤ r, 1 ≤ bi ≤ 106).

In the first line print the minimum number of essays.

NoteIn the first sample Vanya can write 2 essays for the 3rd exam to raise his grade by 2 points and 2 essays for the 4th exam to raise his grade by 1 point.In the second sample, Vanya doesn't need to write any essays as his general point average already is above average.

import Data.List
main = interact $ show . f . map read . tail . words
f (r:avg:x) = h r (max 0 $ g avg x) $ sortBy j $ i x
g _ [] = 0
g avg (x:y:z) = avg - x + g avg z
i [] = []
i (x:y:z) = ((x,y):i z)
j (a,b) (c,d) | b < d = LT | b > d = GT | otherwise = EQ
h r n [] = n
h r n ((a,b):c) | d >= n = n * b | otherwise = d*b + h r (n-d) c where d = r - a


Pasha has recently bought a new phone jPager and started adding his friends' phone numbers there. Each phone number consists of exactly n digits.Also Pasha has a number k and two sequences of length n / k (n is divisible by k) a1, a2, ..., an / k and b1, b2, ..., bn / k. Let's split the phone number into blocks of length k. The first block will be formed by digits from the phone number that are on positions 1, 2,..., k, the second block will be formed by digits from the phone number that are on positions k + 1, k + 2, ..., 2·k and so on. Pasha considers a phone number good, if the i-th block doesn't start from the digit bi and is divisible by ai if represented as an integer. To represent the block of length k as an integer, let's write it out as a sequence c1, c2,...,ck. Then the integer is calculated as the result of the expression c1·10k - 1 + c2·10k - 2 + ... + ck.Pasha asks you to calculate the number of good phone numbers of length n, for the given k, ai and bi. As this number can be too big, print it modulo 109 + 7.

The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ min(n, 9)) — the length of all phone numbers and the length of each block, respectively. It is guaranteed that n is divisible by k. The second line of the input contains n / k space-separated positive integers — sequence a1, a2, ..., an / k (1 ≤ ai < 10k). The third line of the input contains n / k space-separated positive integers — sequence b1, b2, ..., bn / k (0 ≤ bi ≤ 9).

Print a single integer — the number of good phone numbers of length n modulo 109 + 7.

main = interact $ show . solve . parse
  where parse = filter (not . null) . map (map read . words) . lines

mod' = (`mod` (10^9+7))

solve :: [[Integer]] -> Integer
solve [[_, k], as, bs] = product' xs
  where
    product' = foldr (\x y -> mod' (x*y)) 1
    xs = zipWith solveBlock as bs
    solveBlock x y = mod' $ below 10 - below (y+1) + below y
      where
        below n
          | n <= 0 = 0
          | otherwise = 1 + (n * 10^(k-1) - 1) `div` x

--fast read
import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Control.Applicative
modulo=1000000007
readInts a = fmap (map (fst . fromJust)) $ fmap (map B.readInteger) $ fmap B.words a
readLists = readInts $ B.getLine
readLLists = fmap (map (fst . fromJust)) $ fmap (map B.readInteger) $ fmap B.lines $ B.getContents
readMatrix = fmap readInts $ fmap B.lines $ B.getContents
getModLessNum::Integer->Integer->Integer -> Integer
getModLessNum n a m
  | n-1-m < 0 = 0
  | otherwise = 1 + div (n-m-1) a -- fromIntegral $ length $ filter (\x -> mod x a == m) [0..(n-1)]
getModNum::Integer->Integer->Integer
getModNum k a = getModLessNum (10^k) a 0
getModNumNot::Integer->Integer->Integer->Integer
getModNumNot k a b = getModLessNum (10^(k-1)) a (mod (a - (mod (b*(10^(k-1))) a)) a)
getAns::Integer -> Integer -> Integer -> Integer
getAns k a b = (getModNum k a) - (getModNumNot k a b)
main = do
  [n,k] <- readLists
  a <- readLists
  b <- readLists
  let ans = foldr1 (\x y -> mod (x*y) modulo) [getAns k a0 b0|(a0,b0) <- zip a b]
  print $ ans

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

modn :: Int64
modn = 1000000007

nums k a b = (10^k-1) `div` a - (firstDigit b) + (if b == 0 then 0 else 1)
  where firstDigit l
            | l == 0    = (10^(k-1) - 1) `div` a
            | otherwise = ((l+1) * 10^(k-1) - 1) `div` a - (l*10^(k-1) - 1) `div` a

main :: IO ()
main = do
    [n, k] <- map (read::String->Int64) . words <$> getLine
    as <- map (read::String->Int64) . words <$> getLine
    bs <- map (read::String->Int64) . words <$> getLine
    let blocks = zipWith (nums k) as bs
    print $ foldl' (\a -> \b -> a*b `mod` modn) 1 blocks

import Control.Applicative

solve :: Integer -> (Integer,Integer) -> Integer
solve k (a,b) = num - rm
    where
        num = (10^k - 1) `div` a + 1
        rm = (+ 1) . (`div` a) . max (-1) $ ((b+1) * 10^(k-1) - 1) - ((b * 10^(k-1) - 1) `div` a + 1) * a

main :: IO ()
main = do
    [n,k] <- map read . words <$> getLine
    a <- map read . words <$> getLine
    b <- map read . words <$> getLine
    print . foldr1 (((`mod` 1000000007) .) . (*)) . map ((`mod` 1000000007) . solve k) $ zip a b

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

modn :: Int
modn = 1000000007

nums k a b = (10^k-1) `div` a - (firstDigit b) + (if b == 0 then 0 else 1)
  where firstDigit l
            | l == 0    = (10^(k-1) - 1) `div` a
            | otherwise = ((l+1) * 10^(k-1) - 1) `div` a - (l*10^(k-1) - 1) `div` a

main :: IO ()
main = do
    [n, k] <- map (read::String->Int) . words <$> getLine
    as <- map (read::String->Int) . words <$> getLine
    bs <- map (read::String->Int) . words <$> getLine
    let blocks = zipWith (nums k) as bs
    print $ foldl' (\a -> \b -> a*b `mod` modn) 1 blocks


Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials.He considers a polynomial valid if its degree is n and its coefficients are integers not exceeding k by the absolute value. More formally:Let a0, a1, ..., an denote the coefficients, so . Then, a polynomial P(x) is valid if all the following conditions are satisfied:  ai is integer for every i;  |ai| ≤ k for every i;  an ≠ 0. Limak has recently got a valid polynomial P with coefficients a0, a1, a2, ..., an. He noticed that P(2) ≠ 0 and he wants to change it. He is going to change one coefficient to get a valid polynomial Q of degree n that Q(2) = 0. Count the number of ways to do so. You should count two ways as a distinct if coefficients of target polynoms differ.

The first line contains two integers n and k (1 ≤ n ≤ 200 000, 1 ≤ k ≤ 109) — the degree of the polynomial and the limit for absolute values of coefficients. The second line contains n + 1 integers a0, a1, ..., an (|ai| ≤ k, an ≠ 0) — describing a valid polynomial . It's guaranteed that P(2) ≠ 0.

Print the number of ways to change one coefficient to get a valid polynomial Q that Q(2) = 0.

NoteIn the first sample, we are given a polynomial P(x) = 10 - 9x - 3x2 + 5x3.Limak can change one coefficient in three ways:  He can set a0 =  - 10. Then he would get Q(x) =  - 10 - 9x - 3x2 + 5x3 and indeed Q(2) =  - 10 - 18 - 12 + 40 = 0.  Or he can set a2 =  - 8. Then Q(x) = 10 - 9x - 8x2 + 5x3 and indeed Q(2) = 10 - 18 - 32 + 40 = 0.  Or he can set a1 =  - 19. Then Q(x) = 10 - 19x - 3x2 + 5x3 and indeed Q(2) = 10 - 38 - 12 + 40 = 0. In the second sample, we are given the same polynomial. This time though, k is equal to 12 instead of 109. Two first of ways listed above are still valid but in the third way we would get |a1| > k what is not allowed. Thus, the answer is 2 this time.

large=123456789123456789
main=interact$show.f1.map read.tail.words
f1 (a:b)=f3 a 0 b $(reverse.f2 a 0.reverse) b
f2 a b [c]=[]
f2 a b (c:d)=if abs e>a then large:f2 a large d else e:f2 a e d where e=b*2+c
f3 a b [c] _=if abs b<=a && b/=0 then 1 else 0
f3 a b (c:d) (e:f)=if e/=large && abs (e*2+b)<=a then 1+g else g where g=f4 a (b+c) d f
f4 a b c d=if odd b then 0 else f3 a (div b 2) c d

import Data.Char
main = do nk <- getLine
          let n = (myRead.head.words) nk
          let k = (toInteger.myRead.last.words) nk
          sa <- getLine
          let a = (map toInteger.map myRead.words) sa
          let b = calc n a 0
          let s = scanr1 (\x y -> (if y > k * 10 then y else y * 2 + x)) (if last b < 0 then map (0 -) b else b)
          let ans = if last b < 0 then calc2 n k (map (0-) a) (map (0-) b) s else calc2 n k a b s
          putStrLn (show ans)
myRead :: String -> Int
myRead ('-':as) = 0 - foldl (\x y -> 10*x + (ord y - ord '0')) 0 as
myRead s = foldl (\x y -> 10*x + (ord y - ord '0')) 0 s
calc :: Int -> [Integer] -> Int -> [Integer]
calc 0 (a:[]) car = [toInteger car + a]
calc n (a:as) car = if bi < 0
                      then toInteger(mod (-bi) 2):calc (n-1) as (-(div (-bi) 2) - mod (-bi) 2)
                      else toInteger(mod bi 2):calc (n-1) as (div bi 2)
                    where bi = car + fromInteger a
calc2 :: Int -> Integer -> [Integer] -> [Integer] -> [Integer] -> Int
calc2 0 k (a:[]) (b:[]) (s:[]) = if abs (s - a) <= k && a /= s then 1 else 0
calc2 n k (a:as) (b:bs) (s:ss) | b /= 0 && abs (s - a) <= k = 1
                               | b /= 0 = 0
                               | abs (s - a) <= k = 1 + calc2 (n-1) k as bs ss
                               | otherwise = calc2 (n-1) k as bs ss

import Data.Char
main = do nk <- getLine
          let n = (read.head.words) nk
          let k = (toInteger.read.last.words) nk
          sa <- getLine
          let a = (map toInteger.map read.words) sa
          let b = calc n a 0
          let s = scanr1 (\x y -> (if y > k * 10 then y else y * 2 + x)) (if last b < 0 then map (0 -) b else b)
          let ans = if last b < 0 then calc2 n k (map (0-) a) (map (0-) b) s else calc2 n k a b s
          putStrLn (show ans)
myRead :: String -> Int
myRead ('-':as) = 0 - foldl (\x y -> 10*x + (ord y - ord '0')) 0 as
myRead s = foldl (\x y -> 10*x + (ord y - ord '0')) 0 s
calc :: Int -> [Integer] -> Int -> [Integer]
calc 0 (a:[]) car = [toInteger car + a]
calc n (a:as) car = if bi < 0
                      then toInteger(mod (-bi) 2):calc (n-1) as (-(div (-bi) 2) - mod (-bi) 2)
                      else toInteger(mod bi 2):calc (n-1) as (div bi 2)
                    where bi = car + fromInteger a
calc2 :: Int -> Integer -> [Integer] -> [Integer] -> [Integer] -> Int
calc2 0 k (a:[]) (b:[]) (s:[]) = if abs (s - a) <= k && a /= s then 1 else 0
calc2 n k (a:as) (b:bs) (s:ss) | b /= 0 && abs (s - a) <= k = 1
                               | b /= 0 = 0
                               | abs (s - a) <= k = 1 + calc2 (n-1) k as bs ss
                               | otherwise = calc2 (n-1) k as bs ss


Vova plans to go to the conference by train. Initially, the train is at the point $$$1$$$ and the destination point of the path is the point $$$L$$$. The speed of the train is $$$1$$$ length unit per minute (i.e. at the first minute the train is at the point $$$1$$$, at the second minute — at the point $$$2$$$ and so on).There are lanterns on the path. They are placed at the points with coordinates divisible by $$$v$$$ (i.e. the first lantern is at the point $$$v$$$, the second is at the point $$$2v$$$ and so on).There is also exactly one standing train which occupies all the points from $$$l$$$ to $$$r$$$ inclusive.Vova can see the lantern at the point $$$p$$$ if $$$p$$$ is divisible by $$$v$$$ and there is no standing train at this position ($$$p \not\in [l; r]$$$). Thus, if the point with the lantern is one of the points covered by the standing train, Vova can't see this lantern.Your problem is to say the number of lanterns Vova will see during the path. Vova plans to go to $$$t$$$ different conferences, so you should answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of queries. Then $$$t$$$ lines follow. The $$$i$$$-th line contains four integers $$$L_i, v_i, l_i, r_i$$$ ($$$1 \le L, v \le 10^9$$$, $$$1 \le l \le r \le L$$$) — destination point of the $$$i$$$-th path, the period of the lantern appearance and the segment occupied by the standing train.

Print $$$t$$$ lines. The $$$i$$$-th line should contain one integer — the answer for the $$$i$$$-th query.

NoteFor the first example query, the answer is $$$3$$$. There are lanterns at positions $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$ and $$$10$$$, but Vova didn't see the lanterns at positions $$$4$$$ and $$$6$$$ because of the standing train.For the second example query, the answer is $$$0$$$ because the only lantern is at the point $$$51$$$ and there is also a standing train at this point.For the third example query, the answer is $$$1134$$$ because there are $$$1234$$$ lanterns, but Vova didn't see the lanterns from the position $$$100$$$ to the position $$$199$$$ inclusive.For the fourth example query, the answer is $$$0$$$ because the standing train covers the whole path.

{-# 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
    [len,v,l,r] <- map read . words <$> getLine :: IO [Int]
    print $ len`div`v - r`div`v + (l-1)`div`v

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

solve1 :: (Int, Int, Int, Int) -> Int
solve1 (d, v, l, r) = max 0 (lt - ls + 1) + max 0 (rt - rs + 1)
  where
    ls = 1
    lt = (l - 1) `div` v
    rs = (r + 1 + v - 1) `div` v
    rt = d `div` v

main :: IO ()
main = do
    n <- readLn
    dvlrs <- replicateM n $ do
        [d, v, l, r] <- unfoldr (B.readInt . B.dropWhile (== ' ')) <$> B.getLine
        return (d, v, l, r)
    mapM_ (print . solve1) dvlrs


Monocarp is playing yet another computer game. In this game, his character has to kill a dragon. The battle with the dragon lasts $$$100^{500}$$$ seconds, during which Monocarp attacks the dragon with a poisoned dagger. The $$$i$$$-th attack is performed at the beginning of the $$$a_i$$$-th second from the battle start. The dagger itself does not deal damage, but it applies a poison effect on the dragon, which deals $$$1$$$ damage during each of the next $$$k$$$ seconds (starting with the same second when the dragon was stabbed by the dagger). However, if the dragon has already been poisoned, then the dagger updates the poison effect (i.e. cancels the current poison effect and applies a new one).For example, suppose $$$k = 4$$$, and Monocarp stabs the dragon during the seconds $$$2$$$, $$$4$$$ and $$$10$$$. Then the poison effect is applied at the start of the $$$2$$$-nd second and deals $$$1$$$ damage during the $$$2$$$-nd and $$$3$$$-rd seconds; then, at the beginning of the $$$4$$$-th second, the poison effect is reapplied, so it deals exactly $$$1$$$ damage during the seconds $$$4$$$, $$$5$$$, $$$6$$$ and $$$7$$$; then, during the $$$10$$$-th second, the poison effect is applied again, and it deals $$$1$$$ damage during the seconds $$$10$$$, $$$11$$$, $$$12$$$ and $$$13$$$. In total, the dragon receives $$$10$$$ damage.Monocarp knows that the dragon has $$$h$$$ hit points, and if he deals at least $$$h$$$ damage to the dragon during the battle — he slays the dragon. Monocarp has not decided on the strength of the poison he will use during the battle, so he wants to find the minimum possible value of $$$k$$$ (the number of seconds the poison effect lasts) that is enough to deal at least $$$h$$$ damage to the dragon.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of the test case contains two integers $$$n$$$ and $$$h$$$ ($$$1 \le n \le 100; 1 \le h \le 10^{18}$$$) — the number of Monocarp's attacks and the amount of damage that needs to be dealt. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9; a_i < a_{i + 1}$$$), where $$$a_i$$$ is the second when the $$$i$$$-th attack is performed.

For each test case, print a single integer — the minimum value of the parameter $$$k$$$, such that Monocarp will cause at least $$$h$$$ damage to the dragon.

NoteIn the first example, for $$$k=3$$$, damage is dealt in seconds $$$[1, 2, 3, 5, 6, 7]$$$.In the second example, for $$$k=4$$$, damage is dealt in seconds $$$[2, 3, 4, 5, 6, 7, 10, 11, 12, 13]$$$.In the third example, for $$$k=1$$$, damage is dealt in seconds $$$[1, 2, 4, 5, 7]$$$.

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

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Data.List
--import Data.Array.Unboxed
import Data.Int -- don't be an idiot who gets hacked because of Int32

binSearch :: (Int64 -> Bool) -> Int64 -> Int64 -> Int64
{-# INLINE binSearch #-}
binSearch p = let
  go li ri = if  li == ri
    then  li
    else  let
    mi = li + quot (ri - li) 2
    in  if  p mi
    then  go li mi
    else  go (mi + 1) ri
  in  go

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    ~[h] <- getInt64s 1
    a <- getInt64s n
    let
      score k = (\step -> foldl' step k $ zipWith (-) (tail a) a) $ \acc sz ->
        acc + min k sz
      ans = binSearch (\k -> score k >= h) 0 h
    pure $ putInt64s [ans]

type SP = State [P.ByteString]

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

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

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

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

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

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

binSearch :: (Int -> Bool) -> Int -> Int -> Int
{-# INLINE binSearch #-}
binSearch p = let
  go li ri = if  li == ri
    then  li
    else  let
    mi = li + quot (ri - li) 2
    in  if  p mi
    then  go li mi
    else  go (mi + 1) ri
  in  go

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n, h] <- getInts 2
    a <- getInts n
    let
      score k = (\step -> foldl' step k $ zipWith (-) (tail a) a) $ \acc sz ->
        acc + min k sz
      ans = binSearch (\k -> score k >= h) 0 h
    pure $ putInts [ans]

type SP = State [P.ByteString]

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

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

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

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

import Control.Monad
import Data.Maybe
import Data.Int
import Data.List
import qualified Data.ByteString.Char8 as C
import qualified Data.Map.Strict as M
import Data.ByteString.Builder
import System.IO

parseInt :: (Integral a) => C.ByteString -> a
parseInt = fromIntegral . fst . fromJust . C.readInteger

getInts :: (Integral a) => IO [a]
getInts = map parseInt . C.words <$> C.getLine

update :: Num a => a -> Maybe a -> Maybe a
update delta value = case value of
  Nothing -> Just delta
  Just x -> Just (x + delta)

main :: IO ()
main = do
  [numCase] <- getInts
  output <- fmap mconcat $ replicateM numCase $ do
    [n, h] <- getInts :: IO [Int64]
    as <- getInts :: IO [Int64]
    let m1 = foldl' (\mp x -> M.alter (update 1) x mp) M.empty $ zipWith (-) (tail as) as
        m2 = snd $ M.mapAccumWithKey (\(c, t) x y -> let p = (c + y, t + x * y) in (p, p)) (0, 0) m1
        check x = case M.lookupLE x m2 of
                    Nothing -> n * x >= h
                    Just (_, (c, t)) -> (n - c) * x + t >= h
        func l r
          | l == r = l
          | check m = func l m
          | otherwise = func (m + 1) r
          where m = (l + r) `div` 2
    return $ int64Dec (func 1 h) <> charUtf8 '\n'
  hPutBuilder stdout output


Timur's grandfather gifted him a chessboard to practice his chess skills. This chessboard is a grid $$$a$$$ with $$$n$$$ rows and $$$m$$$ columns with each cell having a non-negative integer written on it. Timur's challenge is to place a bishop on the board such that the sum of all cells attacked by the bishop is maximal. The bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked. Help him find the maximal sum he can get.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains the integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 200$$$, $$$1 \leq m \leq 200$$$). The following $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element of the $$$i$$$-th line $$$a_{ij}$$$ is the number written in the $$$j$$$-th cell of the $$$i$$$-th row $$$(0\leq a_{ij} \leq 10^6)$$$ It is guaranteed that the sum of $$$n\cdot m$$$ over all test cases does not exceed $$$4\cdot10^4$$$.

For each test case output a single integer, the maximum sum over all possible placements of the bishop.

NoteFor the first test case here the best sum is achieved by the bishop being in this position:

import Data.Array
import Control.Monad (replicateM_, replicateM)

main :: IO ()
main = read <$> getLine >>= flip replicateM_ singleCase

singleCase :: IO ()
singleCase = map read . words <$> getLine >>=
             \([n, m]) -> replicateM n (map read . words <$> getLine) >>=
             print . maxSum . listArray ((1, 1), (n, m)) . concat

diagSum :: Int -> Array (Int, Int) Int -> Bool -> Int
diagSum dd a b = let ((1,1), (n, m)) = bounds a
                     bf True i = dd+i
                     bf False i = dd-i
                     -- par True = [(1-n) .. (m-1)]
                     -- par False = [2 .. (n+m)]
                 in
                   sum . map (a!) . filter (inRange (bounds a)) $
                   [(i, bf b i) | i <- [1..n]]

maxSum :: Array (Int, Int) Int -> Int
maxSum a = let ((1, 1), (n, m)) = bounds a
               pd = array (1-n, m-1) [(k, diagSum k a True) | k <- [(1-n)..(m-1)]]
               nd = array (2, n+m) [(k, diagSum k a False) | k <- [2..(n+m)]]
               f acc (i, j) = max acc ((pd!(j-i))+(nd!(j+i))-(a!(i, j)))
           in
             foldl f 0 $ range (bounds a)

readArr :: Int -> IO [[Int]]
readArr 0 = pure []
readArr i = do
  arr <- map (\s -> read s :: Int) <$> (words <$> getLine)
  ans <- readArr $ i - 1
  pure (arr: ans)

mergeL :: [Int] -> [Int] -> [Int]
mergeL a [] = a
mergeL (x: xs) (y: ys) = (x + y: mergeL xs ys)

mergeR :: [Int] -> [Int] -> [Int]
mergeR [] a = a
mergeR (x: xs) (y: ys) = (x + y: mergeR xs ys)

calcLD :: [[Int]] -> [Int]
calcLD (x: []) = x
calcLD (x: xs) = reverse $ mergeR (reverse x) (0: (reverse $ calcLD xs))

calcRD :: [[Int]] -> [Int]
calcRD (x: []) = x
calcRD (x: xs) = mergeR x (0: calcRD xs)

calcH :: Int -> [Int] -> [Int] -> Int -> Int -> [Int] -> Int
calcH _ _ _ _ _ [] = 0
calcH n ld rd i j (x: xs) = max (rd !! (i + j) + ld !! (j - i + n - 1) - x) (calcH n ld rd i (j + 1) xs)

calc :: Int -> [Int] -> [Int] -> Int -> [[Int]] -> Int
calc _ _ _ _ [] = 0
calc n ld rd i (x: xs) = max (calcH n ld rd i 0 x) (calc n ld rd (i + 1) xs)

for :: Int -> IO ()
for 0 = pure ()
for i = do
  (n: m: _) <- map (\s -> read s :: Int) <$> (words <$> getLine)
  arr <- readArr n
  print $ calc n (calcLD arr) (calcRD arr) 0 arr
  for $ i - 1

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


Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned over, both cars turned over. A car is good if it turned over in no collision. The results of the collisions are determined by an n × n matrix А: there is a number on the intersection of the і-th row and j-th column that describes the result of the collision of the і-th and the j-th car:    - 1: if this pair of cars never collided.  - 1 occurs only on the main diagonal of the matrix.  0: if no car turned over during the collision.  1: if only the i-th car turned over during the collision.  2: if only the j-th car turned over during the collision.  3: if both cars turned over during the collision. Susie wants to find all the good cars. She quickly determined which cars are good. Can you cope with the task?

The first line contains integer n (1 ≤ n ≤ 100) — the number of cars. Each of the next n lines contains n space-separated integers that determine matrix A.  It is guaranteed that on the main diagonal there are  - 1, and  - 1 doesn't appear anywhere else in the matrix. It is guaranteed that the input is correct, that is, if Aij = 1, then Aji = 2, if Aij = 3, then Aji = 3, and if Aij = 0, then Aji = 0.

Print the number of good cars and in the next line print their space-separated indices in the increasing order.

import Data.Array.Unboxed
import qualified Data.Set as Set
import Data.List

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

main = do
	cars <- getLine

	let
		n = read cars :: Int

	rows_list <- getLines n

	let
		rows = map read $ concat $ map words $ rows_list :: [Int]
		matrix = listArray ((1, 1), (n, n)) rows :: UArray (Int, Int) Int
		good_cars = findGoodCars matrix n

	putStrLn $ show $ length good_cars
	putStrLn $ intercalate " " $ map show good_cars

findGoodCars :: UArray (Int, Int) Int -> Int -> [Int]
findGoodCars matrix n = [1..n] \\ (Set.elems $ findBadCars matrix 1 Set.empty)
	where
		findBadCars :: UArray (Int, Int) Int -> Int -> Set.Set Int -> Set.Set Int
		findBadCars matrix row set
			| row > n = set
			| otherwise = findBadCars matrix (row+1) bad
			where
				bad = inspectCollisions matrix row 1 set
				inspectCollisions :: UArray(Int, Int) Int -> Int -> Int -> Set.Set Int -> Set.Set Int
				inspectCollisions matrix row col set
					| col > n = set
					| collision == 1 = inspectCollisions matrix row (col+1) (Set.insert row set)
					| collision == 2 = inspectCollisions matrix row (col+1) (Set.insert col set)
					| collision == 3 = inspectCollisions matrix row (col+1) (Set.insert row $ Set.insert col set)
					| otherwise = inspectCollisions matrix row (col + 1) set
					where
						collision = matrix!(row,col)

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

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

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

main = do
  n <- readLn
  rs <- replicateM n getInts

  let is = map snd $ filter (all (`elem` [0, -1, 2]) . fst) $ zip rs [1..]

  print $ length is
  putStrLn $ unwords $ map show is

import Data.List (intercalate)
answer::[[Int]] -> [Int]
answer a = toNumberList $ map (all (\x -> (x == -1 || x == 0 || x == 2))) a
toNumberList::[Bool] -> [Int]
toNumberList [] = []
toNumberList b = map fst $ filter (\x -> snd x) $ zip [1..] b
readInput::Int -> IO [[Int]]
readInput 0 = return []
readInput n = do
  w <- getLine
  let a = [read n::Int|n <- (words w)]
  next <- readInput (n-1)
  return ([a] ++ next)
printAnswer::[Int] -> IO ()
printAnswer [] = print 0
printAnswer x = do
  print (length x)
  putStrLn $ intercalate " " $ map show $ x
main = do
  w <- getLine
  let n = read w::Int
  m <- readInput n
  printAnswer $ answer m

module Main where
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8  as C
import Data.List
import Data.Maybe

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

getIntMat :: IO [[Int]]
getIntMat = map ((map (read::String->Int)) . words) . lines <$> getContents

main :: IO ()
main = do
  n <- getInt
  m <- getIntMat
  let gs = sol m
  print $ length gs
  putStrLn . unwords $ map show gs

sol :: [[Int]] -> [Int]
sol = map ((+1) . fst) . filter (\(i,xs) -> all good xs) . zip [0..]
  where
  good x = x==(-1) || x`mod`2==0

{-# LANGUAGE ScopedTypeVariables #-}

import Control.Monad

main = do
    n <- getLine >>= return.read
    m <- replicateM n getLine >>= return.(map good)
    let l = map snd $ filter fst $ zip m [1..n]
    putStrLn $ show $ length l
    putStrLn $ unwords $ map show l

good s = not $ any (\x -> x==1||x==3) ((map read)$words s)

main :: IO ()
main = getContents >>= printSolution . solve . map (map read . words) . tail . lines

solve :: [[Int]] -> [Int]
solve = map fst . filter (not . any (`elem` [1, 3]) . snd) . zip [1..]

printSolution :: Show a => [a] -> IO ()
printSolution xs = print (length xs) >> putStrLn (unwords (map show xs))

import Control.Monad
import Data.List

main = do
    n <- fmap read getLine
    xs <- forM [1..n] (\i -> do
        ys <- fmap (map read . words) getLine
        if 1 `elem` ys || 3 `elem` ys then return []
                                      else return [i]
        )
    let cxs = concat xs
    print $ length cxs
    putStrLn . intercalate " " . map show $ cxs

import Control.Monad
import Data.List

split key str = split_helper str [] where
    split_helper [] acc = if null acc then [] else [reverse acc]

    split_helper str acc =
        let
            c = head str
        in
            if head str == key then
                if null acc then
                    split_helper (tail str) []
                else
                    reverse acc : split_helper (tail str) []
            else
                split_helper (tail str) (c : acc)

solve n m i =
    if i > n then
        []
    else let
        rest = solve n (tail m) (i+1)
        good x = x < 0 || even x
    in
        if all (good . read) $ split ' ' (head m) then
            i : rest
        else
            rest

main = do
    n <- readLn
    m <- sequence $ take n $ repeat getLine
    let result = solve n m 1
    print $ length result
    when (length result > 0) $
        putStrLn $ concat $ intersperse " " $ map show result

import Control.Applicative
import Data.List

main= do
	n<-  read  <$>getLine::IO Int
	s<- map (map read). map words. lines <$> getContents ::IO [[Int]]
	let t=  map (length . take 1. filter (\z-> elem z [1,3])) s
	let t1= map snd $ filter (\z-> fst z==0) $ zip t [1..]
	print $ length t1
	putStrLn $ intercalate " " $ map show t1

-- http://codeforces.com/problemset/problem/545/A

import Data.List

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

main = do
	cars <- getLine

	let
		n = read cars :: Int

	rows_list <- getLines n

	let
		collisions = map read $ concat $ map words $ rows_list :: [Int]
		cars = getCars n
		good_cars = findGoodCars cars collisions

	putStrLn $ show $ length good_cars
	putStrLn $ intercalate " " $ map show good_cars

-- (Car number, Good/Bad - True/False)
type Car = (Int, Bool)
-- Initially all cars are good
getCars :: Int -> [Car]
getCars n = [(x, True) | x <- [1..n]]

findGoodCars :: [Car] -> [Int] -> [Int]
findGoodCars cars collisions =
	foldr
	(\(n, s) acc -> if s then n:acc else acc)
	[] $ findGoodCars' cars collisions 1
	where
		n = length cars
		findGoodCars' :: [Car] -> [Int] -> Int -> [Car]
		findGoodCars' cars [] _ = cars
		findGoodCars' cars (c:cs) index
			| c == 1 = findGoodCars' (markBadCar row cars) cs (index + 1)
			| c == 2 = findGoodCars' (markBadCar col cars) cs (index + 1)
			| c == 3 = findGoodCars' (markBadCar col $ markBadCar row cars) cs (index + 1)
			| otherwise = findGoodCars' cars cs (index+1)
			where
				row = index `quot` n
				col = ((index-1) `mod` n) + 1
				markBadCar :: Int -> [Car] -> [Car]
				markBadCar _ [] = []
				markBadCar i ((n,s):cs)
					| i == n = (n, False):cs
					| otherwise = (n, s):markBadCar (i) cs

import Data.Array.Unboxed
import qualified Data.Set as Set
import Data.List

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

main = do
	cars <- getLine

	let
		n = read cars :: Int

	rows_list <- getLines n

	let
		rows = map read $ concat $ map words $ rows_list :: [Int]
		matrix = listArray ((1, 1), (n, n)) rows :: UArray (Int, Int) Int
		good_cars = findGoodCars matrix n

	putStrLn $ show $ length good_cars
	putStrLn $ intercalate " " $ map show good_cars

findGoodCars :: UArray (Int, Int) Int -> Int -> [Int]
findGoodCars matrix n = [1..n] \\ (Set.elems $ findBadCars matrix 1 Set.empty)
	where
		findBadCars :: UArray (Int, Int) Int -> Int -> Set.Set Int -> Set.Set Int
		findBadCars matrix row set
			| row > n = set
			| n `Set.member` set = findBadCars matrix (row+1) set
			| otherwise = findBadCars matrix (row+1) bad
			where
				bad = inspectCollisions matrix row 1 set
				inspectCollisions :: UArray(Int, Int) Int -> Int -> Int -> Set.Set Int -> Set.Set Int
				inspectCollisions matrix r col set
					| col > n = set
					| collision == 1 = inspectCollisions matrix r (col+1) (Set.insert r set)
					| collision == 2 = inspectCollisions matrix r (col+1) (Set.insert col set)
					| collision == 3 = inspectCollisions matrix r (col+1) (Set.insert r $ Set.insert col set)
					| otherwise = inspectCollisions matrix r (col + 1) set
					where
						collision = matrix!(r,col)

-- http://codeforces.com/problemset/problem/545/A

import Data.List

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

main = do
	cars <- getLine

	let
		n = read cars :: Int

	rows_list <- getLines n

	let
		collisions = map read $ concat $ map words $ rows_list :: [Int]
		cars = getCars n
		good_cars = findGoodCars cars collisions

	putStrLn $ show $ length good_cars
	putStrLn $ intercalate " " $ map show good_cars

-- (Car number, Good/Bad - True/False)
type Car = (Int, Bool)
-- Initially all cars are good
getCars :: Int -> [Car]
getCars n = [(x, True) | x <- [1..n]]

findGoodCars :: [Car] -> [Int] -> [Int]
findGoodCars cars collisions =
	foldr
	(\(n, s) acc -> if s then n:acc else acc)
	[] $ findGoodCars' cars collisions 0
	where
		n = length cars
		findGoodCars' :: [Car] -> [Int] -> Int -> [Car]
		findGoodCars' cars [] _ = cars
		findGoodCars' cars (c:cs) index
			| c == 1 = findGoodCars' (markBadCar row cars) cs (index + 1)
			| c == 2 = findGoodCars' (markBadCar col cars) cs (index + 1)
			| c == 3 = findGoodCars' (markBadCar col $ markBadCar row cars) cs (index + 1)
			| otherwise = findGoodCars' cars cs (index+1)
			where
				row = index `quot` n
				col = (index `mod` n) + 1
markBadCar :: Int -> [Car] -> [Car]
markBadCar _ [] = []
markBadCar i ((n,s):cs)
	| i == n = (n, False):cs
	| otherwise = (n, s):markBadCar (i) cs

module Main where
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8  as C
import Data.List
import Data.Maybe

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

getIntMat :: IO [[Int]]
getIntMat = map ((map (read::String->Int)) . words) . lines <$> getContents

main :: IO ()
main = do
  n <- getInt
  m <- getIntMat
  putStrLn . unwords . map show $ sol m

sol :: [[Int]] -> [Int]
sol = map ((+1) . fst) . filter (\(i,xs) -> all (f i) $ zip [0..] xs) . zip [0..]
  where
  f j (k,x) = j==k || x`mod`2==0


You have a permutation: an array $$$a = [a_1, a_2, \ldots, a_n]$$$ of distinct integers from $$$1$$$ to $$$n$$$. The length of the permutation $$$n$$$ is odd.You need to sort the permutation in increasing order.In one step, you can choose any prefix of the permutation with an odd length and reverse it. Formally, if $$$a = [a_1, a_2, \ldots, a_n]$$$, you can choose any odd integer $$$p$$$ between $$$1$$$ and $$$n$$$, inclusive, and set $$$a$$$ to $$$[a_p, a_{p-1}, \ldots, a_1, a_{p+1}, a_{p+2}, \ldots, a_n]$$$.Find a way to sort $$$a$$$ using no more than $$$\frac{5n}{2}$$$ reversals of the above kind, or determine that such a way doesn't exist. The number of reversals doesn't have to be minimized.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 2021$$$; $$$n$$$ is odd) — the length of the permutation. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — the permutation itself.  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2021$$$.

For each test case, if it's impossible to sort the given permutation in at most $$$\frac{5n}{2}$$$ reversals, print a single integer $$$-1$$$. Otherwise, print an integer $$$m$$$ ($$$0 \le m \le \frac{5n}{2}$$$), denoting the number of reversals in your sequence of steps, followed by $$$m$$$ integers $$$p_i$$$ ($$$1 \le p_i \le n$$$; $$$p_i$$$ is odd), denoting the lengths of the prefixes of $$$a$$$ to be reversed, in chronological order. Note that $$$m$$$ doesn't have to be minimized. If there are multiple answers, print any.

NoteIn the first test case, the permutation is already sorted. Any even number of reversals of the length $$$3$$$ prefix doesn't change that fact.In the second test case, after reversing the prefix of length $$$3$$$ the permutation will change to $$$[5, 4, 3, 2, 1]$$$, and then after reversing the prefix of length $$$5$$$ the permutation will change to $$$[1, 2, 3, 4, 5]$$$.In the third test case, it's impossible to sort the permutation.

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

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

import Data.List

rev :: Int -> State [Int] ()
rev k = do
  ~(sp, ss) <- splitAt k <$> get
  put (reverse sp ++ ss)

solve :: Int -> State [Int] [Int]
solve 1 = pure []
solve n = do
  ~(Just npos) <- elemIndex n <$> get
  rev (npos + 1)
  ~(Just ppos) <- elemIndex (n-1) <$> get
  rev ppos
  rev (ppos + 2)
  rev 3
  rev n
  (\res -> npos + 1 : ppos : ppos + 2 : 3 : n : res) <$> solve (n-2)

main :: IO ()
main = (P.words <$> P.getContents >>=) $ evalStateT $ do
  [t] <- getInts 1
  replicateM_ t $ do
    [n] <- getInts 1
    a <- getInts n
    let
      isOK = all even $ zipWith (-) a [1..]
      ans = filter (> 1) $ evalState (solve n) a
    if  isOK
      then  putInts [length ans] >> putInts ans
      else  putInts [0-1]

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

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

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

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

{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad (replicateM, guard)
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromJust)
import Data.List (elemIndex)

main :: IO ()
main = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines

type InputTy = [Int]
type OutputTy = Maybe [Int]

input :: Scanner InputTy
input = numberOf int

solve :: InputTy -> OutputTy
solve [_] = Just []
solve as = do
  i <- elemIndex n as
  guard $ even i
  as <- rev (i + 1) as
  j <- elemIndex (n - 1) as
  guard $ odd j
  as <- rev j as
  as <- rev (j + 2) as
  as <- rev 3 as
  let as' = reverse (drop 2 as)
  ([i + 1, j, j + 2, 3, n] ++) <$> solve as'
    where
      n = length as
      rev k as = let (ls, rs) = splitAt k as in Just $ reverse ls ++ rs

output :: OutputTy -> C.ByteString
output Nothing = C.pack "-1"
output (Just xs) = C.pack $ show (length xs) ++ "\n" ++ unwords (map show xs)

-------------------------- Template ------------------------------------------
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

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

integer :: Scanner Integer
integer = read . C.unpack <$> bstr

double :: Scanner Double
double = read . C.unpack <$> bstr

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


Implication is a function of two logical arguments, its value is false if and only if the value of the first argument is true and the value of the second argument is false. Implication is written by using character '', and the arguments and the result of the implication are written as '0' (false) and '1' (true). According to the definition of the implication:   When a logical expression contains multiple implications, then when there are no brackets, it will be calculated from left to fight. For example,. When there are brackets, we first calculate the expression in brackets. For example,.For the given logical expression  determine if it is possible to place there brackets so that the value of a logical expression is false. If it is possible, your task is to find such an arrangement of brackets.

The first line contains integer n (1 ≤ n ≤ 100 000) — the number of arguments in a logical expression. The second line contains n numbers a1, a2, ..., an (), which means the values of arguments in the expression in the order they occur.

Print "NO" (without the quotes), if it is impossible to place brackets in the expression so that its value was equal to 0. Otherwise, print "YES" in the first line and the logical expression with the required arrangement of brackets in the second line. The expression should only contain characters '0', '1', '-' (character with ASCII code 45), '>' (character with ASCII code 62), '(' and ')'. Characters '-' and '>' can occur in an expression only paired like that: ("->") and represent implication. The total number of logical arguments (i.e. digits '0' and '1') in the expression must be equal to n. The order in which the digits follow in the expression from left to right must coincide with a1, a2, ..., an. The expression should be correct. More formally, a correct expression is determined as follows:   Expressions "0", "1" (without the quotes) are correct.  If v1, v2 are correct, then v1->v2 is a correct expression.  If v is a correct expression, then (v) is a correct expression.  The total number of characters in the resulting expression mustn't exceed 106. If there are multiple possible answers, you are allowed to print any of them.

main :: IO()
main = solve . (map read . words) =<<getContents

solve :: [Int] -> IO()
solve (_:a) =
    let
        zeroNum = length $ filter (==0) a
        ra = reverse a
        na = reverse $ tail ra
        r1 = head ra
        r2 = head $ tail ra
        invalid = (r1 == 1) || (zeroNum == 2 && r2 == 0)
    in
        if invalid then
            putStrLn "NO"
        else
            if (null na) then
                putStrLn "YES\n0"
            else do putStr "YES\n("
                    firstZero na True
                    putStrLn "->0)"
    where
        firstZero :: [Int] -> Bool -> IO()
        firstZero []     _              = putStr ")"
        firstZero (a:ax) True  | a == 0 = do putStr "(0->("
                                             incLast ax
                                             putStr "))"
                               | a == 1 = do putStr "(1"
                                             firstZero ax False
        firstZero (a:ax) False | a == 0 = do putStr "->(0->("
                                             incLast ax
                                             putStr ")))"
                               | a == 1 = do putStr "->1"
                                             firstZero ax False

        incLast :: [Int] -> IO()
        incLast (a:ax) | null ax   = putStr $ show a
                       | otherwise = do putStr $ show a
                                        putStr "->"
                                        incLast ax

import Control.Applicative ((<$>))
import Control.Monad (mapM_, (>>=))

solve :: String -> [String]
solve a
    | last a /= '0' = ["NO"]
    | a == "0"      = ["YES", "0"]
    | dropWhile (/= '0') a == "00" = ["NO"]
    | take 2 (reverse a) == "01" = ["YES", loop a]
    | head a == '0' = ["YES", "0->(" ++ (loop . init . tail $ a) ++ ")->0"]
    | otherwise = ["YES", loop a' ++ "->(0->(" ++ loop a'' ++ "))->0"]
    where
    a' = takeWhile (/= '0') a
    a'' = init . tail . dropWhile (/= '0') $ a
    loop :: String -> String
    loop "1" = "1"
    loop "0" = "0"
    loop (i:rest) = i:"->" ++ loop rest

main :: IO ()
main = getLine >>= \_ -> solve . filter (/= ' ') <$> getLine >>= mapM_ putStrLn

import Data.Char (isSpace)

insertArrows :: String -> String
insertArrows "" = ""
insertArrows (x : xs) = x : concatMap (("->" ++) . pure) xs

arrowsAfterEach :: String -> String
arrowsAfterEach = concatMap (: "->")

solve :: String -> String
solve inp = case  reverse inp  of
  [] -> error "expected input"
  '1' : _  -> "NO\n"
  '0' : [] -> "YES\n0\n"
  '0' : '1' : _ -> "YES\n" ++ insertArrows inp ++ "\n"
  '0' : '0' : xs
    -> case  span (== '1') xs  of
    (_, []) -> "NO\n"
    (ones, '0' : ys) ->
      "YES\n"
      ++ arrowsAfterEach (reverse ys)
      ++ "(0->("
      ++ arrowsAfterEach ones
      ++ "0))->0\n"
    _ -> error "expected 0 or 1"
  _ -> error "expected 0 or 1"

main :: IO ()
main = interact (solve . filter (not . isSpace) . dropWhile (/= '\n'))

import Data.Char (isSpace)

insertArrows :: String -> String
insertArrows "" = ""
insertArrows (x : xs) = x : concatMap (("->" ++) . pure) xs

arrowsAfterEach :: String -> String
arrowsAfterEach = concatMap (: "->")

solve :: String -> String
solve inp = case  reverse inp  of
  [] -> error "expected input"
  '1' : _  -> "NO\n"
  '0' : [] -> "YES\n0\n"
  '0' : '1' : _ -> "YES\n" ++ insertArrows inp ++ "\n"
  '0' : '0' : xs
    -> case  span (== '1') xs  of
    (_, []) -> "NO\n"
    (ones, '0' : ys) ->
      "YES\n"
      ++ arrowsAfterEach ys
      ++ "(0->("
      ++ arrowsAfterEach ones
      ++ "0))->0\n"
    _ -> error "expected 0 or 1"
  _ -> error "expected 0 or 1"

main :: IO ()
main = interact (solve . filter (not . isSpace) . dropWhile (/= '\n'))


Adilbek was assigned to a special project. For Adilbek it means that he has $$$n$$$ days to run a special program and provide its results. But there is a problem: the program needs to run for $$$d$$$ days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends $$$x$$$ ($$$x$$$ is a non-negative integer) days optimizing the program, he will make the program run in $$$\left\lceil \frac{d}{x + 1} \right\rceil$$$ days ($$$\left\lceil a \right\rceil$$$ is the ceiling function: $$$\left\lceil 2.4 \right\rceil = 3$$$, $$$\left\lceil 2 \right\rceil = 2$$$). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to $$$x + \left\lceil \frac{d}{x + 1} \right\rceil$$$.Will Adilbek be able to provide the generated results in no more than $$$n$$$ days?

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. The next $$$T$$$ lines contain test cases – one per line. Each line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le d \le 10^9$$$) — the number of days before the deadline and the number of days the program runs.

Print $$$T$$$ answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in $$$n$$$ days or NO (case insensitive) otherwise.

NoteIn the first test case, Adilbek decides not to optimize the program at all, since $$$d \le n$$$.In the second test case, Adilbek can spend $$$1$$$ day optimizing the program and it will run $$$\left\lceil \frac{5}{2} \right\rceil = 3$$$ days. In total, he will spend $$$4$$$ days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program $$$2$$$ days, it'll still work $$$\left\lceil \frac{11}{2+1} \right\rceil = 4$$$ days.

{-# LANGUAGE LambdaCase #-}

import Control.Monad

main = do
    n <- read <$> getLine
    replicateM_ n $ do
        map read . words <$> getLine >>= \case
            [n, d] ->
                if minDays d <= n
                then putStrLn "YES"
                else putStrLn "NO"
            _ -> undefined

minDays d = minimum [i + ceiling (fromInteger d / fromInteger (i + 1)) | i <- [(guess-1)..(guess+2)]]
  where
    guess = floor $ sqrt (fromInteger d) - 1

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

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

works n d = let x = floor $ sqrt $ fromIntegral d in any (<= n) $ (\a -> a + d ! (a + 1)) <$> [max (x - 10) 0..x + 10]

main = getLine >>= test.read

test 0 = return ()
test n = do
  (a:b:_) <- map read.words <$> getLine
  output $ works a b
  test $ pred n

output True = putStrLn "YES"
output _ = putStrLn "NO"

f :: Integer -> Integer -> Integer
f d x = x + ceiling( fromIntegral(d) / fromIntegral(x+1) )

solveTask :: (Integer, Integer) -> String
solveTask (n, d)
    | d <= n = "YES\n"
    | otherwise =
      let x = sqrt (fromIntegral  d) - 1
          x0 = floor x
          x1 = ceiling x
      in if f d x0 <= n || f d x1 <=n
        then "YES\n" else "NO\n"

groupTaskInput :: [String] -> [(Integer, Integer)]
groupTaskInput [] = []
groupTaskInput (n:(d:xs)) = (read n, read d) : groupTaskInput(xs)

makeTaskInput :: String -> [(Integer, Integer)]
makeTaskInput s = groupTaskInput $ tail $ words $ s

solve :: String -> String
solve s = concat $ (map solveTask) $ makeTaskInput s

main' :: IO ()
main' = do interact $ solve

main = main'

import Control.Monad
import Data.Int

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

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

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

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

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

f1 :: IO ()
f1 = do
    n <- get :: IO Int32
    d <- get :: IO Int32
    putStrLn (if f2 n d then "YES" else "NO")

f2 :: Int32 -> Int32 -> Bool
f2 n d = let x = bs 0 (fromIntegral d) (fromIntegral d) in
    (x + (div ((fromIntegral d) + x) (x + 1)) <= (fromIntegral n))

bs :: Int64 -> Int64 -> Int64 -> Int64
bs min max d = let aux x = x < (div (d + x) (x + 1)) in
    if min + 1 >= max then
        min
    else
        let mid = div (min + max) 2 in
        if aux mid then
            bs mid max d
        else
            bs min mid d

import System.IO
-- import Prelude

readInt :: IO Int
readInt = readLn

readTuple :: IO (Int, Int)
readTuple = readLn

castToInt x = read x::Int

main = do
    t <- readInt
    mainLoop t

mainLoop t = do
    if t == 0 then
        return ()
    else do
        line <- getLine
        let test_case = (map castToInt . take 2 . words) line

        solveTask test_case

        mainLoop (t - 1)

solveTask test_case = do
    let (n, d) = (head test_case, (head . tail) test_case)
    let x = sqrt (fromIntegral d) - 1

    let lower_x = floor x
    let upper_x = ceiling x

    let xs = [lower_x, upper_x]
    let ys = map (getActualDays d) xs
    let max_days = maximum ys

    if max_days <= n then putStrLn "YES"
        else putStrLn "NO"

getActualDays :: Int -> Int -> Int
getActualDays d x = x + ceiling (fromIntegral d / (fromIntegral x + 1))

{-# LANGUAGE Strict #-}

import Control.Monad
import Data.Ratio

solve n d i
  | i >= n = "NO"
  | total > n = solve n d (i+1)
  | otherwise = "YES"
  where
    total = i + run
    run = ceiling $ d % (i+1)

main = do
  t <- readLn :: IO Int
  replicateM_ t $ do
    [n,d] <- map read . words <$> getLine :: IO [Int]
    putStrLn $ solve n d 0

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

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

works n d = let x = floor $ sqrt $ fromIntegral d in any (<= n) $ (\a -> a + d ! (a + 1)) <$> [max (x - 10) 0..x + 10]

main = getLine >>= test.read

test 0 = return ()
test n = do
  (a:b:_) <- map read.words <$> getLine
  output $ works a b
  test $ pred n

output True = print "YES"
output _ = print "NO"

import Control.Monad
import Data.Int

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

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

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

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

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

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

import Control.Monad
import Data.Int

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

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

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

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

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

f1 :: IO ()
f1 = do
    n <- get :: IO Int32
    d <- get :: IO Int32
    putln (if f2 n d then "YES" else "NO")

f2 :: Int32 -> Int32 -> Bool
f2 n d = let x = bs 0 (fromIntegral d) (fromIntegral d) in
    (x + (div ((fromIntegral d) + x) (x + 1)) <= (fromIntegral n))

bs :: Int64 -> Int64 -> Int64 -> Int64
bs min max d = let aux x = x < (div (d + x) (x + 1)) in
    if min + 1 >= max then
        min
    else
        let mid = div (min + max) 2 in
        if aux mid then
            bs mid max d
        else
            bs min mid d


Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern.

First line of input contains two names (length of each of them doesn't exceed 10), the two initials potential victims. Next line contains integer n (1 ≤ n ≤ 1000), the number of days. Next n lines contains two names (length of each of them doesn't exceed 10), first being the person murdered on this day and the second being the one who replaced that person. The input format is consistent, that is, a person murdered is guaranteed to be from the two potential victims at that time. Also, all the names are guaranteed to be distinct and consists of lowercase English letters.

Output n + 1 lines, the i-th line should contain the two persons from which the killer selects for the i-th murder. The (n + 1)-th line should contain the two persons from which the next victim is selected. In each line, the two names can be printed in any order.

ross rachel
4
ross joey
rachel phoebe
phoebe monica
monica chandler

ross rachel
joey rachel
joey phoebe
joey monica
joey chandler

NoteIn first example, the killer starts with ross and rachel.   After day 1, ross is killed and joey appears.  After day 2, rachel is killed and phoebe appears.  After day 3, phoebe is killed and monica appears.  After day 4, monica is killed and chandler appears.

f (a, b) (c, d) = if a == c then (b, d) else (a, d)

g s = (l !! 0, l !! 1)
    where l = words s

g' t = (fst t) ++ " " ++ (snd t)

main = do
        initialNames <- getLine
        nS <- getLine
        let n = read nS :: Int
        restOfTheNames <- sequence (take n (repeat getLine))
        let result = unlines (map g' (scanl f (g initialNames) (map g restOfTheNames)))
        putStrLn result

f::String->String->[String]->[String]
f _ _ []=[]
f a b (s:str)=let (c:d:[])=words s
              in if c==a then (d++" "++b):(f d b str) else (a++" "++d):(f a d str)

main = do
       e<-getLine
       e2<-getLine
       e3<-getContents
       let (a:b:[])=words e
       mapM_ putStrLn $ (a++" "++b) :f a b (lines e3)

import Control.Applicative( (<$>))
import Data.Bool( bool)
import Control.Monad( replicateM)
main = do
    [vic1_, vic2_] <- words <$> getLine
    n <- readLn::IO Int
    changes_ <- replicateM n (words <$> getLine)
    let
	proc [vic1, vic2]	[]	    = [vic1++" "++vic2]
	proc [vic1, vic2] ([from,to]:rem) = let
			    l = vic1++" "++vic2
			    candi1 = [to,vic2]
			    candi2 = [vic1,to]
			    next = bool candi2 candi1 (vic1==from)
			in
			    l:(proc next rem)
    mapM_ putStrLn $ proc [vic1_, vic2_] changes_


You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move.There are $$$n$$$ doors, the $$$i$$$-th door initially has durability equal to $$$a_i$$$.During your move you can try to break one of the doors. If you choose door $$$i$$$ and its current durability is $$$b_i$$$ then you reduce its durability to $$$max(0, b_i - x)$$$ (the value $$$x$$$ is given).During Slavik's move he tries to repair one of the doors. If he chooses door $$$i$$$ and its current durability is $$$b_i$$$ then he increases its durability to $$$b_i + y$$$ (the value $$$y$$$ is given). Slavik cannot repair doors with current durability equal to $$$0$$$.The game lasts $$$10^{100}$$$ turns. If some player cannot make his move then he has to skip it.Your goal is to maximize the number of doors with durability equal to $$$0$$$ at the end of the game. You can assume that Slavik wants to minimize the number of such doors. What is the number of such doors in the end if you both play optimally?

The first line of the input contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 100$$$, $$$1 \le x, y \le 10^5$$$) — the number of doors, value $$$x$$$ and value $$$y$$$, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th door.

Print one integer — the number of doors with durability equal to $$$0$$$ at the end of the game, if you and Slavik both play optimally.

NoteClarifications about the optimal strategy will be ignored.

-- Codeforces Round #531 (C), Contest 1102, Problem set ?.

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.Function

main :: IO ()
main = do
  [n,x,y] <- map read . words <$> getLine :: IO [Int]
  as <- unfoldr (BS.readInt . BS.dropWhile(<'!')) <$> BS.getLine :: IO [Int]
  let breakableInOne = length $ filter (<= x) as
  print $ if x > y then n else (breakableInOne+1) `shiftR` 1

import Data.Function -- on
import Data.Functor -- <$>
import Data.List hiding (sortOn)

toList :: (Read a) => String -> [a]
toList = map read <$> words

main = do
    [n, x, y] <- toList <$> getLine :: IO [Int]
    as <- toList <$> getLine :: IO [Int]
    let ans = if x > y then n
              else (succ $ length $ filter (<= x) as) `div` 2
    print ans

import Control.Monad
readInts = liftM (map read . words) getLine
solve [[n, x, y], s] = if x > y then n else (1 + length (filter (<=x) s)) `div` 2
main = replicateM 2 readInts >>= putStrLn . show . solve

import Control.Monad
readInts = liftM (map read . words) getLine
solve [[n, x, y], s] = if x > y then n else (1 + length (filter (<x) s)) `div` 2
main = replicateM 2 readInts >>= putStrLn . show . solve

import Control.Monad
readInts = liftM (map read . words) getLine
solve [n, x, y] s = if x > y then n else length $ takeWhile (< x) s
main = readInts >>= \s -> readInts >>= putStrLn . show . solve s


In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly 0.273549107 beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this: If a number's integer part does not end with digit 9 and its fractional part is strictly less than 0.5, then the rounded up number coincides with the number’s integer part.  If a number's integer part does not end with digit 9 and its fractional part is not less than 0.5, the rounded up number is obtained if we add 1 to the last digit of the number’s integer part. If the number’s integer part ends with digit 9, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position. Merchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the King’s order?

The first line contains a single number to round up — the integer part (a non-empty set of decimal digits that do not start with 0 — with the exception of a case when the set consists of a single digit — in this case 0 can go first), then follows character «.» (a dot), and then follows the fractional part (any non-empty set of decimal digits). The number's length does not exceed 1000 characters, including the dot. There are no other characters in the input data.

If the last number of the integer part is not equal to 9, print the rounded-up number without leading zeroes. Otherwise, print the message "GOTO Vasilisa." (without the quotes).

module Main where

import Data.List

main = do
    inputLine <- getLine
    let (prefix, postfix) = span (/='.') inputLine

    let result = if last prefix == '9'
            then "GOTO Vasilisa."
            else if postfix !! 1 >= '5'
                then show ( 1 + read prefix :: Integer )
                else prefix

    putStrLn result

import Data.Maybe
import Data.List
import Data.Bifunctor

main = do
    x <- getLine
    let (y,z) = splitAt (fromJust $ findIndex (=='.') x) x
    let int = read :: String -> Integer
    putStrLn $ case bimap int int (y, [head  $ tail z]) of
        (a,_) | a`mod`10 == 9 -> "GOTO Vasilisa."
        (a,b) | b < 5         -> show a
        (a,b)                 -> show $ succ a

import Char

bigTest = take 1000 (repeat '0') ++ ".9"

myRound :: String -> String
myRound line = myRound' "" line
  where
    myRound' prefix (a:'.':b:_)
      |  a == '9'  =  "GOTO Vasilisa."
      |  b <  '5'  =  prefix ++ [a]
      |  otherwise =  prefix ++ [intToDigit (digitToInt a + 1)]
    myRound' prefix (a:as) = myRound' (prefix ++ [a]) as
    myRound' _ _ = error "Not found '.'"

main = do
  line <- getLine
  putStrLn $ myRound line

import Data.List (delete)
import Data.Char (ord, chr)

remove (x:xs) = xs

solve s = roundNumber $ span (/='.') s
       where roundNumber (x,y) | last x == '9' = "GOTO Vasilisa."
                               | (head $ remove y) >= '5' = init x ++ [chr . (+1) . ord $ last x]
                               | otherwise = x

main = do number <- getLine
          putStrLn $ solve number

main = do
  n <- getLine
  putStrLn (round' n)
round' n | last i == '9' = "GOTO Vasilisa."
         | f!!1 < '5'    = i
         | otherwise     = show (read i + 1)
    where (i,f) = break (== '.') n

s(a,b)|last a=='9'="GOTO Vasilisa."|b!!1>'4'=init a++[succ$last a]|1>0=a
main=interact$s.span(/='.')

main = interact $ rounded

rounded :: String -> String
rounded s =
    let (intPart,fracPart) = span (/= '.') s
        (leadDigits, lastDigit) = (init intPart, last intPart)
        roundUp = (fracPart !! 1) `elem` ['5'..'9']
    in  if lastDigit == '9'
            then "GOTO Vasilisa."
            else if roundUp then leadDigits ++ [succ lastDigit] else intPart

main = do d <- getLine
          let (d_int,(_:d_frac)) = span (/='.') d
          putStrLn $ if last d_int == '9' then
                         "GOTO Vasilisa."
                     else if (read [head d_frac]::Int) < 5 then
                              d_int
                          else
                              show ((read d_int::Integer)+1)

import Data.Maybe
import Data.List

f str | str !! (inx - 1) == '9' = "GOTO Vasilisa."
      | str !! (inx + 1) >= '5' = (take (inx - 1) str) ++  (show . (+) 1 . read $ [str !! (inx - 1)])
      | otherwise = take inx str
 where inx = fromJust . elemIndex '.'$ str

main = do
   str <- getLine
   putStrLn . f $ str

import Data.Maybe
import Data.List
import Data.Bifunctor

main = do
    x <- getLine
    let (y,z) = splitAt (fromJust $ findIndex (=='.') x) x
    let int = read :: String -> Integer
    putStrLn $ case bimap int int (y, [head  $ tail z]) of
        (a,_) | a`mod`10 == 9 -> "GOTO Vasilasa."
        (a,b) | b < 5         -> show a
        (a,b)                 -> show $ succ a

import Data.Maybe
import Data.List
import Data.Bifunctor

main = do
    x <- getLine
    let (y,z) = splitAt (fromJust $ findIndex (=='.') x) x
    let int = read :: String -> Integer
    putStrLn $ case bimap int int (y, [head  $ tail z]) of
        (a,_) | a`mod`10 == 9 -> "GOTO Vasilasa"
        (a,b) | b < 5         -> show a
        (a,b)                 -> show $ succ a

main = (readLn :: IO Double) >>= \x ->  putStrLn $
    let (y,z) = (truncate x,x-fromIntegral y) in
    case (y,z) of
        (a,b) | a`mod`10 == 9 -> "GOTO Vasilasa"
        (a,b) | b < 0.5       -> show a
        _                     -> show $ succ y

main = interact $ rounded

rounded :: String -> String
rounded s =
    let (intPart,fracPart) = span (/= '.') s
        (leadDigits, lastDigit) = (init intPart, last intPart)
        roundUp = (fracPart !! 1) `elem` ['5'..'9']
    in  if roundUp
            then if lastDigit == '9'
                then "GOTO Vasilisa."
                else leadDigits ++ [succ lastDigit]
            else
                intPart

main = do d <- getLine
          let (d_int,(_:d_frac)) = span (/='.') d
          putStrLn $ if last d_int == '9' then
                         "GOTO Vasilisa."
                     else if (read [head d_frac]::Int) < 5 then
                              d_int
                          else
                              show ((read d_int::Int)+1)

s(a,b)|last a=='9'="GOTO Vasilisa."|b!!2>'4'=init a++[succ$last a]|1>0=a
main=interact$s.span(/='.')

import Data.Maybe
import Data.List

f str | str !! (inx - 1) == '9' = "GOTO Vasilisa"
      | str !! (inx + 1) >= '5' = (take (inx - 1) str) ++  (show . (+) 1 . read $ [str !! (inx - 1)])
      | otherwise = take inx str
 where inx = fromJust . elemIndex '.'$ str

main = do
   str <- getLine
   putStrLn . f $ str


Did you know you can download more RAM? There is a shop with $$$n$$$ different pieces of software that increase your RAM. The $$$i$$$-th RAM increasing software takes $$$a_i$$$ GB of memory to run (temporarily, once the program is done running, you get the RAM back), and gives you an additional $$$b_i$$$ GB of RAM (permanently). Each software can only be used once. Your PC currently has $$$k$$$ GB of RAM.Note that you can't use a RAM-increasing software if it takes more GB of RAM to use than what you currently have.Since RAM is the most important thing in the world, you wonder, what is the maximum possible amount of RAM achievable?

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains the integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 1000$$$). Then two lines follow, each containing $$$n$$$ integers describing the arrays $$$a$$$ and $$$b$$$ ($$$1 \le a_i, b_i \le 1000$$$).

For each test case, output a single line containing the largest amount of RAM you can achieve.

NoteIn the first test case, you only have enough RAM to run the third software initially, but that increases your RAM to $$$20$$$ GB, which allows you to use the first software, increasing your RAM to $$$29$$$ GB. The only software left needs $$$30$$$ GB of RAM, so you have to stop here.In the second test case, you can use the first, second, fourth and fifth software that need only $$$1$$$ GB of RAM per software to run to increase your RAM to $$$5$$$ GB, and then use the last remaining one to increase your RAM to $$$6$$$ GB.In the third test case, all the software need more than $$$1$$$ GB of RAM to run, so the amount of RAM you have stays at $$$1$$$ GB.

import Control.Monad (forM)
import Data.List

array a = map (read::String -> Int) $ words a

compute::[(Int, Int)] -> Int -> Int
compute aa k = foldl (\x i -> if fst i <= x then x + snd i else x) k aa

solve t = do
  input <- getLine
  a <- getLine
  b <- getLine
  let aa = sort $ zip (array a) (array b)
      [n, k] = array input
      ans = compute aa k
  print ans

main = do
tlen <- readLn :: IO Int
forM [0..(tlen - 1)] (\t -> do solve t)


Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.

The first line contains single integer n (1 ≤ n ≤ 2·105) — the number of cubes. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109), where ai is the number written on the i-th cube after Dima has changed their order.

Print n integers, separated by spaces — the numbers written on the cubes in their initial order. It can be shown that the answer is unique.

NoteConsider the first sample.  At the begining row was [2, 3, 9, 6, 7, 1, 4].  After first operation row was [4, 1, 7, 6, 9, 3, 2].  After second operation row was [4, 3, 9, 6, 7, 1, 2].  After third operation row was [4, 3, 7, 6, 9, 1, 2].  At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4].

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE OverloadedStrings #-}
-- {-# LANGUAGE BangPatterns #-}
-- {-# LANGUAGE ViewPatterns #-}
-- {-# LANGUAGE TupleSections #-}

import           System.IO hiding (char8)
import           Control.Applicative
import           Control.Monad
import           Data.List
import           Data.Tuple
import           Data.Int
import           Data.Char
import           Data.Function (on)
import           Data.Array
-- import           Data.Array.Unboxed
-- import           Data.Array.IArray
-- import           Data.Array.ST
-- import           Data.Array.MArray
-- import           Data.Array.Unsafe
import           Data.Ix
import           Data.Maybe
import           Data.Monoid hiding ((<>))
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BL
import           Data.ByteString.Builder
-- import           Data.Vector.Unboxed ((//), (++), (!), (!?))
-- import qualified Data.Vector.Unboxed as U
-- import           Data.IntSet (IntSet)
-- import qualified Data.IntSet as S
-- import           Data.IntMap.Strict (IntMap)
-- import qualified Data.IntMap.Strict as M
-- import           Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))
-- import qualified Data.Sequence as S
-- import           Debug.Trace

main = do
  n <- readInt1 <$> BS.getLine
  ns <- readIntN <$> BS.getLine
  putStrLn . intercalate " " . map show $ solve n ns

solve :: Int -> [Int] -> [Int]
solve n ns = zipWith3 f ns (reverse ns) [0..] where
  f a b i = if min (i + 1) (n - i) `mod` 2 == 0 then a else b

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

readInt1 :: BS.ByteString -> Int
readInt1 = fst . fromJust . BS.readInt

readInt2 :: BS.ByteString -> (Int,Int)
readInt2 = toTuple . readIntN

readInt3 :: BS.ByteString -> (Int,Int,Int)
readInt3 = toTriple . readIntN

readIntN :: BS.ByteString -> [Int]
readIntN =  map readInt1 . BS.words

readInt641 :: BS.ByteString -> Int64
readInt641 = fromIntegral . fst . fromJust . BS.readInteger

readInt642 :: BS.ByteString -> (Int64,Int64)
readInt642 = toTuple . readInt64N

readInt643 :: BS.ByteString -> (Int64,Int64,Int64)
readInt643 = toTriple . readInt64N

readInt64N :: BS.ByteString -> [Int64]
readInt64N =  map readInt641 . BS.words

readInteger1 :: BS.ByteString -> Integer
readInteger1 = fst . fromJust . BS.readInteger

readInteger2 :: BS.ByteString -> (Integer,Integer)
readInteger2 = toTuple . readIntegerN

readInteger3 :: BS.ByteString -> (Integer,Integer,Integer)
readInteger3 = toTriple . readIntegerN

readIntegerN :: BS.ByteString -> [Integer]
readIntegerN =  map readInteger1 . BS.words

toTuple :: [a] -> (a, a)
toTuple [x, y] = (x, y)

toTriple :: [a] -> (a, a, a)
toTriple [x, y, z] =(x, y, z)

fromTuple :: (a, a) -> [a]
fromTuple (x, y) = [x, y]

fromTriple :: (a, a, a) -> [a]
fromTriple (x, y, z) = [x, y, z]

-- if not applying, use "const"

applyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')
applyTuple f g (x, y) = (f x, g y)

applyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')
applyTriple f g h (x, y, z) = (f x, g y, h z)


Let's call an array $$$a$$$ consisting of $$$n$$$ positive (greater than $$$0$$$) integers beautiful if the following condition is held for every $$$i$$$ from $$$1$$$ to $$$n$$$: either $$$a_i = 1$$$, or at least one of the numbers $$$a_i - 1$$$ and $$$a_i - 2$$$ exists in the array as well.For example:   the array $$$[5, 3, 1]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 2 = 3$$$ exists in the array; for $$$a_2$$$, the number $$$a_2 - 2 = 1$$$ exists in the array; for $$$a_3$$$, the condition $$$a_3 = 1$$$ holds;  the array $$$[1, 2, 2, 2, 2]$$$ is beautiful: for $$$a_1$$$, the condition $$$a_1 = 1$$$ holds; for every other number $$$a_i$$$, the number $$$a_i - 1 = 1$$$ exists in the array;  the array $$$[1, 4]$$$ is not beautiful: for $$$a_2$$$, neither $$$a_2 - 2 = 2$$$ nor $$$a_2 - 1 = 3$$$ exists in the array, and $$$a_2 \ne 1$$$;  the array $$$[2]$$$ is not beautiful: for $$$a_1$$$, neither $$$a_1 - 1 = 1$$$ nor $$$a_1 - 2 = 0$$$ exists in the array, and $$$a_1 \ne 1$$$;  the array $$$[2, 1, 3]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 1 = 1$$$ exists in the array; for $$$a_2$$$, the condition $$$a_2 = 1$$$ holds; for $$$a_3$$$, the number $$$a_3 - 2 = 1$$$ exists in the array. You are given a positive integer $$$s$$$. Find the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Then $$$t$$$ lines follow, the $$$i$$$-th line contains one integer $$$s$$$ ($$$1 \le s \le 5000$$$) for the $$$i$$$-th test case.

Print $$$t$$$ integers, the $$$i$$$-th integer should be the answer for the $$$i$$$-th testcase: the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.

NoteConsider the example test:  in the first test case, the array $$$[1]$$$ meets all conditions;  in the second test case, the array $$$[3, 4, 1]$$$ meets all conditions;  in the third test case, the array $$$[1, 2, 4]$$$ meets all conditions;  in the fourth test case, the array $$$[1, 4, 6, 8, 10, 2, 11]$$$ meets all conditions.

main = interact $ unlines . map (show . ceiling . sqrt . read) . tail . lines

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P
import Data.List as L
import Data.Int (Int64)
import Data.Bits as B
import System.IO as Io
--import Data.Char as C
--import Data.IntSet as S

solve :: IO ()
solve = do
  n <- readLn :: IO Int
  let q = takeWhile (<n) $ scanl (+) 1 [3, 5..]
    in print $ length q + 1

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

import Control.Monad

solve n = div ((n + 1) * (div n 2 + 1)) 2

printResult = do
    n <- readLn :: IO Int
    let xs = takeWhile (\x->solve x < n) [1,3..]
        r = if null xs then 1 else div (last xs) 2 + 2
    print r

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

import Control.Monad ( replicateM_ )

solve :: IO ()
solve = do
    s <- readLn :: IO Int
    let go x y = if y >= s then 0 else 1 + go (x + 2) (y + x + 2)
    print $ go (-1) 0

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

{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromJust, fromMaybe)

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

solve :: Int -> Int
solve s = (1 +) . length . takeWhile (< s) $ scanl1 (+) [1, 3 ..]

--- Template ---
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

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

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

integer :: Scanner Integer
integer = read . C.unpack <$> str

double :: Scanner Double
double = read . C.unpack <$> str

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 (,)


Polycarpus adores TV series. Right now he is ready to finish watching a season of a popular sitcom "Graph Theory". In total, the season has n episodes, numbered with integers from 1 to n.Polycarpus watches episodes not one by one but in a random order. He has already watched all the episodes except for one. Which episode has Polycaprus forgotten to watch?

The first line of the input contains integer n (2 ≤ n ≤ 100000) — the number of episodes in a season. Assume that the episodes are numbered by integers from 1 to n. The second line contains n - 1 integer a1, a2, ..., an (1 ≤ ai ≤ n) — the numbers of episodes that Polycarpus has watched. All values of ai are distinct.

Print the number of the episode that Polycarpus hasn't watched.

import Data.List
import Data.Function

main = interact $ show . getAns . map read . words

getAns :: [Int] -> Int
getAns (n:xs) = sum [1..n] - sum xs

import Data.List
import Data.Int
import Data.Function

main = interact $ show . getAns . map read . words

getAns :: [Int64] -> Int64
getAns (n:xs) = n * (n + 1) `div` 2 - sum xs

import qualified Data.ByteString.Char8 as BS
import Data.ByteString (ByteString)
import Data.Char
import Data.Int

readInt :: IO Int
readInt = do line <- BS.getLine
             let Just (n,_) = BS.readInt line
             return n

parseInts :: Int -> ByteString -> [Int]
parseInts k bs | k <= 0 = []
parseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of
                   Nothing -> []
                   Just (n,bs') -> n : parseInts (k-1) bs'

main = do
  n <- fmap read getLine
  s <- fmap (sum . map fromIntegral . parseInts n) BS.getLine :: IO Int64
  let n' = fromIntegral n
      answer = div (n'*(n'+1)) 2 - s
  print answer

{-# LANGUAGE NoMonomorphismRestriction #-}
import Control.Applicative ((<$>))
import Control.Monad
import Text.Printf (printf)
import Data.Maybe (Maybe, fromMaybe)
import Data.List (sort, foldl')
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as BS

solve :: [Int] -> Int
solve s = fst . head . dropWhile (\(x, y) -> x == y) . zip [1..] $ sort s

main :: IO ()
main = do
  n <- getInt
  a <- getInts
  print . solve $ a ++ [n+1]

toNumber = fst . fromMaybe (0, BS.pack "")
getInt = toNumber . BS.readInt <$> BS.getLine
getInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))
countup = foldl' (\x y -> M.insertWith' (+) y 1 x) M.empty
countof m x = M.findWithDefault 0 x m

import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Data.List

solve i [] = i
solve i (a:as) = if i /= a then i else solve (i+1) as

main = print =<<  solve 1 . sort <$> (map (fst . fromJust . B.readInt) . B.words <$> (getLine >> B.getLine))

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
-- hiding clauses are to allow Data.Foldable's generalizations
import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)
import Control.Monad.ST

import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (ByteString)
import Data.Bits
import Data.Char
import Data.Either
import Data.Foldable
import Data.Function
import Data.IORef
import Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Traversable
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
import System.IO
-- }}}
-- silly utilities {{{
-- stolen from lens:
a & f = f a
a <&> f = fmap f a
infixl 1 &, <&>

fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)
-- }}}
-- input and output {{{
bsGetLine :: IO ByteString
bsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine

inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]

ssUnwords :: [ShowS] -> ShowS
ssUnwords [] = id
ssUnwords (x:xs) = x . (' ':) . ssUnwords xs

ssUnlines :: [ShowS] -> ShowS
ssUnlines [] = id
ssUnlines (x:xs) = x . ('\n':) . ssUnlines xs

showMany :: (Show a) => [a] -> String
showMany xs = ssUnwords (map shows xs) ""
showMatrix :: (Show a) => [[a]] -> String
showMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) ""

printMany :: (Show a) => [a] -> IO ()
printMany xs = putStrLn (showMany xs)
printMatrix :: (Show a) => [[a]] -> IO ()
printMatrix xs = putStr (showMatrix xs)
-- }}}

main :: IO ()
main = do
	n <- inputInteger
	xs <- inputIntegers
	print $ n * (n + 1) `div` 2 - foldl' (+) 0 xs

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

main = do
		n<- read <$> getLine ::IO Int
		k<-sort <$> map read <$> words <$> getLine ::IO [Int]
		let m= take 1 $  dropWhile (\(a,b)-> a==b) $ zip k [1..]
		print $ if m==[] then n else (snd (head m))

main = do
    let i = fmap (map read . words) getLine :: IO [Integer]
    n <- fmap (!! 0) i
    a <- i
    print $ n * (n + 1) `div` 2 - sum a

import Data.List
import Data.Function

main = interact $ show . getAns . map read . words

getAns :: [Int] -> Int
getAns (n:xs) = n * (n + 1) `div` 2 - sum xs

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
-- hiding clauses are to allow Data.Foldable's generalizations
import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)
import Control.Monad.ST

import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (ByteString)
import Data.Bits
import Data.Char
import Data.Either
import Data.Foldable
import Data.Function
import Data.IORef
import Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Traversable
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
import System.IO
-- }}}
-- silly utilities {{{
-- stolen from lens:
a & f = f a
a <&> f = fmap f a
infixl 1 &, <&>

fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)
-- }}}
-- input and output {{{
bsGetLine :: IO ByteString
bsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine

inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]

ssUnwords :: [ShowS] -> ShowS
ssUnwords [] = id
ssUnwords (x:xs) = x . (' ':) . ssUnwords xs

ssUnlines :: [ShowS] -> ShowS
ssUnlines [] = id
ssUnlines (x:xs) = x . ('\n':) . ssUnlines xs

showMany :: (Show a) => [a] -> String
showMany xs = ssUnwords (map shows xs) ""
showMatrix :: (Show a) => [[a]] -> String
showMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) ""

printMany :: (Show a) => [a] -> IO ()
printMany xs = putStrLn (showMany xs)
printMatrix :: (Show a) => [[a]] -> IO ()
printMatrix xs = putStr (showMatrix xs)
-- }}}

main :: IO ()
main = do
	n <- inputInt
	xs <- inputInts
	print $ n * (n + 1) `div` 2 - foldl' (+) 0 xs

main = do
    let i = fmap (map read . words) getLine :: IO [Int]
    n <- fmap (!! 0) i
    a <- i
    print $ n * (n + 1) `div` 2 - sum a