Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all.In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit n + 1. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the n + 1 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away.For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3.

The first line of the input contains two integers n and t (1 ≤ n ≤ 200 000, 1 ≤ t ≤ 109) — the length of Efim's grade and the number of seconds till the end of the break respectively. The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0.

Print the maximum grade that Efim can get in t seconds. Do not print trailing zeroes.

NoteIn the first two samples Efim initially has grade 10.245. During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect.In the third sample the optimal strategy is to not perform any rounding at all.

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}

import           Control.Applicative
import qualified Data.ByteString.Char8 as B
import           Data.Char

main :: IO ()
main = do
    [_, t] <- map read.words <$> getLine :: IO [Int]
    (xs, ys) <- B.span (/= '.') . B.filter (not.isSpace) <$> B.getLine
    putStr $ solve t xs . tail $ B.unpack ys

solve :: Int -> B.ByteString -> String -> String
solve _ xs (y:ys) | '4' < y = plusOne xs
solve t xs ('4':ys)
    | null rs || head rs < '4' || t <= lf = B.unpack xs ++ '.':solve' t 1 'x' ys
    | otherwise = plusOne xs
  where
    (fs, rs) = span ('4'==) ys
    lf = length fs + 1
    flg = case takeWhile ('4'<=) ys of
        [] -> False
        zs -> any ('4'<) zs
solve t xs (y:ys) = B.unpack xs ++ '.':solve' t 0 y ys

solve' = go
  where
    go 0 0 z zs = z:zs
    go 0 f p zs = [p | p/='x'] ++ replicate f '4' ++ zs
    go !t 0 p (z:zs)
      | '4' < z = [succ p]
      | z == '4' = go t 1 p zs
      | otherwise = p : go t 0 z zs
    go !t !f p (z:zs)
      | '4' < z, t >= f + 1 , p /= 'x' = [succ p]
      | '4' < z = [p | p/='x'] ++ replicate (max 0 $ f-t) '4' ++ "5"
      | z == '4' = go t (f + 1) p zs
      | otherwise = [p | p/='x'] ++ replicate f '4' ++ go t 0 z zs
    go _ f p "" | f > 0 = p : replicate f '4'
    go _ _ p "" = [p]
    go _ _ _ "" = ""

plusOne :: B.ByteString -> String
plusOne bs
  | Just (x, _) <- B.readInteger bs = show $ x + 1
  | otherwise = error "readInteger"

import Data.List
import Control.Monad (liftM)

solve :: Int -> String -> String
solve n q = case findIndex (>= '5') s of
    Nothing -> q
    Just ix -> unparse p . reverse . carry n . reverse $ take (succ ix) s
    where (p, v) = break (=='.') q
          s = tail v

carry :: Int -> String -> String
carry 0  s  = s
carry _ [x] = [x | x < '5']
carry n ('9' : s) = case dropWhile (=='9') s of
    (x:xs) -> carry (pred n) (succ x : xs)
    []     -> []
carry n s@(x:y:r) = if x >= '5' then carry (pred n) (succ y : r) else s

unparse :: String -> String -> String
unparse p s = case s of
    [] -> increment p
    xs -> p ++ "." ++ s

increment :: String -> String
increment s = case fx of
    []     -> '1' : zeros
    (x:xs) -> reverse xs ++ [succ x] ++ zeros
    where (px, fx) = span (== '9') $ reverse s
          zeros = replicate (length px) '0'

main = liftM words getLine >>= \[_, n] -> getLine >>= putStrLn . solve (read n)

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}

import           Control.Applicative

main :: IO ()
main = do
    [_, t] <- map read.words <$> getLine :: IO [Int]
    (xs, _:ys) <- span (/= '.') <$> getLine
    putStr $ solve t xs ys

solve :: Int -> String -> String -> String
solve _ xs (y:ys) | '4' < y = show $ (read xs :: Integer) + 1
solve t xs ('4':ys)
    | null rs || head rs < '4' || t <= lf = xs ++ "." ++ solve' t 1 'x' ys
    | otherwise = show $ (read xs :: Integer) + 1
  where
    (fs, rs) = span ('4'==) ys
    lf = length fs + 1
    flg = case takeWhile ('4'<=) ys of
        [] -> False
        zs -> any ('4'<) zs
solve t xs (y:ys) = xs ++ "." ++ solve' t 0 y ys

solve' t f x xs = go t f x xs
  where
    go 0 0 z zs = z:zs
    go 0 f 'x' zs = replicate f '4' ++ zs
    go 0 f p zs = p:replicate f '4' ++ zs
    go !t 0 p (z:zs)
      | '4' < z = [succ p]
      | z == '4' = go t 1 p zs
      | otherwise = go t 0 z zs
    go !t !f p (z:zs)
      | '4' < z, t >= f + 1 , p /= 'x' = [succ p]
      | '4' < z = [p | p/='x'] ++ replicate (max 0 $ f-t) '4' ++ "5"
      | z == '4' = go t (f + 1) p zs
      | otherwise = replicate f '4' ++ go t 0 z zs
    go _ f p "" | f > 0 = p:replicate f '4'
    go _ _ p "" = [p]
    go _ _ _ zs = zs

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}

import           Control.Applicative

main :: IO ()
main = do
    [_, t] <- map read.words <$> getLine :: IO [Int]
    (xs, _:ys) <- span (/= '.') <$> getLine
    putStr $ solve t xs ys

solve :: Int -> String -> String -> String
solve _ xs (y:ys) | '4' < y = show $ (read xs :: Integer) + 1
solve t xs ('4':ys)
    | null rs || head rs < '4' || t <= lf = xs ++ "." ++ solve' t 1 'x' ys
    | otherwise = show $ (read xs :: Integer) + 1
  where
    (fs, rs) = span ('4'==) ys
    lf = length fs + 1
    flg = case takeWhile ('4'<=) ys of
        [] -> False
        zs -> any ('4'<) zs
solve t xs (y:ys) = xs ++ "." ++ solve' t 0 y ys

solve' t f x xs = go t f x xs
  where
    go 0 0 z zs = z:zs
    go 0 f 'x' zs = replicate f '4' ++ zs
    go 0 f p zs = p:replicate f '4' ++ zs
    go !t 0 p (z:zs)
      | '4' < z = [succ p]
      | z == '4' = go t 1 p zs
      | otherwise = p:go t 0 z zs
    go !t !f p (z:zs)
      | '4' < z, t >= f + 1 , p /= 'x' = [succ p]
      | '4' < z = [p | p/='x'] ++ replicate (max 0 $ f-t) '4' ++ "5"
      | z == '4' = go t (f + 1) p zs
      | otherwise = replicate f '4' ++ go t 0 z zs
    go _ f p "" | f > 0 = p:replicate f '4'
    go _ _ p "" = [p]
    go _ _ _ zs = zs

import Data.List
import Control.Monad (liftM)

solve :: Int -> String -> String
solve n q = case findIndex (>= '5') (tail s) of
    Nothing -> unparse t s
    Just ix -> let s' = reverse . carry n . reverse $ take (ix + 2) s
                in unparse (t + fromEnum (head s' == '1' && head s == '9')) s'
    where s = delete '.' q
          Just t = elemIndex '.' q

carry :: Int -> String -> String
carry 0  s  =  s
carry _ [ ] = [ ]
carry _ [x] = [x]
carry n ('9' : s) = case dropWhile (=='9') s of
    []     -> ['1']
    (x:xs) -> carry (pred n) (succ x : xs)
carry n s@(x:y:r) = if x >= '5' then carry (pred n) (succ y : r) else s

unparse :: Int -> String -> String
unparse n s = if d >= 0
                then s ++ replicate d '0'
                else let (u, v) = splitAt n s in u ++ ['.'] ++ v
    where d = n - length s

main = liftM words getLine >>= \[_, n] -> getLine >>= putStrLn . solve (read n)

import Data.List
import Control.Monad (liftM)

solve :: Int -> String -> String
solve n q = case findIndex (>= '5') s of
    Nothing -> q
    Just ix -> unparse p . reverse . carry n . reverse $ take (succ ix) s
    where (p, v) = break (=='.') q
          s = tail v

carry :: Int -> String -> String
carry 0  s  = s
carry _ [x] = [x | x < '5']
carry n ('9' : s) = case dropWhile (=='9') s of
    (x:xs) -> carry (pred n) (succ x : xs)
    []     -> []
carry n s@(x:y:r) = if x >= '5' then carry (pred n) (succ y : r) else s

unparse :: String -> String -> String
unparse p s = case s of
    [] -> increment p
    xs -> p ++ "." ++ s

increment :: String -> String
increment s = case fx of
    []     -> '1' : zeros
    (x:xs) -> xs ++ [succ x] ++ zeros
    where (px, fx) = span (== '9') $ reverse s
          zeros = replicate (length px) '0'

main = liftM words getLine >>= \[_, n] -> getLine >>= putStrLn . solve (read n)


One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one.The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (1 ≤ i ≤ n), someone can use the first portal to move from it to room number (i + 1), also someone can use the second portal to move from it to room number pi, where 1 ≤ pi ≤ i.In order not to get lost, Vasya decided to act as follows.   Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room 1.  Let's assume that Vasya is in room i and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room pi), otherwise Vasya uses the first portal. Help Vasya determine the number of times he needs to use portals to get to room (n + 1) in the end.

The first line contains integer n (1 ≤ n ≤ 103) — the number of rooms. The second line contains n integers pi (1 ≤ pi ≤ i). Each pi denotes the number of the room, that someone can reach, if he will use the second portal in the i-th room.

Print a single number — the number of portal moves the boy needs to go out of the maze. As the number can be rather large, print it modulo 1000000007 (109 + 7).

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import qualified Data.ByteString.Char8 as B

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

rep :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
{-# INLINE rep #-}

main = do
  n <- readLn :: IO Int
  xs <- map readInt.B.words <$> B.getLine
  print $ solve n $ listArray (0,n-1) $ map (subtract 1) xs

modulo :: Int
modulo = 1000000007

solve :: Int -> UArray Int Int -> Int
solve n arr = runST $ do
  dp <- newArray (0,n) 0 :: ST s (STUArray s Int Int)

  rep n $ \i -> do
    dpi  <- unsafeRead dp i
    dppi <- unsafeRead dp $ unsafeAt arr i
    unsafeWrite dp (i+1) $ (dpi + (dpi - dppi + 1) + 1) `mod` modulo

  unsafeRead dp n


There was an electronic store heist last night.All keyboards which were in the store yesterday were numbered in ascending order from some integer number $$$x$$$. For example, if $$$x = 4$$$ and there were $$$3$$$ keyboards in the store, then the devices had indices $$$4$$$, $$$5$$$ and $$$6$$$, and if $$$x = 10$$$ and there were $$$7$$$ of them then the keyboards had indices $$$10$$$, $$$11$$$, $$$12$$$, $$$13$$$, $$$14$$$, $$$15$$$ and $$$16$$$.After the heist, only $$$n$$$ keyboards remain, and they have indices $$$a_1, a_2, \dots, a_n$$$. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

The first line contains single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of  keyboards in the store that remained after the heist. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{9})$$$ — the indices of the remaining keyboards. The integers $$$a_i$$$ are given in arbitrary order and are pairwise distinct.

Print the minimum possible number of keyboards that have been stolen if the staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

NoteIn the first example, if $$$x=8$$$ then minimum number of stolen keyboards is equal to $$$2$$$. The keyboards with indices $$$9$$$ and $$$11$$$ were stolen during the heist.In the second example, if $$$x=4$$$ then nothing was stolen during the heist.

maxMinFold :: Ord a => [a] -> (a, a)
maxMinFold (x:xs) =
  foldr (\x (tailMin, tailMax) -> (min x tailMin, max x tailMax)) (x,x) xs

main = do
       input1 <- getLine
       input2 <- getLine
       let num = (read input1 :: Int)
       let l = map (read :: String -> Int) . words $ input2
       let (a,b) = maxMinFold l
       let res = b - a - num + 1
       putStr (show res)

import Control.Applicative
import Data.List
import Data.Maybe
import qualified Data.ByteString.Char8 as BS

readIntBS = fst . fromJust . BS.readInt

main = do
  n <- readLn :: IO Int
  xs <- map read . words <$> getLine :: IO [Int]

  print $ maximum xs - minimum xs + 1 - n

-- Codeforces 1041A

main :: IO ()
main = do
    n <- getLine >>= return.read :: IO Int
    as <- getLine >>= return.(map read).words :: IO [Int]
    putStrLn $ show (maximum as - minimum as - n + 1)

import Data.List
import Control.Monad

main = do
    let solution = sum . (\x-> zipWith (\x y->x-y-1) (tail x) x ) . sort
        int x =  read x ::Int
    l <-  getLine >>= return . int
    as <- getLine >>=  return . map int . words
    print $ solution as

import Data.List

main=do
     e1<-getLine
     es<-getLine
     let xs=map read (words es)::[Int]
         a=read e1::Int
     print $ (maximum xs)-(minimum xs)-a+1

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

readInt = readLn :: IO Int
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
second xs = map fst $ filter (even . snd) $ zip xs [1..]

solve :: [Int] -> Int
solve xs = (l - f + 1) - n
    where ys = sort xs
          f  = head ys
          l  = last ys
          n  = length xs

main :: IO ()
main = do
    _ <- getLine
    v <- readInts
    print $ solve v

main = do
  (n:as) <- map read . words <$> getContents
  print $ maximum as - minimum as - n + 1

main = getContents >>= print . solve . map read . words

solve (n:as) = maximum as - minimum as + 1 - n

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

main= do
		getLine
		a<- map read <$> words <$> getLine ::IO [Int]
		let mi = minimum a
		let ma = maximum a
		print $ (ma-mi)+1-(length a)

main :: IO ()
main = interact (solve . lines)

solve :: [String] -> String
solve s = show $ solve' $  last s

solve' line =
 let nums = map (read :: String -> Integer) (words line)
     nmax = maximum nums
     nmin = minimum nums in
     nmax - nmin + 1 - (toInteger (length nums))

process :: [Int] -> Int
process xs = (maximum xs - minimum xs + 1) - length xs

readInt :: String -> Int
readInt = read

main = do
    n <- fmap readInt getLine
    xs <- fmap (map readInt.words) getLine
    print $ process xs


Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.For simplicity, let us assume that Volodya's text can be represented as a single string.

Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.

Print exactly one number — the number of powerful substrings of the given string. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal".

import Data.Int
import qualified Data.ByteString.Char8 as C

main :: IO()
main = do
	str <- C.getLine
	let pre = C.findSubstrings (C.pack "heavy") str
	    suf = C.findSubstrings (C.pack "metal") str
	print $ solve pre suf (length suf) (0::Int64)
	where
		solve [] _ _ s = s
		solve _ [] _ s = s
		solve a@(ah:at) b@(bh:bt) c s
			| ah < bh = solve at b c (s + fromIntegral c)
			| otherwise = solve a bt (c-1) s

import Data.Int
import qualified Data.ByteString.Char8 as C

main :: IO ()
main = do
  str <- C.getLine
  let pre = C.findSubstrings (C.pack "heavy") str
      suf = C.findSubstrings (C.pack "metal") str
  print $ gao pre suf (length suf) (0::Int64)
  where
    gao [] _ _ s = s
    gao _ [] _ s = s
    gao a@(ah:at) b@(bh:bt) c s
      | ah < bh   = gao at b c (s + fromIntegral c)
      | otherwise = gao a bt (c - 1) s

import Data.List

main = do
    line <- getLine
    let heavyBits = getOccuranceBits line "heavy"
    let metalBits = getOccuranceBits line "metal"
    let heavyScan = scanl1 (+) (heavyBits)
    let answerScan = zipWith (\x y -> if (y == 0) then 0 else x) heavyScan metalBits
    print (sum answerScan)

getOccuranceBits :: [Char] -> [Char] -> [Integer]
getOccuranceBits [] _ = []
getOccuranceBits (c:cs) (pattern) = now : (getOccuranceBits cs pattern) where
    now = if (isPrefixOf (pattern) (c:cs)) then 1 else 0

import Data.List

main = do
    line <- getLine
    let heavyBits = getOccuranceBits line "heavy"
    let metalBits = getOccuranceBits line "metal"
    let heavyScan = scanl1 (+) (heavyBits)
    let answerScan = zipWith (*) heavyScan metalBits
    print (sum answerScan)

getOccuranceBits :: [Char] -> [Char] -> [Integer]
getOccuranceBits [] _ = []
getOccuranceBits (c:cs) (pattern) = now : (getOccuranceBits cs pattern) where
    now = if (isPrefixOf (pattern) (c:cs)) then 1 else 0

import qualified Data.ByteString as B

main :: IO ()
main = print . solve 0 0 =<< B.getLine

solve :: Integer -> Integer -> B.ByteString -> Integer
solve s h xs
  | heavy `B.isPrefixOf` xs = seq hh $ solve s hh (B.drop 5 xs)
  | metal `B.isPrefixOf` xs = seq ss $ solve ss h (B.drop 5 xs)
  | B.null xs = s
  | otherwise = solve s h (B.tail xs)
  where
  hh = h + 1
  ss = s + h

heavy :: B.ByteString
heavy = B.pack [104,101,97,118,121]

metal :: B.ByteString
metal = B.pack [109,101,116,97,108]

import Data.List

hail :: Integer -> String -> Integer
hail n [] = 0
hail n ('h':'e':'a':'v':'y':xs) = hail (n `seq` n+1) xs
hail n ('m':'e':'t':'a':'l':xs) = n + hail n xs
hail n s = hail n (tail s)

main = interact $ show . hail 0

import Control.Monad (liftM)
import Data.Array ((!), listArray)
import Prelude hiding (reads)

reads :: Read a => IO [a]
reads  =  liftM (map read . words) getLine

solve :: String -> Integer
solve s  =  sum [d ! i | i <- [1..n], d ! i == d ! (i-1)]
  where
    n  =  length $ solve' s
    d  =  listArray (0, n) $ scanl (+) 0 $ solve' s
    solve' ""  =  []
    solve' ('h':'e':'a':'v':'y':s)  =  1 : solve' s
    solve' ('m':'e':'t':'a':'l':s)  =  0 : solve' s
    solve' s  =  solve' $ tail s

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

{-# LANGUAGE PatternGuards #-}

import Control.Concurrent
import Control.Monad
import System.IO
import Text.Printf
import System.Environment

main = subMain

handler:: String -> [Int] -> Integer -> Integer -> Integer
handler ('h':str) result heavyCount metallCount = findHeavy str result heavyCount metallCount
handler ('m':str) result heavyCount metallCount = findMetal str result heavyCount metallCount
handler (_:str) result heavyCount metallCount = handler str result heavyCount metallCount
handler [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0

findHeavy:: String -> [Int] -> Integer -> Integer -> Integer
findHeavy ('e':('a':('v':('y':str))))result heavyCount metallCount = handler str (0:result)(heavyCount + 1) metallCount
findHeavy [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0
findHeavy str result heavyCount metallCount = handler str result heavyCount metallCount

findMetal:: String -> [Int] -> Integer -> Integer -> Integer
findMetal ('e':('t':('a':('l':str))))result heavyCount metallCount = handler str (1:result) heavyCount (metallCount + 1)
findMetal [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0
findMetal str result heavyCount metallCount = handler str result heavyCount metallCount

checkResult:: [Int] -> Integer -> Integer -> Integer ->Integer
--checkResult x heavyCount metallCount count = (x, heavyCount, metallCount)
checkResult (0:xs) heavyCount metallCount count = checkResult xs (heavyCount-1) metallCount (count+metallCount)
checkResult (1:xs) heavyCount metallCount count = checkResult xs heavyCount (metallCount-1) (count)
checkResult _ _ 0 count = count
checkResult _ 0 _ count = count
checkResult [] _ _ count = count

subMain = do
  text <- getLine
  print $ handler text [] 0 0

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

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

{-# LANGUAGE OverloadedStrings #-}

import qualified Data.ByteString.Char8 as C
import Control.Applicative ((<$>))

calc' :: Integer -> Int -> C.ByteString -> Integer
--calc' r _ ss | C.length ss < 5 = r
--calc' r h ss = let (p,q) = C.splitAt 5 ss in
--  if p == "heavy"
--    then calc' r (h+1) q
--    else if p == "metal"
--           then calc' (r+h) h q
--           else if C.length q < 5 then r else calc' r h $ C.dropWhile f ss
--           where f x = and $ map (/= x) ['h','m']

calc' r _ ss | C.length ss < 5        = r
calc' r h ss | C.take 5 ss == "heavy" = calc' r (h+1) $ C.drop 5 ss
             | C.take 5 ss == "metal" = calc' (r+(toInteger h)) h $ C.drop 5 ss
             | otherwise              = calc' r h $ C.dropWhile f (C.tail ss)
                 where f x = and $ map (/= x) ['h','m']

--calc' r h ('h':'e':'a':'v':'y':ss) = calc' r (h+1) ss
--calc' r h ('m':'e':'t':'a':'l':ss) = calc' (r+h) h ss
--calc' r h (_:ss)                   = calc' r h (dropWhile f ss)
--          where f x = and $ map (/= x) ['h','m']

calc :: C.ByteString -> Integer
calc = calc' 0 0

main = print =<< calc <$> C.getLine

energy :: String -> Integer
energy str = energy' 0 str
  where energy' _ "" = 0
        energy' heavys ('h':'e':'a':'v':'y':rest) = energy' (succ heavys) rest
        energy' heavys ('m':'e':'t':'a':'l':rest) = heavys + energy' heavys rest
        energy' heavys (_:rest) = energy' heavys rest

main = do
  str <- getLine
  putStrLn $ show (energy str)

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Array.Base
import Data.Array.ST (runSTUArray)

main :: IO ()
main = B.getLine>>=print.solve.head.B.words

solve :: B.ByteString -> Integer
solve bs = go 0 0 bs
   where
     !n = B.length bs
     !ms = metal n bs
     go !i !res xs
       | B.null xs = res
       | B.isPrefixOf "heavy" xs = go (i+5) (res+fromIntegral(unsafeAt ms (i+5))) $ B.drop 5 xs
       | otherwise = go (i+1) res $ B.tail xs

metal :: Int -> B.ByteString -> UArray Int Int
metal n bs = runSTUArray $ do
  a <- newArray (0,n+100) 0 :: ST s (STUArray s Int Int)
  let go !i xs
        | B.isPrefixOf"metal"xs = do
             unsafeWrite a i 1
             go (i+5) $ B.drop 5 xs
        | B.null xs = return ()
        | otherwise = go (i+1) $ B.tail xs
  go 0 bs
  forM_ [n-1,n-2..1] $ \i-> do
    ai <- unsafeRead a i
    unsafeRead a(i-1)>>=unsafeWrite a (i-1).(ai+)
  return a

import Data.List

pre str i = isPrefixOf "heavy" (drop (i-1) str)
suf str i = isSuffixOf "metal" (take i str)

{--
solve str = pair 0 ss tt
    where len = length str
          ss = filter (pre str) [1..len]
          tt = filter (suf str) [1..len]
          pair sum s@(x:xs) t@(y:ys)
            | x + 4 <= y = pair ( sum + (length t) ) xs t
            | otherwise = pair sum s ys
          pair sum _ _ = sum
--}

solve str = solve' 0 str
    where solve' sum ('h':'e':'a':'v':'y':xs) = solve' (sum+1) xs
          solve' sum ('m':'e':'t':'a':'l':xs) = sum + solve' sum xs
          solve' sum (x:xs) = solve' sum xs
          solve' _ _ = 0
main = do
    interact $ show . solve

import qualified Data.ByteString.Char8 as BS
import qualified Data.Set as Set

main :: IO ()
main = do
  s <- BS.getLine
  print $ rush s

rush :: BS.ByteString -> Integer
rush s = let heads = BS.findSubstrings (BS.pack "heavy") s
             tails = BS.findSubstrings (BS.pack "metal") s
             headSet = Set.fromAscList heads
             f t acc = acc + fromIntegral (Set.size (fst (Set.split t headSet)))
         in
             foldr f 0 tails

import Data.List

main = do
    line <- getLine
    let heavyBits = getOccuranceBits line "heavy"
    let metalBits = getOccuranceBits line "metal"
    let heavyScan = scanl1 (+) (heavyBits)
    let answerScan = zipWith (\x y -> if (y == 0) then 0 else x) heavyScan metalBits
    print (sum answerScan)

getOccuranceBits :: [Char] -> [Char] -> [Int]
getOccuranceBits [] _ = []
getOccuranceBits (c:cs) (pattern) = now : (getOccuranceBits cs pattern) where
    now = if (isPrefixOf (pattern) (c:cs)) then 1 else 0

import qualified Data.ByteString as B

main :: IO ()
main = print . solve 0 =<< B.getLine

solve :: Int -> B.ByteString -> Int
solve h xs
  | heavy `B.isPrefixOf` xs = solve (h + 1) (B.drop 5 xs)
  | metal `B.isPrefixOf` xs = h + solve h (B.drop 5 xs)
  | B.null xs = 0
  | otherwise = solve h (B.tail xs)

heavy :: B.ByteString
heavy = B.pack [104,101,97,118,121]

metal :: B.ByteString
metal = B.pack [109,101,116,97,108]

{-# LANGUAGE PatternGuards #-}

import Control.Concurrent
import Control.Monad
import System.IO
import Text.Printf
import System.Environment

main = subMain

handler:: String -> [Int] -> Integer -> Integer -> Integer
handler ('h':str) result heavyCount metallCount = findHeavy str result heavyCount metallCount
handler ('m':str) result heavyCount metallCount = findMetal str result heavyCount metallCount
handler (_:str) result heavyCount metallCount = handler str result heavyCount metallCount
handler [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0

findHeavy:: String -> [Int] -> Integer -> Integer -> Integer
findHeavy ('e':('a':('v':('y':str))))result heavyCount metallCount = handler str (0:result)(heavyCount + 1) metallCount
findHeavy (_:str) result heavyCount metallCount = handler str result heavyCount metallCount
findHeavy [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0

findMetal:: String -> [Int] -> Integer -> Integer -> Integer
findMetal ('e':('t':('a':('l':str))))result heavyCount metallCount = handler str (1:result) heavyCount (metallCount + 1)
findMetal (_:str) result heavyCount metallCount = handler str result heavyCount metallCount
findMetal [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0

checkResult:: [Int] -> Integer -> Integer -> Integer ->Integer
checkResult (0:xs) heavyCount metallCount count = checkResult xs (heavyCount-1) metallCount (count+metallCount)
checkResult (1:xs) heavyCount metallCount count = checkResult xs heavyCount (metallCount-1) (count)
checkResult _ _ 0 count = count
checkResult _ 0 _ count = count
checkResult [] _ _ count = count

subMain = do
  text <- getLine
  print $ handler text [] 0 0

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

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

{-# LANGUAGE PatternGuards #-}

import Control.Concurrent
import Control.Monad
import System.IO
import Text.Printf
import System.Environment

main = subMain

handler ('h':str) result heavyCount metallCount = findHeavy str result heavyCount metallCount
handler ('m':str) result heavyCount metallCount = findMetal str result heavyCount metallCount
handler (_:str) result heavyCount metallCount = handler str result heavyCount metallCount
handler [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0

findHeavy ('e':('a':('v':('y':str))))result heavyCount metallCount = handler str (0:result)(heavyCount + 1) metallCount
findHeavy (_:str) result heavyCount metallCount = handler str result heavyCount metallCount
findHeavy [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0

findMetal ('e':('t':('a':('l':str))))result heavyCount metallCount = handler str (1:result)heavyCount(metallCount + 1)
findMetal (_:str) result heavyCount metallCount = handler str result heavyCount metallCount
findMetal [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0

checkResult (0:xs) heavyCount metallCount count = checkResult xs (heavyCount-1) metallCount (count+metallCount)
checkResult (1:xs) heavyCount metallCount count = checkResult xs heavyCount (metallCount-1) (count)
--checkResult _ _ 0 count = count
--checkResult _ 0 _ count = count
checkResult [] _ _ count = count

subMain = do
  text <- getLine
  print $ handler text [] 0 0

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

{-# LANGUAGE PatternGuards #-}

import Control.Concurrent
import Control.Monad
import System.IO
import Text.Printf
import System.Environment

main = subMain

handler ('h':str) result heavyCount metallCount = findHeavy str result heavyCount metallCount
handler ('m':str) result heavyCount metallCount = findMetal str result heavyCount metallCount
handler (_:str) result heavyCount metallCount = handler str result heavyCount metallCount
handler [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0

findHeavy ('e':('a':('v':('y':str))))result heavyCount metallCount = handler str (0:result)(heavyCount + 1) metallCount
findHeavy (_:str) result heavyCount metallCount = handler str result heavyCount metallCount
findHeavy [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0

findMetal ('e':('t':('a':('l':str))))result heavyCount metallCount = handler str (1:result)heavyCount(metallCount + 1)
findMetal (_:str) result heavyCount metallCount = handler str result heavyCount metallCount
findMetal [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0

checkResult (0:xs) heavyCount metallCount count = checkResult xs (heavyCount-1) metallCount (count+metallCount)
checkResult (1:xs) heavyCount metallCount count = checkResult xs heavyCount (metallCount-1) (count)
checkResult _ _ 0 count = count
checkResult _ 0 _ count = count
checkResult [] _ _ count = count

subMain = do
  text <- getLine
  print $ handler text [] 0 0

{-# LANGUAGE OverloadedStrings #-}

import qualified Data.ByteString.Char8 as C
import Control.Applicative ((<$>))

calc' :: Int -> Int -> C.ByteString -> Int
--calc' r _ ss | C.length ss < 5 = r
--calc' r h ss = let (p,q) = C.splitAt 5 ss in
--  if p == "heavy"
--    then calc' r (h+1) q
--    else if p == "metal"
--           then calc' (r+h) h q
--           else if C.length q < 5 then r else calc' r h $ C.dropWhile f ss
--           where f x = and $ map (/= x) ['h','m']

calc' r _ ss | C.length ss < 5        = r
calc' r h ss | C.take 5 ss == "heavy" = calc' r (h+1) $ C.drop 5 ss
             | C.take 5 ss == "metal" = calc' (r+h) h $ C.drop 5 ss
             | otherwise              = calc' r h $ C.dropWhile f (C.tail ss)
                 where f x = and $ map (/= x) ['h','m']

--calc' r h ('h':'e':'a':'v':'y':ss) = calc' r (h+1) ss
--calc' r h ('m':'e':'t':'a':'l':ss) = calc' (r+h) h ss
--calc' r h (_:ss)                   = calc' r h (dropWhile f ss)
--          where f x = and $ map (/= x) ['h','m']

calc :: C.ByteString -> Int
calc = calc' 0 0

main = print =<< calc <$> C.getLine


Let's call a positive integer $$$n$$$ ordinary if in the decimal notation all its digits are the same. For example, $$$1$$$, $$$2$$$ and $$$99$$$ are ordinary numbers, but $$$719$$$ and $$$2021$$$ are not ordinary numbers.For a given number $$$n$$$, find the number of ordinary numbers among the numbers from $$$1$$$ to $$$n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case is characterized by one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case output the number of ordinary numbers among numbers from $$$1$$$ to $$$n$$$.

import Control.Monad

main = do
    t <- read <$> getLine
    replicateM_ t $ getLine >>= print . solve

solve :: [Char] -> Int
solve x = length x * 9 + read [head x] - 10 + fromEnum (x >= t)
    where t = replicate (length x) (head x)

import Control.Monad

printResult = do
    s <- getLine
    let
        l = length s
        n = read s :: Int
        b = read $ replicate l '1' :: Int
        r = (l-1) * 9 + div n b
    print r

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

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

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

createString 0 = ""
createString n = "1" ++ createString (n-1)

printS = do
    n<-getLine
    let s = createString (length n)
        x = read s :: Int
        y = read n :: Int
    print $ (length n - 1) * 9 + (div y x)

main = do
    t<-readLn
    replicateM_ t printS

import Control.Arrow
import Data.List

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

ordinary :: [Integer]
ordinary = [d*(10^l - 1) `div` 9 | d <- [1..9], l <- [1..9]]

solve :: Integer -> Int
solve n = length $ filter (<= n) ordinary

import Control.Monad

main = do
    t <- read <$> getLine
    replicateM_ t $
        getLine >>=
        print . \x ->
            length x * 9 + read [head x] - 10 + fromEnum (head x == minimum x)


You are given two arrays $$$a$$$ and $$$b$$$ of $$$n$$$ positive integers each. You can apply the following operation to them any number of times:  Select an index $$$i$$$ ($$$1\leq i\leq n$$$) and swap $$$a_i$$$ with $$$b_i$$$ (i. e. $$$a_i$$$ becomes $$$b_i$$$ and vice versa). Find the minimum possible value of $$$\max(a_1, a_2, \ldots, a_n) \cdot \max(b_1, b_2, \ldots, b_n)$$$ you can get after applying such operation any number of times (possibly zero).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1\le n\le 100$$$) — the length of the arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$) where $$$a_i$$$ is the $$$i$$$-th element of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 10\,000$$$) where $$$b_i$$$ is the $$$i$$$-th element of the array $$$b$$$.

For each test case, print a single integer, the minimum possible value of $$$\max(a_1, a_2, \ldots, a_n) \cdot \max(b_1, b_2, \ldots, b_n)$$$ you can get after applying such operation any number of times.

NoteIn the first test, you can apply the operations at indices $$$2$$$ and $$$6$$$, then $$$a = [1, 4, 6, 5, 1, 5]$$$ and $$$b = [3, 2, 3, 2, 2, 2]$$$, $$$\max(1, 4, 6, 5, 1, 5) \cdot \max(3, 2, 3, 2, 2, 2) = 6 \cdot 3 = 18$$$.In the second test, no matter how you apply the operations, $$$a = [3, 3, 3]$$$ and $$$b = [3, 3, 3]$$$ will always hold, so the answer is $$$\max(3, 3, 3) \cdot \max(3, 3, 3) = 3 \cdot 3 = 9$$$.In the third test, you can apply the operation at index $$$1$$$, then $$$a = [2, 2]$$$, $$$b = [1, 1]$$$, so the answer is $$$\max(2, 2) \cdot \max(1, 1) = 2 \cdot 1 = 2$$$.

import Control.Monad

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

process :: IO ()
process = do
    nLine <- getLine  -- ignore n
    aLine <- getLine
    bLine <- getLine
    print (minMaxProd (parse aLine) (parse bLine))
    where
        parse line = map read (words line)
        minMaxProd a b = c * d
            where
                c = maximum (zipWith max a b)
                d = maximum (zipWith min a b)

import Control.Monad

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

process :: IO ()
process = do
    n <- (readLn :: IO Int)
    line <- getLine
    let a = map read (words line)
    line <- getLine
    let b = map read (words line)
    let c = maximum (zipWith min a b)
    let d = maximum (zipWith max a b)
    print (c * d)

import Control.Arrow ((>>>))

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

solve :: [[Int]] -> Int
solve [_, as, bs] = maximum (zipWith min as bs) * maximum (zipWith max as bs)

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

module Main where

(|>) = flip ($)

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

swapfix :: Ord a => (a, a) -> (a, a)
swapfix (x, y) = (min x y, max x y)

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

solve :: [[Int]] -> Int
solve [a, b] =
    let fixed = swapfix <$> zip a b in
    let acost = foldl1 max (fst <$> fixed) in
    let bcost = foldl1 max (snd <$> fixed) in
    acost * bcost

main :: IO ()
main = interact $
    unlines
    . map (show . solve . parse)
    . chunksOf 3
    . tail
    . lines


Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (n ≤ k) values b1, b2, ..., bn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i. e. n < k. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant.

The first line contains two integers k and n (1 ≤ n ≤ k ≤ 2 000) — the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1, a2, ..., ak ( - 2 000 ≤ ai ≤ 2 000) — jury's marks in chronological order. The third line contains n distinct integers b1, b2, ..., bn ( - 4 000 000 ≤ bj ≤ 4 000 000) — the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order.

Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes).

NoteThe answer for the first example is 3 because initially the participant could have  - 10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4 002 000.

import qualified Data.Set as Set

findHead :: Int -> [Int] -> Int -> Set.Set Int
findHead _ [] _ = Set.empty
findHead psum (a:as) b = Set.insert (b - a - psum) $ findHead (psum + a) as b

solve :: [Int] -> [Int] -> Set.Set Int
solve as bs = foldr (Set.intersection . findHead 0 as) lll bs
    where lll = findHead 0 as (head bs)
-- solve as (b:bs)
--     | bs == []  = findHead 0 as b
--     | otherwise = Set.intersection (findHead 0 as b) $ solve as bs
--     -- | otherwise = Trace.traceShow (bs) $ solve as bs

main = do
    nk <- getLine
    a <- getLine
    b <- getLine
    let as = map read $ words a :: [Int]
        bs = map read $ words b :: [Int]
    print $ Set.size $ solve as bs

import qualified Data.Set as Set

findHead :: Integer -> [Integer] -> Integer -> Set.Set Integer
findHead _ [] _ = Set.empty
findHead psum (a:as) b = Set.insert (b - a - psum) $ findHead (psum + a) as b

solve :: [Integer] -> [Integer] -> Set.Set Integer
solve as bs = foldr (Set.intersection . findHead 0 as) lll bs
    where lll = findHead 0 as (head bs)
-- solve as (b:bs)
--     | bs == []  = findHead 0 as b
--     | otherwise = Set.intersection (findHead 0 as b) $ solve as bs
--     -- | otherwise = Trace.traceShow (bs) $ solve as bs

main = do
    nk <- getLine
    a <- getLine
    b <- getLine
    let as = map read $ words a :: [Integer]
        bs = map read $ words b :: [Integer]
    print $ Set.size $ solve as bs

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

main = do
  B.getLine
  as <- fmap readInts B.getLine
  bs <- fmap readInts B.getLine
  print $ S.size $ solve as bs

solve as bs = foldl1 S.intersection $ map (\b -> S.fromList $ map (b-) ss) bs
  where ss = scanl1 (+) as :: [Int]

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

import qualified Data.Set as Set

findHead :: Int -> [Int] -> Int -> Set.Set Int
findHead _ [] _ = Set.empty
findHead psum (a:as) b = Set.insert (b + a + psum) $ findHead (psum + a) as b

solve :: [Int] -> [Int] -> Set.Set Int
solve as bs = foldr (Set.intersection . findHead 0 as) lll bs
    where lll = findHead 0 as (last bs)

main = do
    nk <- getLine
    a <- getLine
    b <- getLine
    let as = map read $ words a :: [Int]
        bs = map read $ words b :: [Int]
    print $ Set.size $ solve as bs


Volodya and Vlad play the following game. There are k pies at the cells of n  ×  m board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the border of the board of length 1 (between two knots of the board) so that Volodya is not able to move the pie outside the board through this edge anymore. The question is: will Volodya win this game? We suppose both players follow the optimal strategy.

First line contains 3 integers, separated by space: 1 ≤ n, m ≤ 100 — dimensions of the board and 0 ≤ k ≤ 100 — the number of pies. Each of the next k lines contains 2 integers, separated by space: 1 ≤ x ≤ n, 1 ≤ y ≤ m — coordinates of the corresponding pie. There could be more than one pie at a cell.

Output only one word: "YES" — if Volodya wins, "NO" — otherwise.

import qualified Data.ByteString.Lazy.Char8 as C
import IO
import Data.Maybe

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

main = do
	input <- fmap (map (C.takeWhile (/='\r')) . C.lines) $ C.hGetContents stdin
	let [n, m, k] = readIntList $ head input
	let ps = map readIntList . take k $ tail input
	putStrLn $ if elem True [ foldl min (x-1) [n-x, y-1, m-y] < 5 | [x, y] <- ps ] then "YES" else "NO"

readLL :: String -> [Int]
readLL = (map read) . words
main = do
[n, m, k] <- getLine >>= return . readLL
ps <- getContents >>= return . (map readLL) . (take k) . lines
putStrLn $ if any (\[x, y] -> any (<=5) [x, y, (n-x+1), (m-y+1)]) ps then "YES" else "NO"

import Control.Monad (liftM)

(<?>) :: a -> a -> Bool -> a
(<?>) a b p  =  if p then a else b

reads :: Read a => IO [a]
reads  =  liftM (map read . words) getLine

solve :: Int -> Int -> [[Int]] -> Bool
solve n m xs  =  any p xs
  where
    p [x, y]  =  x <= 5 || y <= 5 || (n - x) + 1 <= 5 || (m - y) + 1 <= 5

main :: IO ()
main  =  do
    [n, m, k]  <-  Main.reads
    xs  <-  mapM (const Main.reads) [1..k]
    putStrLn $ "YES" <?> "NO" $ solve n m xs

import Control.Monad

main = do
    [n, m, k] <- liftM (map read . words) getLine
    list <- replicateM k $ do
        [a, b] <- liftM (map read . words) getLine
        return $ a <= 5 || b <= 5 || a >= n - 4 || b >= m - 4

    putStrLn $ if or list then "YES" else "NO"

import qualified Data.ByteString.Lazy.Char8 as C
import IO
import Data.Maybe

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

main = do
	input <- fmap (map (C.takeWhile (/='\r')) . C.lines) $ C.hGetContents stdin
	let [n, m, k] = readIntList $ head input
	let ps = map readIntList . take k $ tail input
	putStrLn $ if elem True [ foldl min (x+1) [n-x, (y+1), m-y] < 5 | [x, y] <- ps ] then "YES" else "NO"

import qualified Data.ByteString.Lazy.Char8 as C
import IO
import Data.Maybe

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

main = do
	input <- fmap (map (C.takeWhile (/='\r')) . C.lines) $ C.hGetContents stdin
	let [n, m, k] = readIntList $ head input
	let ps = map readIntList . take k $ tail input
	putStrLn $ if elem True [ foldl min x [n-1-x, y, m-1-y] < 5 | [x, y] <- ps ] then "YES" else "NO"

------------------------------------------------------------------------
-- 55C. Кекс или смерть
------------------------------------------------------------------------
-- Created: 11.03.2011 18:09:43 Russian Standard Time
-- Copyright 2011 jz <da-eto@ya.ru>

module Main (main) where

readLL :: String -> [Int]
readLL = (map read) . words

-- main function
main = do
    [n, m, k] <- getLine >>= return . readLL
    ps <- getContents >>= return . (map readLL) . (take k) . lines
    putStrLn $ if solve n m ps then "YES" else "NO" where

    solve n m ps = any isWin ps where
        isWin [x, y] = any (<=4) [x, y, (n-x+1), (m-y+1)]

------------------------------------------------------------------------
-- 55C. Кекс или смерть
------------------------------------------------------------------------
-- Created: 11.03.2011 18:09:43 Russian Standard Time
-- Copyright 2011 jz <da-eto@ya.ru>

module Main (main) where

readLL :: String -> [Int]
readLL = (map read) . words

-- main function
main = do
    [n, m, k] <- getLine >>= return . readLL
    ps <- getContents >>= return . (map readLL) . (take k) . lines
    putStrLn $ if solve n m ps then "YES" else "NO" where

    solve n m ps = any isWin ps where
        isWin [x, y] = any (<=3) [x, y, (n-x+1), (m-y+1)]

import Control.Monad

main = do
    [n, m, k] <- liftM (map read . words) getLine
    list <- replicateM k $ do
        [a, b] <- liftM (map read . words) getLine
        return $ a <= 5 || b <= 5 || a >= n - 4 || b >= m - 4

    putStrLn $ if and list then "YES" else "NO"


Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.

The single line contains two integers, n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1000).

Print any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value. If there are multiple suitable tables, you are allowed to print any of them.

NoteIn the first sample the sum in the first row is 1 + 3 = 4, in the second row — 3 + 1 = 4, in the first column — 1 + 3 = 4 and in the second column — 3 + 1 = 4. There are other beautiful tables for this sample.In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements.

import Control.Applicative
import Data.List
main :: IO ()
main = do
    inp <- map read <$> words <$> getLine
    let n = inp !! 0 :: Int
        k = inp !! 1
    mapM_ (putStrLn . intercalate " " . map show) $ solve n k n
solve :: Int -> Int -> Int -> [[Int]]
solve _ _ 0 =  []
solve n k left = (replicate (n-left) 0 ++ [k] ++ replicate (left - 1) 0) : solve n k (left - 1)

import Control.Applicative
import Data.List
main :: IO ()
main = do
    inp <- map read <$> words <$> getLine
    let n = inp !! 0 :: Int
        k = inp !! 1
    mapM_ (putStrLn . intercalate " " . map show)
        $ [ [ if x == y then k else 0 | y <- [1..n]] | x <- [1 .. n]]

import Control.Monad

import Data.Char
import Data.List

generateList :: Int -> Int -> [Int]
generateList 0 _ = []
generateList n k = [ele] ++ (generateList (n - 1) (k - ele))
    where ele = min 1000 k

solve :: Int -> [Int] -> [[Int]]
solve 0 _ = []
solve n mList = (drop n mList ++ take n mList) : (solve (n - 1) mList)

main :: IO ()
main = do
    input <- getContents
    let [n, k] = map read . words $ input
    let mList = generateList n k
    putStrLn $ unlines . map (intercalate " " . map show) . solve n $ mList

import Control.Monad (liftM, forM_)
import Data.Char (ord)
import Data.List (intercalate)

main :: IO ()
main  =  do
    [n, k]  <-  reads
    forM_ [1..n] (\i -> prints [if i == j then k else 0 | j <- [1..n]])

  where

    prints :: Show a => [a] -> IO ()
    prints  =  putStrLn . intercalate " " . map show

    readPair :: Num a => IO (a, a)
    readPair  =  do
        [a, b]  <-  reads
        return (a, b)

    reads :: Num a => IO [a]
    reads  =  liftM (map read . words) getLine
      where
        read ('-':s)  =  (-1) * read s
        read s  =  read' 0 s
        read' a ""  =  a
        read' a (c:s)  =  read' a' s
          where
            a'  =  10 * a + fromIntegral (ord c - ord '0')

f::Int->Int->Int->String
f x y n
   |x==y=show n
   |otherwise=show 0

f2::Int->Int->Int->[String]
f2 y m n
   |y>m=[]
   |otherwise=(unwords [f x y n|x<-[1..m]]):f2 (y+1) m n

main = do
       e<-getLine
       let (n:k:[])= map read (words e)::[Int]
       mapM_ putStrLn $ f2 (1::Int) n k

import Control.Applicative ((<$>))
import Data.List (unfoldr)

main :: IO ()
main = mapM_ (putStrLn . unwords . map show) =<< solve . toTuple . map read . words <$> getLine

solve :: (Int, Int) -> [[Int]]
solve (n, k) = take n $ splitN n $ cycle (k : replicate n 0)

splitN :: Int -> [a] -> [[a]]
splitN n = takeWhile (not . null) . unfoldr (Just . splitAt n)

toTuple :: [a] -> (a, a)
toTuple xs = (head xs, xs !! 1)

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

process n k i = do
		putStr $ concat $ replicate (i-1) "0 "
		putStr $ (show k)++ " "
		putStrLn $ concat $ replicate (n-i) "0 "

main = do
		[n,k]<- map read <$> words <$> getLine::IO [Int]
		mapM_ (process n k) [1..n]

process :: Int -> Int -> [[Int]]
process n k = [[if i==j then k else 0 | j <- [1..n]] | i <- [1..n]]

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    [n,k] <- fmap (map readInt.words) getLine
    mapM_ (putStrLn.unwords.map show) $ process n k

import Data.Tuple
import Data.List
cal ls = let n = read $ head $ words $  (ls !! 0)
	     k = read $ last $ words $  (ls !! 0)
	     toN = [0..(n-1)]
	 in map (\a -> concatMap (\b -> show b ++ " ") a) $ map (\i -> make n i k) toN

make n i k = let zeros = [0,0..]
           in (take i zeros) ++ [k] ++ (take (n-i-1) zeros)

main = interact (unlines . cal . lines)


You are given a positive integer $$$n$$$. In one move, you can increase $$$n$$$ by one (i.e. make $$$n := n + 1$$$). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of $$$n$$$ be less than or equal to $$$s$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$n$$$ and $$$s$$$ ($$$1 \le n \le 10^{18}$$$; $$$1 \le s \le 162$$$).

For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of $$$n$$$ be less than or equal to $$$s$$$.

import Control.Monad

sumOfDigits :: Integer -> Integer
sumOfDigits = sum . map (`mod` 10) . takeWhile (> 0) . iterate (`div` 10)

pows10 :: [Integer]
pows10 = iterate (* 10) 1

options :: Integer -> [Integer]
options n = map (\x -> n + case  mod n x  of  { 0 -> 0; r -> x-r }) $ pows10

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [n, s] <- map read . words <$> getLine
    let  newN = head $ dropWhile ((> s) . sumOfDigits) (options n)
    print $ newN - n


Bimokh is Mashmokh's boss. For the following n days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of tokens but he can't use it in any other day to get more money. If a worker gives back w tokens then he'll get  dollars. Mashmokh likes the tokens however he likes money more. That's why he wants to save as many tokens as possible so that the amount of money he gets is maximal possible each day. He has n numbers x1, x2, ..., xn. Number xi is the number of tokens given to each worker on the i-th day. Help him calculate for each of n days the number of tokens he can save.

The first line of input contains three space-separated integers n, a, b (1 ≤ n ≤ 105; 1 ≤ a, b ≤ 109). The second line of input contains n space-separated integers x1, x2, ..., xn (1 ≤ xi ≤ 109).

Output n space-separated integers. The i-th of them is the number of tokens Mashmokh can save on the i-th day.

parseInput = map (read :: String -> Integer).words

f :: Integer -> Integer -> [Integer] -> [Integer]
f a b [] = []
f a b (x:xs) = (x * a `mod` b) `div` a : f a b xs

main = do
    s <- getLine
    let [n, a, b] = parseInput s
    xs <- getLine
    putStrLn $ unwords. map show $ f a b $ parseInput xs

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  [n,a,b] <- map read.words <$> getLine
  xs <- map(fromIntegral.readInt).B.words <$> B.getContents
  putStr.unwords.map show $ solve a b xs

solve :: Integer -> Integer -> [Integer] -> [Integer]
solve a b xs = do
  x <- xs
  let (!q,!r) = (a*x)`quotRem`b
      p w = q*b <= a*w && a*w <= a*x
  [x - lowerBound p 0 x]

lowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i
lowerBound p low high = go low high
   where
     go !low !high
       | high <= low = high
       | p mid       = go low       mid
       | otherwise   = go (mid + 1) high
      where
        mid = (low + high) `quot` 2
{-# INLINE lowerBound #-}

parseInput = map (read :: String -> Integer).words

f :: Integer -> Integer -> [Integer] -> [Integer]
f a b [] = []
f a b (x:xs) = (x * a `mod` b) : f a b xs

main = do
    s <- getLine
    let [n, a, b] = parseInput s
    xs <- getLine
    putStrLn $ unwords. map show $ f a b $ parseInput xs

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  [n,a,b] <- map read.words <$> getLine
  xs <- map(fromIntegral.readInt).B.words <$> B.getContents
  putStr.unwords.map show $ solve a b xs

solve :: Integer -> Integer -> [Integer] -> [Integer]
solve a b xs = [(a*x)`rem`b | x<-xs]


«Next please», — the princess called and cast an estimating glance at the next groom.The princess intends to choose the most worthy groom, this is, the richest one. Whenever she sees a groom who is more rich than each of the previous ones, she says a measured «Oh...». Whenever the groom is richer than all previous ones added together, she exclaims «Wow!» (no «Oh...» in this case). At the sight of the first groom the princess stays calm and says nothing.The fortune of each groom is described with an integer between 1 and 50000. You know that during the day the princess saw n grooms, said «Oh...» exactly a times and exclaimed «Wow!» exactly b times. Your task is to output a sequence of n integers t1, t2, ..., tn, where ti describes the fortune of i-th groom. If several sequences are possible, output any of them. If no sequence exists that would satisfy all the requirements, output a single number -1.

The only line of input data contains three integer numbers n, a and b (1 ≤ n ≤ 100, 0 ≤ a, b ≤ 15, n > a + b), separated with single spaces.

Output any sequence of integers t1, t2, ..., tn, where ti (1 ≤ ti ≤ 50000) is the fortune of i-th groom, that satisfies the given constraints. If no sequence exists that would satisfy all the requirements, output a single number -1.

NoteLet's have a closer look at the answer for the first sample test.   The princess said «Oh...» (highlighted in bold): 5 1 3 6 16 35 46 4 200 99.  The princess exclaimed «Wow!» (highlighted in bold): 5 1 3 6 16 35 46 4 200 99.

import Control.Monad
import Data.List
next (n, a, b, l, s) = if n == 0 then Nothing
                       else Just (if b > 0 then (s+1, (n-1, a, b-1, s+1, 2*s+1))
                       else if a > 0 then (l+1, (n-1, a-1, b, l+1, s+l+1))
                       else (l, (n-1, a, b, l, l+s)))
main = do
  [n, a, b] <- (liftM ((map read) . words)) getLine
  putStrLn . unwords . map show $ if n == 1 then [1]
                                  else if a == n-1 then [-1]
                                  else if b > 0 then 1 : unfoldr next (n-1, a, b, 1, 1)
                                  else 1 : 1 : unfoldr next (n-2, a, b, 1, 2)

readWords :: IO [String]
readWords = getLine >>= return . words

reads :: Read a => IO [a]
reads = readWords >>= return . (map read)

powersOfTwo :: [Int]
powersOfTwo  =  zipWith (^) (repeat 2) [1..]

solve :: Int -> Int -> Int -> [Int]
solve n 0 0  =  replicate n 1
solve n a 0
  | n > a + 1  =  [1, 1] ++ [2..a+1] ++ (replicate (n-2-a) 1)
  | otherwise  =  []
solve n a b
  =  [1]
  ++ (take b powersOfTwo)
  ++ [2^b+1..2^b+a]
  ++ (replicate (n - 1 - a - b) 1)

printAns :: [Int] -> IO ()
printAns xs  =  printAns_ xs
  where
    printAns_ []      =  print (-1)
    printAns_ [x]     =  print x
    printAns_ (x:xs)  =  putStr (show x ++ " ") >> printAns_ xs

main :: IO ()
main = do
    [n, a, b] <- Main.reads
    printAns (solve n a b)

makeWows 0 = [const 1]
makeWows b = replicate b (*2)

makeOhs a = replicate a (+1)

makeSeq a b n = (makeWows b++makeOhs a++(repeat id))

solve [n,a,b]
	|a>0&&b==0&&n==a+1 = [-1]
	|otherwise = take n $ scanl (flip ($)) 1 (makeSeq a b n)

main=interact$unlines.map show.solve.map read.words

import Data.List
import Control.Monad

rich = 1:[sum [rich !! j | j <- [0..i-2]] + 1
        | i <- [2..]]

solve n a b | b /= 0 = do
    let rich1 = take (b + 1) rich
    let rich2 = [last rich1+1..last rich1 + a]
    let rich3 = replicate (n - a - b - 1) 1

    putStrLn $ intercalate " " $ map show (rich1++rich2++rich3)

solve n a b | a + 2 <= n = do
    let rich1 = [1,1]
    let rich2 = [last rich1+1..last rich1 + a]
    let rich3 = replicate (n - a - b - 2) 1

    putStrLn $ intercalate " " $ map show (rich1++rich2++rich3)

solve n a b | n == 1 = do
    putStrLn "1"

solve n a b = do
    putStrLn "-1"

main = do
    [n, a, b] <- liftM (map read . words) getLine

    solve n a b

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
import Foreign
import Foreign.C.Types
import Foreign.C.String
import Foreign.Marshal.Alloc
import Debug.Trace
import Data.List
import Control.Monad
import Control.Monad.ST
import qualified Data.Array.Unboxed as UB
import Data.Array.ST
import Data.Array
import Data.Char
class IOtyp a where scan' :: String -> a; show' :: a -> String
instance IOtyp Int where scan' = read; show' = show
instance IOtyp Char where scan' (x:_) = x;show' = (:[])
instance IOtyp Float where scan' = read;show' = show
instance IOtyp Double where scan' = read;show' = show
instance IOtyp Integer where scan' = read;show' = show
instance IOtyp String where scan' = id;show' = id
instance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y
instance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z
foreign import ccall "stdio.h puts" c_puts :: CString -> IO ()
scan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'
scans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan
scanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words
scanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist
puts :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}

solve 1 0 0 = [1]
solve n a b | n<=(a+1) = [-1]
solve n a 0 = take n (2:[2..(a+2)]++[1,1..])
solve n a_ b_ = rec a_ (b_+1) 0 0 n
    where
      rec 0 0 _ _ 0 = []
      rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)
      rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)
      rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)

main = do (n,a,b) <- scan :: IO (Int,Int,Int)
          putStrLn.unwords.map show $ solve n a b

s[n,a,b]|length g<n=take n$scanl(flip($))1(g++repeat(\_->1))|1>0=[-1]where q|b>0||a==0=replicate b(*2)|1>0=[id];g=q++replicate a(+1)
main=interact$unwords.map show.s.map read.words

import Control.Monad
import Data.List
next (n, a, b, l, s) = if n == 0 then Nothing
                       else Just (if b > 0 then (s+1, (n-1, a, b-1, s+1, 2*s+1))
                       else if a > 0 then (l+1, (n-1, a-1, b, l+1, s+l+1))
                       else (l, (n-1, a, b, l, l+s)))
main = do
  [n, a, b] <- (liftM ((map read) . words)) getLine
  putStrLn . unwords . map show $ 1 : 1: unfoldr next (n-2, a, b, 1, 2)

import Control.Monad
import Data.List
next (n, a, b, l, s) = if n == 0 then Nothing
                       else Just (if b > 0 then (s+1, (n-1, a, b-1, s+1, 2*s+1))
                       else if a > 0 then (l+1, (n-1, a-1, b, l+1, s+l+1))
                       else (l, (n-1, a, b, l, l+s)))
main = do
  [n, a, b] <- (liftM ((map read) . words)) getLine
  putStrLn . unwords . map show $ 1 : unfoldr next (n-1, a, b, 1, 1)

import Control.Monad
import Data.List
next (n, a, b, l, s) = if n == 0 then Nothing
                       else Just (if b > 0 then (s+1, (n-1, a, b-1, s+1, 2*s+1))
                       else if a > 0 then (l+1, (n-1, a-1, b, l+1, s+l+1))
                       else (l, (n-1, a, b, l, l+s)))
main = do
  [n, a, b] <- (liftM ((map read) . words)) getLine
  putStrLn . unwords . map show $ 1 : unfoldr next (n, a, b, 1, 1)

readWords :: IO [String]
readWords = getLine >>= return . words

reads :: Read a => IO [a]
reads = readWords >>= return . (map read)

powersOfTwo :: [Int]
powersOfTwo  =  zipWith (^) (repeat 2) [1..]

solve :: Int -> Int -> Int -> [Int]
solve n a 0
  | n > a + 1  =  [1, 1] ++ [2..a+1] ++ (replicate (n-2-a) 1)
  | otherwise  =  []
solve n a b
  =  [1]
  ++ (take b powersOfTwo)
  ++ [2^b+1..2^b+a]
  ++ (replicate (n - 1 - a - b) 1)

printAns :: [Int] -> IO ()
printAns xs  =  printAns_ xs
  where
    printAns_ []      =  print (-1)
    printAns_ [x]     =  print x
    printAns_ (x:xs)  =  putStr (show x ++ " ") >> printAns_ xs

main :: IO ()
main = do
    [n, a, b] <- Main.reads
    printAns (solve n a b)

makeSeq a b n = ((replicate b (*2))++(replicate a (+1))++(replicate (n-a-b-1) (const 1)))
solve [n,a,b]
	|b>0 = result 1
	|otherwise = result 2
	where result first = scanl (flip ($)) first (makeSeq a b n)

main=interact$unlines.map show.solve.map read.words

makeWows 0 = [const 1]
makeWows b = replicate b (*2)

makeOhs a = replicate a (+1)

makeSeq a b n = (makeWows b++makeOhs a++(replicate (n-a-b-1) id))

solve [n,a,b]
	|b==0&&n==a+1 = [-1]
	|otherwise = scanl (flip ($)) 1 (makeSeq a b n)

main=interact$unlines.map show.solve.map read.words

makeWows 0 = [const 1]
makeWows b = replicate b (*2)

makeOhs a = replicate a (+1)

makeSeq a b n = (makeWows b++makeOhs a++(repeat id))

solve [n,a,b]
	|b==0&&n==a+1 = [-1]
	|otherwise = take n $ scanl (flip ($)) 1 (makeSeq a b n)

main=interact$unlines.map show.solve.map read.words

import Data.List
import Control.Monad

rich = 1:[sum [rich !! j | j <- [0..i-2]] + 1
        | i <- [2..]]

main = do
    [n, a, b] <- liftM (map read . words) getLine

    let rich1 = take (b + 1) rich
    let rich2 = [last rich1+1..last rich1 + a]
    let rich3 = replicate (n - a - b - 1) 1

    putStrLn $ intercalate " " $ map show (rich1++rich2++rich3)

import Data.List
import Control.Monad

rich = 1:[sum [rich !! j | j <- [0..i-2]] + 1
        | i <- [2..]]

solve n a b | b /= 0 = do
    let rich1 = take (b + 1) rich
    let rich2 = [last rich1+1..last rich1 + a]
    let rich3 = replicate (n - a - b - 1) 1

    putStrLn $ intercalate " " $ map show (rich1++rich2++rich3)

solve n a b | a + 2 <= n = do
    let rich1 = [1,1]
    let rich2 = [last rich1+1..last rich1 + a]
    let rich3 = replicate (n - a - b - 2) 1

    putStrLn $ intercalate " " $ map show (rich1++rich2++rich3)

solve n a b = do
    putStrLn "-1"

main = do
    [n, a, b] <- liftM (map read . words) getLine

    solve n a b

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
import Foreign
import Foreign.C.Types
import Foreign.C.String
import Foreign.Marshal.Alloc
import Debug.Trace
import Data.List
import Control.Monad
import Control.Monad.ST
import qualified Data.Array.Unboxed as UB
import Data.Array.ST
import Data.Array
import Data.Char
class IOtyp a where scan' :: String -> a; show' :: a -> String
instance IOtyp Int where scan' = read; show' = show
instance IOtyp Char where scan' (x:_) = x;show' = (:[])
instance IOtyp Float where scan' = read;show' = show
instance IOtyp Double where scan' = read;show' = show
instance IOtyp Integer where scan' = read;show' = show
instance IOtyp String where scan' = id;show' = id
instance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y
instance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z
foreign import ccall "stdio.h puts" c_puts :: CString -> IO ()
scan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'
scans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan
scanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words
scanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist
puts :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}

solve n a_ b_ = rec a_ (b_+1) 0 0 n
    where
      rec 0 0 _ _ 0 = []
      rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)
      rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)
      rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)

main = do (n,a,b) <- scan :: IO (Int,Int,Int)
          putStrLn.unwords.map show $ solve n a b

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
import Foreign
import Foreign.C.Types
import Foreign.C.String
import Foreign.Marshal.Alloc
import Debug.Trace
import Data.List
import Control.Monad
import Control.Monad.ST
import qualified Data.Array.Unboxed as UB
import Data.Array.ST
import Data.Array
import Data.Char
class IOtyp a where scan' :: String -> a; show' :: a -> String
instance IOtyp Int where scan' = read; show' = show
instance IOtyp Char where scan' (x:_) = x;show' = (:[])
instance IOtyp Float where scan' = read;show' = show
instance IOtyp Double where scan' = read;show' = show
instance IOtyp Integer where scan' = read;show' = show
instance IOtyp String where scan' = id;show' = id
instance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y
instance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z
foreign import ccall "stdio.h puts" c_puts :: CString -> IO ()
scan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'
scans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan
scanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words
scanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist
puts :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}

solve n a_ 0 = [-1]

solve n a_ b_ = rec a_ (b_+1) 0 0 n
    where
      rec 0 0 _ _ 0 = []
      rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)
      rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)
      rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)

main = do (n,a,b) <- scan :: IO (Int,Int,Int)
          putStrLn.unwords.map show $ solve n a b

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
import Foreign
import Foreign.C.Types
import Foreign.C.String
import Foreign.Marshal.Alloc
import Debug.Trace
import Data.List
import Control.Monad
import Control.Monad.ST
import qualified Data.Array.Unboxed as UB
import Data.Array.ST
import Data.Array
import Data.Char
class IOtyp a where scan' :: String -> a; show' :: a -> String
instance IOtyp Int where scan' = read; show' = show
instance IOtyp Char where scan' (x:_) = x;show' = (:[])
instance IOtyp Float where scan' = read;show' = show
instance IOtyp Double where scan' = read;show' = show
instance IOtyp Integer where scan' = read;show' = show
instance IOtyp String where scan' = id;show' = id
instance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y
instance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z
foreign import ccall "stdio.h puts" c_puts :: CString -> IO ()
scan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'
scans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan
scanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words
scanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist
puts :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}

solve n 0 0 = take n [1,1..]
solve n 0 b = [-1]
solve n a_ b_ = rec a_ (b_+1) 0 0 n
    where
      rec 0 0 _ _ 0 = []
      rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)
      rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)
      rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)

main = do (n,a,b) <- scan :: IO (Int,Int,Int)
          putStrLn.unwords.map show $ solve n a b

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
import Foreign
import Foreign.C.Types
import Foreign.C.String
import Foreign.Marshal.Alloc
import Debug.Trace
import Data.List
import Control.Monad
import Control.Monad.ST
import qualified Data.Array.Unboxed as UB
import Data.Array.ST
import Data.Array
import Data.Char
class IOtyp a where scan' :: String -> a; show' :: a -> String
instance IOtyp Int where scan' = read; show' = show
instance IOtyp Char where scan' (x:_) = x;show' = (:[])
instance IOtyp Float where scan' = read;show' = show
instance IOtyp Double where scan' = read;show' = show
instance IOtyp Integer where scan' = read;show' = show
instance IOtyp String where scan' = id;show' = id
instance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y
instance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z
foreign import ccall "stdio.h puts" c_puts :: CString -> IO ()
scan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'
scans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan
scanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words
scanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist
puts :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}

solve n a_ b_ = 1 : rec a_ b_ 1 1 n
    where
      rec 0 0 _ _ 0 = []
      rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)
      rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)
      rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)

main = do (n,a,b) <- scan :: IO (Int,Int,Int)
          putStrLn.unwords.map show $ solve n a b

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
import Foreign
import Foreign.C.Types
import Foreign.C.String
import Foreign.Marshal.Alloc
import Debug.Trace
import Data.List
import Control.Monad
import Control.Monad.ST
import qualified Data.Array.Unboxed as UB
import Data.Array.ST
import Data.Array
import Data.Char
class IOtyp a where scan' :: String -> a; show' :: a -> String
instance IOtyp Int where scan' = read; show' = show
instance IOtyp Char where scan' (x:_) = x;show' = (:[])
instance IOtyp Float where scan' = read;show' = show
instance IOtyp Double where scan' = read;show' = show
instance IOtyp Integer where scan' = read;show' = show
instance IOtyp String where scan' = id;show' = id
instance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y
instance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z
foreign import ccall "stdio.h puts" c_puts :: CString -> IO ()
scan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'
scans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan
scanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words
scanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist
puts :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}

solve n a_ b_ = rec (a_+1) (b_+1) 0 0 n
    where
      rec 0 0 _ _ 0 = []
      rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)
      rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)
      rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)

main = do (n,a,b) <- scan :: IO (Int,Int,Int)
          putStrLn.unwords.map show $ solve n a b

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
import Foreign
import Foreign.C.Types
import Foreign.C.String
import Foreign.Marshal.Alloc
import Debug.Trace
import Data.List
import Control.Monad
import Control.Monad.ST
import qualified Data.Array.Unboxed as UB
import Data.Array.ST
import Data.Array
import Data.Char
class IOtyp a where scan' :: String -> a; show' :: a -> String
instance IOtyp Int where scan' = read; show' = show
instance IOtyp Char where scan' (x:_) = x;show' = (:[])
instance IOtyp Float where scan' = read;show' = show
instance IOtyp Double where scan' = read;show' = show
instance IOtyp Integer where scan' = read;show' = show
instance IOtyp String where scan' = id;show' = id
instance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y
instance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z
foreign import ccall "stdio.h puts" c_puts :: CString -> IO ()
scan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'
scans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan
scanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words
scanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist
puts :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}

solve n a b | n<=(a+1) = [-1]
solve n a 0 = take n (2:[2..(a+2)]++[1,1..])
solve n a_ b_ = rec a_ (b_+1) 0 0 n
    where
      rec 0 0 _ _ 0 = []
      rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)
      rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)
      rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)

main = do (n,a,b) <- scan :: IO (Int,Int,Int)
          putStrLn.unwords.map show $ solve n a b

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
import Foreign
import Foreign.C.Types
import Foreign.C.String
import Foreign.Marshal.Alloc
import Debug.Trace
import Data.List
import Control.Monad
import Control.Monad.ST
import qualified Data.Array.Unboxed as UB
import Data.Array.ST
import Data.Array
import Data.Char
class IOtyp a where scan' :: String -> a; show' :: a -> String
instance IOtyp Int where scan' = read; show' = show
instance IOtyp Char where scan' (x:_) = x;show' = (:[])
instance IOtyp Float where scan' = read;show' = show
instance IOtyp Double where scan' = read;show' = show
instance IOtyp Integer where scan' = read;show' = show
instance IOtyp String where scan' = id;show' = id
instance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y
instance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z
foreign import ccall "stdio.h puts" c_puts :: CString -> IO ()
scan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'
scans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan
scanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words
scanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist
puts :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}

solve n a_ 0 = take n ([2..(a_+2)]++[1,1..])

solve n a_ b_ = rec a_ (b_+1) 0 0 n
    where
      rec 0 0 _ _ 0 = []
      rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)
      rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)
      rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)

main = do (n,a,b) <- scan :: IO (Int,Int,Int)
          putStrLn.unwords.map show $ solve n a b

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
import Foreign
import Foreign.C.Types
import Foreign.C.String
import Foreign.Marshal.Alloc
import Debug.Trace
import Data.List
import Control.Monad
import Control.Monad.ST
import qualified Data.Array.Unboxed as UB
import Data.Array.ST
import Data.Array
import Data.Char
class IOtyp a where scan' :: String -> a; show' :: a -> String
instance IOtyp Int where scan' = read; show' = show
instance IOtyp Char where scan' (x:_) = x;show' = (:[])
instance IOtyp Float where scan' = read;show' = show
instance IOtyp Double where scan' = read;show' = show
instance IOtyp Integer where scan' = read;show' = show
instance IOtyp String where scan' = id;show' = id
instance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y
instance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z
foreign import ccall "stdio.h puts" c_puts :: CString -> IO ()
scan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'
scans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan
scanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words
scanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist
puts :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}

solve n a_ b_ = rec a_ b_ 0 0 n
    where
      rec 0 0 _ _ 0 = []
      rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)
      rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)
      rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)

main = do (n,a,b) <- scan :: IO (Int,Int,Int)
          putStrLn.unwords.map show $ solve n a b

import List
g(_,a)[x,y]=[y,a:x]
p x=[[length x],x]
main=interact$unlines.map(unwords.map show).(>>=p).foldr g[[],[]].sort.(`zip`[1..]).map((+0).read).tail.words

s[n,a,b]|a+b<n=take n$scanl(flip($))1$replicate b(*2)++replicate a(+1)++repeat(\_->1)|1>0=[-1]
main=interact$unwords.map show.s.map read.words

s[n,a,b]|a+b<n=take n$scanl(flip($))1$replicate b(*2)++replicate 2(+1)++repeat(\_->1)|1>0=[-1]
main=interact$unwords.map show.s.map read.words


Haha, try to solve this, SelectorUnlimited!— antontrygubO_oYour friends Alice and Bob practice fortune telling.Fortune telling is performed as follows. There is a well-known array $$$a$$$ of $$$n$$$ non-negative integers indexed from $$$1$$$ to $$$n$$$. The tellee starts with some non-negative number $$$d$$$ and performs one of the two operations for each $$$i = 1, 2, \ldots, n$$$, in the increasing order of $$$i$$$. The possible operations are: replace their current number $$$d$$$ with $$$d + a_i$$$ replace their current number $$$d$$$ with $$$d \oplus a_i$$$ (hereinafter $$$\oplus$$$ denotes the bitwise XOR operation)Notice that the chosen operation may be different for different $$$i$$$ and for different tellees.One time, Alice decided to start with $$$d = x$$$ and Bob started with $$$d = x + 3$$$. Each of them performed fortune telling and got a particular number in the end. Notice that the friends chose operations independently of each other, that is, they could apply different operations for the same $$$i$$$.You learnt that either Alice or Bob ended up with number $$$y$$$ in the end, but you don't know whose of the two it was. Given the numbers Alice and Bob started with and $$$y$$$, find out who (Alice or Bob) could get the number $$$y$$$ after performing the operations. It is guaranteed that on the jury tests, exactly one of your friends could have actually gotten that number.HacksYou cannot make hacks in this problem.

On the first line of the input, you are given one number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The following $$$2 \cdot t$$$ lines contain test cases. The first line of each test case contains three numbers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le x \le 10^9$$$, $$$0 \le y \le 10^{15}$$$) — the length of array $$$a$$$, Alice's initial number (Bob's initial number is therefore $$$x+3$$$), and the number that one of the two friends got in the end. The second line of each test case contains $$$n$$$ numbers — the array $$$a$$$ ($$$0 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print the name of the friend who could get the number $$$y$$$: "Alice" or "Bob".

NoteIn the first test case, Alice could get $$$9$$$ using the following operations: $$$7 + 2 = 9$$$.In the second test case, Alice could get $$$2$$$ using this operations: $$$(0 + 1) \oplus 3 = 2$$$.In the third test case, Bob started with $$$x+3 = 0+3=3$$$ and could get $$$1$$$ this way: $$$(((3 + 1) + 2) \oplus 3) \oplus 4 = 1$$$.

{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad

solve :: Int -> [Int] -> Int -> Bool
solve x as y = (x + y + sum as) `mod` 2 == 0

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n, x, y] <- map read . words <$> getLine
    as <- map read . words <$> getLine
    putStrLn $ if solve x as y
      then "Alice"
      else "Bob"

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

mainFun :: SP Builder
mainFun = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    n <- getInt
    x <- getInt
    y <- getInt
    a <- replicateM n getInt
    let
      aliceParity = foldl' (+) x a
    pure $ string7 $ if  even (aliceParity  - y)
      then  "Alice\n"
      else  "Bob\n"

type SP = State P.ByteString
type S = StateT P.ByteString

dropSpace :: P.ByteString -> P.ByteString
dropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough

--getNext :: Monad m => S m P.ByteString
--getNext = state $ P.span (> ' ') . dropSpace

getInt :: Monad m => S m Int
getInt = state $ fromJust . P.readInt . dropSpace

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 inp
  P.putStr $ toLazyByteString outp


You are given an array $$$a$$$ of length $$$n$$$. We define the equality of the array as the number of indices $$$1 \le i \le n - 1$$$ such that $$$a_i = a_{i + 1}$$$. We are allowed to do the following operation:  Select two integers $$$i$$$ and $$$x$$$ such that $$$1 \le i \le n - 1$$$ and $$$1 \le x \le 10^9$$$. Then, set $$$a_i$$$ and $$$a_{i + 1}$$$ to be equal to $$$x$$$. Find the minimum number of operations needed such that the equality of the array is less than or equal to $$$1$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$

For each test case, print the minimum number of operations needed.

NoteIn the first test case, we can select $$$i=2$$$ and $$$x=2$$$ to form $$$[1, 2, 2, 1, 1]$$$. Then, we can select $$$i=3$$$ and $$$x=3$$$ to form $$$[1, 2, 3, 3, 1]$$$.In the second test case, we can select $$$i=3$$$ and $$$x=100$$$ to form $$$[2, 1, 100, 100, 2]$$$.

lastIndexOfPair' :: Int -> Int -> [Int] -> Int
lastIndexOfPair' _ pos [_] = pos
lastIndexOfPair' i pos (x : xs)
 | (x == head xs) = lastIndexOfPair' (i + 1) (i + 1) xs
 | otherwise = lastIndexOfPair' (i + 1) pos xs

lastIndexOfPair :: [Int] -> Int
lastIndexOfPair a = lastIndexOfPair' 0 (-1) a

indexOfPair' :: Int -> [Int] -> Int
indexOfPair' _ [x] = -1
indexOfPair' i (x : xs)
 | (x == head xs) = i
 | otherwise = indexOfPair' (i + 1) xs

indexOfPair :: [Int] -> Int
indexOfPair a = indexOfPair' 0 a

join :: String -> [String] -> String
join _ [x] = x
join delimiter (x : xs) = x ++ delimiter ++ join delimiter xs

ans :: IO String
ans = do
 nInput <- getLine
 aInput <- getLine
 let n = read nInput :: Int
 let a = [read x :: Int | x <- words aInput]
 let pos = indexOfPair a
 let lastPos = lastIndexOfPair a
 let cnt = lastPos - pos + 1
 if (pos == -1 || cnt == 2) then do
  return "0"
 else if (cnt == 3) then do
  return "1"
 else do
  return (show (cnt - 3))

main :: IO ()
main = do
 tInput <- getLine
 let t = read tInput :: Int
 results <- sequence (replicate t ans)
 putStrLn (join "\r\n" results)

lastIndexOfPair' :: Eq t => Int -> Int -> [t] -> Int
lastIndexOfPair' _ pos [_] = pos
lastIndexOfPair' i pos (x : xs)
 | (x == head xs) = lastIndexOfPair' (i + 1) (i + 1) xs
 | otherwise = lastIndexOfPair' (i + 1) pos xs

lastIndexOfPair :: Eq t => [t] -> Int
lastIndexOfPair a = lastIndexOfPair' 0 (-1) a

indexOfPair' :: Eq t => Int -> [t] -> Int
indexOfPair' _ [x] = -1
indexOfPair' i (x : xs)
 | (x == head xs) = i
 | otherwise = indexOfPair' (i + 1) xs

indexOfPair :: Eq t => [t] -> Int
indexOfPair a = indexOfPair' 0 a

join :: String -> [String] -> String
join _ [x] = x
join delimiter (x : xs) = x ++ delimiter ++ join delimiter xs

ans :: IO String
ans = do
 nInput <- getLine
 aInput <- getLine
 let n = read nInput :: Int
 let a = [read x :: Int | x <- words aInput]
 let pos = indexOfPair a
 let lastPos = lastIndexOfPair a
 let cnt = lastPos - pos + 1
 if (pos == -1 || cnt == 2) then do
  return "0"
 else if (cnt == 3) then do
  return "1"
 else do
  return (show (cnt - 3))

main :: IO ()
main = do
 tInput <- getLine
 let t = read tInput :: Int
 results <- sequence (replicate t ans)
 putStrLn (join "\r\n" results)