Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the n drinks and mixed them. Then he wondered, how much orange juice the cocktail has.Find the volume fraction of orange juice in the final drink.

The first input line contains a single integer n (1 ≤ n ≤ 100) — the number of orange-containing drinks in Vasya's fridge. The second line contains n integers pi (0 ≤ pi ≤ 100) — the volume fraction of orange juice in the i-th drink, in percent. The numbers are separated by a space.

Print the volume fraction in percent of orange juice in Vasya's cocktail. The answer will be considered correct if the absolute or relative error does not exceed 10  - 4.

NoteNote to the first sample: let's assume that Vasya takes x milliliters of each drink from the fridge. Then the volume of pure juice in the cocktail will equal  milliliters. The total cocktail's volume equals 3·x milliliters, so the volume fraction of the juice in the cocktail equals , that is, 66.(6) percent.

import Control.Monad

main :: IO ()
main = do
  _ <- getLine
  percentages <- fmap (map read.words) getLine
  let perc_f = map fromIntegral percentages
  print((fromIntegral (sum perc_f)) / (fromIntegral (length perc_f)))

module Main (main)
    where

import Control.Monad (replicateM)

main :: IO ()
main = print . solve . map (map read . words) =<< replicateM 2 getLine
    where solve [[n], xs] = sum xs / n

-- the haskell wiki is amazing!!!
-- https://wiki.haskell.org/Generic_number_type
-- https://wiki.haskell.org/Converting_numbers

-- you have to convert the integers to type Fractional!!!!!!
-- at least this is the way that i found to make it work!!!!

conv lst uu
  | (null lst) = uu
  | otherwise = conv (tail lst) (uu ++ [(read (head lst))::Int])

avg lst sum
  | (null lst) = sum
  | otherwise = avg (tail lst) (sum + (head lst))

main = do
  ww <- getLine
  ff <- getLine
  let aa = conv (words ff) []
      ans = avg aa 0

  putStrLn (show ( realToFrac ans / realToFrac (length aa)))

main :: IO ()
main = do
    n <- readLn :: IO Float
    input <- getLine
    let args = map (\x -> read x :: Float) $ words input
    print $ (sum args)/n

main = do
    getLine
    ps <- fmap (map read . words) getLine
    print $ (fromIntegral $ sum ps) / (fromIntegral $ length ps)

main = do
  getLine
  xs <- fmap (map read . words) getLine
  print $ (sum xs) / (fromIntegral $ length xs)

import Data.List
import qualified Data.Map as M
(|>) x f = f x

main = interact solve

solve contents = let
  ls = contents |> lines
  sz = ls |> (!! 0) |> read :: Int
  portions = ls |> (!! 1) |> words |> map read :: [Int]
  in solve' portions sz |> show

solve' portions sz = portions |> sum |> fromIntegral |> (/ (fromIntegral sz))

main = do
    auxN <- getLine
    let n = read auxN :: Double
    auxP <- getLine
    let sumP = read (show (sum (map read $ words auxP :: [Int]))) :: Double
    putStrLn (show (sumP/n))

promedio :: [Double] -> Double
promedio l = sum l / (fromIntegral $ length l)

main = do
    header <- getLine
    numbers <- fmap words getLine
    print $ promedio $ f numbers
        where
            f l = map read l

promedio :: [Double] -> Double
promedio l = (foldr (+) 0 l) / (fromIntegral $ length l)

main = do
    header <- getLine
    numbers <- fmap words getLine
    print $ promedio $ f numbers
        where
            f l = map read l

import Data.List
import Data.Maybe
import Data.Char
import Data.Function
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve.concat.map (map read.words).take 2. lines
solve :: [Integer]->String
solve (x:xs) =  show $ (/fromIntegral x) $ fromIntegral $ sum xs

import Data.List
main=do
	a<-getLine
	t<-fmap (map read.words) getLine
	print $ sum t / genericLength t

solve :: Int -> [Double] -> Double
solve n xs  =  sum xs / (fromIntegral n)

main :: IO ()
main  =  do
    n <- readLn
    xs  <-  getLine >>= return . map read . words
    print $ solve n xs

import Control.Monad

main = readInput >>= putStrLn . show . (\(n, ps) -> sum ps / n)

readInput :: IO (Double, [Double])
readInput = liftM2 toTuple getLine getLine
  where toTuple a b = (read a, map read $ words b)

import Text.Printf
import Data.List
import Data.Functor
import Control.Applicative
import Prelude
import Control.Monad
import Data.Maybe
import Data.Function
import Data.Array
import qualified Data.ByteString.Char8 as B8
import Data.Foldable (foldr')

readInt :: String -> Int
readInt = Prelude.read

solve :: Int -> [Double] -> Double
solve n arr = sum arr / fromIntegral n

main :: IO ()
main = do
    n <- readInt <$> getLine
    arr <- (map (fromIntegral . readInt) . words) <$> getLine
    let answer = solve n arr
    printf "%.5f\n" answer

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

main=do
     n<-  read <$>  getLine::IO Int
     q<-  sum <$> map read <$> words <$>getLine ::IO Int
     print $ (fromIntegral q)/ (fromIntegral n)

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

solve :: [Double] -> Double
solve (n:ps) = sum ps / n
solve _ = undefined

main=getContents>>=print.e.map read.words
e(n:s)=sum s/n

main=getContents>>=print.solve.map read.words
solve(n:s)=sum s/n

main = do
  n <- readLn
  ps <- fmap (map read . words) getLine
  print (sum ps / n)

solve :: [Int] -> Double
solve ps = fromIntegral (sum ps) / fromIntegral (length ps * 100) * 100

main = do
  getLine -- n
  ps <- fmap (map read . words) getLine
  print $ solve ps

main = do
    n <- fmap read getLine
    p <- fmap (map read . words) getLine
    print $ sum p / n

-- Vicfred
-- https://codeforces.com/problemset/problem/200/B

main :: IO ()
main = do
    n <- readLn :: IO Double
    a <- getLine >>= return . map read . words :: IO [Double]
    print (sum a / n)

import Control.Applicative

main = do
  n <- readLn
  x <- sum.map read.words <$> getLine
  print $ x/n

main = do
    x <- getLine
    items <- map parse . words <$> getLine
    print $ (foldl (+) 0.0 items) / (read x) * 100

parse :: String -> Double
parse x = y / 100
    where y = read x :: Double

calc xs = (sum xs / fromIntegral (100 * length xs)) * 100

main = do s <- getLine
          t <- getLine
          putStrLn $ show $ calc $ map (\x -> read x :: Double) $ words t

calc xs = (sum xs / fromIntegral (100 * length xs)) * 100

main = do s <- getLine
          t <- getLine
          putStrLn $ show $ calc $ map (\x -> read x :: Float) $ words t

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

myprint x1 = putStrLn $ intercalate " " $ map show x1

main= do
	n<- read <$> getLine ::IO Double
	s<- map (fst.fromJust.C.readInteger) . C.words <$> C.getLine ::IO [Integer]
	let ss = sum s
	print $ (fromIntegral ss) / n

main = do
  n <- readLn :: IO Double
  a <- getLine >>= return. map read. words :: IO [Double]
  print (sum a / n)

main :: IO ()
main = do
    n <- toRational . (read :: String -> Int) <$> getLine
    print =<< (fromRational :: Rational -> Double) . (* 100) . (/ n) . sum . map ((/ 100) . toRational . (read :: String -> Int)) . words <$> getLine

--ghc 7.10

average :: (Fractional a) => [a] -> a
average a = (sum a) / (fromIntegral (length a))

main = do
    nStr <- getLine
    aStr <- getLine
    let a = map read . words $ aStr :: [Double]
    print $ average a

main=print.slv.map read.words =<< getContents
slv (n:ps) = (sum.take (floor n) $ ps)/n

main = interact $ show.f.map read.words.last.lines
f xs = (*100.0).(/(fromIntegral.length $ xs)).sum.map (*0.01) $ xs

{-# OPTIONS_GHC -O2 -optc-O2 #-}

import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC

solve :: Int -> [Int] -> Float
solve n x = sum (map fromIntegral x) / fromIntegral n

main =
  do all <- BS.getContents
     let Just (n, r1) = readInt all
     let (x, _)  = readMany readInt r1
     print (solve n x)
  where readInt s = BSC.readInt (BSC.dropWhile isSpace s)
        readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)
        readMany readf s = case readf s of
          Just (x, r) -> let (xs, t) = readMany readf r
                         in  (x : xs, t)
          Nothing     -> ([], s)

main :: IO ()
main = do
    n <- toRational . (read :: String -> Int) <$> getLine
    print =<< (fromRational :: Rational -> Double) . (/ n) . sum . map ((/ 100) . toRational . (read :: String -> Int)) . words <$> getLine


All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — a coordinate on the Ox axis. No two cities are located at a single point.Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in).Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city.For each city calculate two values mini and maxi, where mini is the minimum cost of sending a letter from the i-th city to some other city, and maxi is the the maximum cost of sending a letter from the i-th city to some other city

The first line of the input contains integer n (2 ≤ n ≤ 105) — the number of cities in Lineland. The second line contains the sequence of n distinct integers x1, x2, ..., xn ( - 109 ≤ xi ≤ 109), where xi is the x-coordinate of the i-th city. All the xi's are distinct and follow in ascending order.

Print n lines, the i-th line must contain two integers mini, maxi, separated by a space, where mini is the minimum cost of sending a letter from the i-th city, and maxi is the maximum cost of sending a letter from the i-th city.

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

solve :: [Int] -> [[Int]]
solve (n:x) =
    let   x1 = head x
          xn = last x
    in    solve' x1 xn x 0 True
    where solve' :: Int -> Int -> [Int] -> Int -> Bool -> [[Int]]
          solve' x1 xn (x:xs) _    True = ([(head xs) - x, xn - x]:(solve' x1 xn xs x False))
          solve' x1 xn [x]    last _    = [[(x - last), x - x1]]
          solve' x1 xn (x:xs) last _    = ([(min (x - last) ((head xs) - x)), (max (x - x1) (xn - x))]:(solve' x1 xn xs x False))

output :: [[Int]] -> IO()
output [[a, b]] = output' [a, b]
output (x:xs)   = do output' x
                     output xs

output' :: [Int] -> IO()
output' [a, b] = putStrLn ((show a) ++ " " ++ (show b))

main = do
  n <- readLn
  xs <- fmap (map read . words) getLine

  let
    h = head xs
    l = last xs

    r = [(xs!!1 - h, l - h)] ++
        (zipWith3 f xs (tail xs) (tail $ tail xs)) ++
        [(xs!!(n-1)-xs!!(n-2), l-h)]
      where
        f a b c = (min (b-a) (c-b), max (l-b) (b-h))

  putStrLn $ unlines $ map (\(x, y) -> show x ++ " " ++ show y) r

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = getLine>>= \n-> (solve.(++) [read n].concat =<< forM [1 ..1] ( \i -> map (fst.fromJust.C.readInteger).C.words <$> C.getLine))
solve (x:xs) = let m=Map.fromList $ zip [1..x] xs in forM_ [1..x] $ \i -> putStrLn $ unwords $ map show (slv1 i m)
    where
    slv1 a m | a==1      = [m Map.! 2 - m Map.! 1, m Map.! x - m Map.! 1]
             | a==x      = [m Map.! x - m Map.! (x-1), m Map.! x - m Map.! 1]
             | otherwise = [minimum [m Map.! a - m Map.! (a-1), m  Map.! (a+1) - m Map.! a], maximum [m Map.! x - m Map.! a, m Map.! a - m Map.! 1]]

import Control.Arrow ((&&&), (***))
import Data.Functor ((<$>))

main :: IO ()
main = mapM_ (putStrLn . uncurry (++) . (show *** (' ':) . show)) =<< solve <$> (tail <$> map read <$> words <$> getContents)

solve :: [Integer] -> [(Integer, Integer)]
solve xs = zip (uncurry (zipWith min) $ (id &&& tail) $ zipWith (-) (xs ++ [10000000000]) (-10000000000 : xs)) [ max (x - head xs) (last xs - x) | x <- xs ]

import Control.Monad (forM_)
main = do
  getLine
  cs <- fmap (map read . words) getLine :: IO [Int]
  let h = head cs
      t = last cs
      toL = zipWith (-) cs (h : cs) :: [Int]
      toR = zipWith (-) (tail cs ++ [t]) cs :: [Int]
  forM_ (zip3 cs toL toR) $ \(c,l,r) ->
    putStrLn $ unwords $ map show [min' l r, max' (c-h) (t-c)]
min' 0 a = a
min' a 0 = a
min' a b = min a b
max' 0 a = a
max' a 0 = a
max' a b = max a b

main = do
    _ <- getLine
    xs <- fmap (map read . words) getLine
    let sol = solve xs
    mapM_ (putStrLn . (\(a,b) -> show a ++ " " ++ show b)) sol

solve :: [Int] -> [(Int, Int)]
solve xs@(x:y:ys) = (y-x, maxv-x) : f x (y:ys)
    where minv = head xs
          maxv = last xs
          f a (b:c:cs) = (min (b-a) (c-b), max (b-minv) (maxv-b)) : f b (c:cs)
          f a [b] = [(b-a, b-minv)]

import System.IO

solve1 :: [Int] -> [Int]
solve1 [x,y] = [ abs $ x-y ]
solve1 (x:y:z:xs) = min (abs $ x-y) (abs $ y-z) : solve1(y:z:xs)

solve2 :: [Int] -> Int -> Int -> [Int]
solve2 (x:xs) y z = max (abs $ x-y) (abs $ x-z) : solve2 xs y z

main = do
	s <- getLine
	let n = read s :: Int
	s <- getLine
	let xs = map read ( words s ) :: [Int]

	let mns = abs( head xs - (head.tail) xs ) : solve1 xs
	let mxs = solve2 xs (head xs) (last xs)

	let ans = zip (map show mns) (map show mxs)
	str_printer ans

str_printer :: [(String,String)] -> IO ()
str_printer [] = return ()
str_printer (x:xs) = do putStr $ (fst x) ++ " "; putStrLn $ snd x ; str_printer xs

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

mymax s1 s2 a = max (a-s1) (s2-a)
mymin a b c = min (b-a) (c-b)
myprint a b =   intercalate " " $ map show [a,b]

main=do
	getLine
	s<-map (fst.fromJust.C.readInt). C.words<$> C.getLine::IO [Int]
	let s1 = head s
	let s2 = last s
	let maxs = map (mymax s1 s2) s
	let mins1 =   (zipWith3 (\a b c ->mymin a b c) s (tail s) (tail (tail s)))
	let mins2 = ((head (tail s))-(head s)): mins1
	let mins = mins2 ++[ last s- (last (init s))]
	putStrLn $ intercalate "\n" $ zipWith (myprint) mins maxs

module Main where

import Control.Applicative

solve :: [Int] -> Int -> Int -> [(Int, Int)]
solve (x' : x : [x'']) a b = [minMax x x' x'' a b]
solve (x' : x : x'' : xs) a b =
    minMax x x' x'' a b : solve (x : x'' : xs) a b

minMax :: Int -> Int -> Int -> Int -> Int -> (Int, Int)
minMax x x' x'' a b =
    let min' = min (dist x x') (dist x x'')
        max' = max (dist x a) (dist x b)
     in (min', max')

edgeHead :: [Int] -> (Int, Int)
edgeHead xs@(x:x':_) =
    let min' = dist x x'
        max' = dist (head xs) (last xs)
     in (min', max')

edgeTail :: [Int] -> (Int, Int)
edgeTail xs =
    let min' = dist (last xs) (last (init xs))
        max' = dist (head xs) (last xs)
     in (min', max')

dist :: Int -> Int -> Int
dist a b
    | a <= 0 && b <= 0 = abs (abs b - abs a)
    | a >= 0 && b <= 0 = a + abs b
    | a <= 0 && b >= 0 = b + abs a
    | a >= 0 && b >= 0 = abs (b - a)

showTuple :: (Int, Int) -> String
showTuple (a, b) = show a ++ " " ++ show b

main :: IO ()
main = do
    _ <- getLine
    xs <- (map (\s -> read s::Int) . words) <$> getLine
    if length xs == 2
       then do
            putStrLn $ showTuple $ edgeHead xs
            putStrLn $ showTuple $ edgeTail xs
       else do
            putStrLn $ showTuple $ edgeHead xs
            mapM_ (putStrLn . showTuple) (solve xs (head xs) (last xs))
            putStrLn $ showTuple $ edgeTail xs

import Data.Int (Int64)

process :: [Int64] -> [(Int64,Int64)]
process xs = zip dmins dmaxs
    where
        cmin = head xs
        cmax = last xs
        dl = zipWith (-) xs (2*cmin-cmax:xs)
        dr = zipWith (-) (tail xs ++ [2*cmax-cmin]) xs
        dmins = zipWith min dl dr
        cmid = (cmin + cmax) `div` 2
        dmaxs = map (\x -> if x <= cmid then cmax-x else x-cmin) xs

readInt :: String -> Int64
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    xs <- fmap (map readInt.words) getLine
    mapM_ (\(l,r) -> putStrLn (show l ++ " " ++ show r)) $ process xs

import Data.List
import Data.Int

main :: IO ()
main = interact $ showMatrix . solve . getList

getList :: (Read a) => String -> [a]
getList = tail . fmap read . words

showMatrix :: (Show a) => [[a]] -> String
showMatrix = unlines . fmap (unwords . fmap show)

solve :: [Int64] -> [[Int64]]
solve xs = transpose [minList, maxList]
    where minList = zipWith3 (\a b c -> min (b - a) (c - b))
                        (-3 * 10 ^ (9::Int64) : xs) xs (tail xs ++ [3*10^(9::Int64)])
          maxList = fmap (\x -> max (lst - x) (x - frst)) xs
            where frst = head xs
                  lst = last xs

import Control.Arrow ((&&&), (***))
import Data.Functor ((<$>))

main :: IO ()
main = mapM_ (putStrLn . uncurry (++) . (show *** (' ':) . show)) =<< solve <$> (tail <$> map read <$> words <$> getContents)

solve :: [Integer] -> [(Integer, Integer)]
solve xs = zip (uncurry (zipWith min) $ (id &&& tail) $ zipWith (-) (xs ++ [last xs + abs (head xs)]) ((head xs - abs (last xs)) : xs)) [ max (x - head xs) (last xs - x) | x <- xs ]

import Control.Arrow ((&&&), (***))
import Data.Functor ((<$>))

main :: IO ()
main = mapM_ (putStrLn . uncurry (++) . (show *** (' ':) . show)) =<< solve <$> (tail <$> map read <$> words <$> getContents)

solve :: [Int] -> [(Int, Int)]
solve xs = zip (uncurry (zipWith min) $ (id &&& tail) $ zipWith (-) (xs ++ [maxBound]) (minBound : xs)) [ max (x - head xs) (last xs - x) | x <- xs ]

import Data.Int (Int64)

process :: [Int64] -> [(Int64,Int64)]
process xs = zip dmins dmaxs
    where
        dl = zipWith (-) xs (minBound:xs)
        dr = zipWith (-) (tail xs ++ [maxBound]) xs
        dmins = zipWith min dl dr
        cmin = head xs
        cmax = last xs
        cmid = (cmin + cmax) `div` 2
        dmaxs = map (\x -> if x <= cmid then cmax-x else x-cmin) xs

readInt :: String -> Int64
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    xs <- fmap (map readInt.words) getLine
    mapM_ (\(l,r) -> putStrLn (show l ++ " " ++ show r)) $ process xs

process :: [Int] -> [(Int,Int)]
process xs = zip dmins dmaxs
    where
        dl = zipWith (-) xs (minBound:xs)
        dr = zipWith (-) (tail xs ++ [maxBound]) xs
        dmins = zipWith min dl dr
        cmin = head xs
        cmax = last xs
        cmid = (cmin + cmax) `div` 2
        dmaxs = map (\x -> if x <= cmid then cmax-x else x-cmin) xs

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    xs <- fmap (map readInt.words) getLine
    mapM_ (\(l,r) -> putStrLn (show l ++ " " ++ show r)) $ process xs

import Data.List

main :: IO ()
main = interact $ showMatrix . solve . getList

getList :: (Read a) => String -> [a]
getList = tail . fmap read . words

showMatrix :: (Show a) => [[a]] -> String
showMatrix = unlines . fmap (unwords . fmap show)

solve :: [Int] -> [[Int]]
solve xs = transpose [minList, maxList]
    where minList = zipWith3 (\a b c -> min (b - a) (c - b)) (minBound : xs) xs (tail xs ++ [maxBound])
          maxList = fmap (\x -> max (lst - x) (x - frst)) xs
            where frst = head xs
                  lst = last xs

import Data.List
import Data.Int

main :: IO ()
main = interact $ showMatrix . solve . getList

getList :: (Read a) => String -> [a]
getList = tail . fmap read . words

showMatrix :: (Show a) => [[a]] -> String
showMatrix = unlines . fmap (unwords . fmap show)

solve :: [Int64] -> [[Int64]]
solve xs = transpose [minList, maxList]
    where minList = zipWith3 (\a b c -> min (b - a) (c - b)) (minBound : xs) xs (tail xs ++ [maxBound])
          maxList = fmap (\x -> max (lst - x) (x - frst)) xs
            where frst = head xs
                  lst = last xs


Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions:   climb one area up;  climb one area down;  jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question.

The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous.

Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes).

NoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon.

{-# LANGUAGE BangPatterns #-}
import qualified Data.ByteString.Char8 as B
import qualified Data.IntSet as S
import Control.Applicative ((<$>))
import Data.Sequence as Seq ((|>),ViewL(..),viewl,singleton,length)

getTwoLines = sequence [B.getLine,B.getLine]

main = do
  [h,k] <- map read . words <$> getLine :: IO [Int]
  xs <- getTwoLines
  let (f,valid,q,vs) = (done h, validNext xs h k
                       ,singleton ((0,0),0),S.empty)
      cst = bfs f valid q vs :: Int
  putStrLn $ if blocked h k xs || cst > h then "NO" else "YES"

blocked h k b = cnt 0 0 == k
  where cnt i c
          | i == h || c == k = c
          | all (=='X') [b?(0,i),b?(1,i)] = cnt (i+1) (c+1)
          | otherwise = cnt (i+1) 0

[b1,_] ? (0,j) = B.index b1 j
[_,b2] ? (1,j) = B.index b2 j

validNext b h k vs ((i,j),t) = filter valid next
    where next = zip [(1-i,j+k),(i,j+1), (i,j-1)] $ repeat (t+1)
          valid ((x,y),iter) =
            iter <= y && (not $ visited vs (x,y)) && (y >= h || b?(x,y) /= 'X')

done h ((_,j),_) = j >= h

visited vs (i,j) = S.member (i*100000+j) vs
mark vs (i,j) = S.insert (i*100000+j) vs

bfs done next q vs =
  case viewl q of
    a@((i,j),_) :< qs ->
      if reallyDone then 0 else bfs done next nq $ mark vs (i,j)
      where nxt= if visited vs (i,j) then [] else next vs a
            reallyDone = done a || any done nxt
            nq = foldl (|>) qs nxt
    EmptyL  -> maxBound

{-# LANGUAGE BangPatterns #-}

import Data.Array.ST
import Data.Array.Unboxed
import Data.List
import Control.Applicative
import Control.Monad

main = do
  [n,k] <- map read.words <$> getLine
  arr <- listArray ((0,0),(1,n-1)).concat.lines <$> getContents
  putStrLn $ solve n k arr

solve :: Int -> Int -> UArray (Int,Int) Char -> String
solve n k arr = bfs 0 [(0,0)] visited0
   where
     visited0 = listArray ((0,0),(1,n-1)) $ True : repeat False
     bfs !water xs visited
       | null next = "NO"
       | any isGoal next = "YES"
       | otherwise = bfs (water+1) next (update next visited)
      where
        isGoal (x,y) = y>=n-1
        next = nub $ xs >>= childs
        jump (0,y) = (1,y+k)
        jump (1,y) = (0,y+k)
        childs (x0,y0) = do
          (x,y) <- [(x0,y0+1),(x0,y0-1),jump(x0,y0)]
          guard $ water < y
          if y > n-1
             then return (x,y)
             else do
               guard $ not (visited!(x,y)) && arr!(x,y) == '-'
               return (x,y)

update :: [(Int,Int)] -> UArray (Int,Int) Bool -> UArray (Int,Int) Bool
update [] arr = arr
update xs arr = runSTUArray $ do
  a <- unsafeThaw arr
  go a xs
  return a
   where
     go a [] = return ()
     go a (x:xs) = do
       writeArray a x True
       go a xs


During the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows:   The cell with coordinates $$$(x, y)$$$ is at the intersection of $$$x$$$-th row and $$$y$$$-th column. Upper left cell $$$(1,1)$$$ contains an integer $$$1$$$.The developers of the SUM function don't sleep either. Because of the boredom, they teamed up with the developers of the RAND function, so they added the ability to calculate the sum on an arbitrary path from one cell to another, moving down or right. Formally, from the cell $$$(x,y)$$$ in one step you can move to the cell $$$(x+1, y)$$$ or $$$(x, y+1)$$$. After another Dinwows update, Levian started to study "Celex-2021" (because he wants to be an accountant!). After filling in the table with the GAZ-GIZ function, he asked you to calculate the quantity of possible different amounts on the path from a given cell $$$(x_1, y_1)$$$ to another given cell $$$(x_2, y_2$$$), if you can only move one cell down or right.Formally, consider all the paths from the cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$ such that each next cell in the path is located either to the down or to the right of the previous one. Calculate the number of different sums of elements for all such paths.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 57179$$$) — the number of test cases. Each of the following $$$t$$$ lines contains four natural numbers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \le x_1 \le x_2 \le 10^9$$$, $$$1 \le y_1 \le y_2 \le 10^9$$$) — coordinates of the start and the end cells.

For each test case, in a separate line, print the number of possible different sums on the way from the start cell to the end cell.

NoteIn the first test case there are two possible sums: $$$1+2+5=8$$$ and $$$1+3+5=9$$$.

import           Control.Arrow
import           Control.Monad.State
import           Data.Array
import           Data.Bits
import           Data.Bool
import qualified Data.ByteString.Lazy.Char8 as C
import           Data.Char
import           Data.Function
import           Data.List
import           Data.Map                   (Map, (!))
import qualified Data.Map                   as M
import           Data.Maybe
import           Data.Ord
import           Data.Ratio
import           Data.Set                   (Set)
import qualified Data.Set                   as S
import           Text.Printf

-- import Text.Parsec
-- import Text.Parsec.Expr
-- import Text.Parsec.Language (emptyDef)
-- import Text.Parsec.String
-- import qualified Text.Parsec.Token as T

infixl 0 >$>
(>$>) = flip ($)

main = C.interact $
  C.lines >>> drop 1 >>> map (C.words >>> map readInt >>> solve >>> show >>> C.pack) >>> C.unlines

readInt = C.readInt >>> fromJust >>> fst

solve :: [Int] -> Integer
solve [x1,y1,x2,y2] = n*m + 1
  where
    n = fromIntegral (x2-x1)
    m = fromIntegral (y2-y1)

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

main = getLine >>= flip replicateM_ test . read

test = do
    (x1:y1:x2:y2:_) <- map read . words <$> getLine
    print $ (x2 - x1) * (y2 - y1) + 1

solve :: [[Integer]] -> [Integer]
solve [] = []
solve (x:xs) = (count x) : (solve xs)

count :: [Integer] -> Integer
count [x1,y1,x2,y2]
	| x1 > x2 		= 		0
	| y1 > y2 		= 		0
	| x1 == x2		= 		1
	| y1 == y2 		= 		1
	| otherwise		= 		a * b - (a + b - 1) + 1
	where
		a = x2 - x1 + 1
		b = y2 - y1 + 1

main = do
	t' <- getLine
	let t = read t' :: Int
	fin <- getContents
	let input = map (map read) (map words (take t (lines fin))) :: [[Integer]]
	let result = solve input
	mapM print result

import Data.List

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

split = _split [] ""

main = do
  input <- getContents
  let (_:tokens) = split input
      vals = read <$> tokens :: [Integer]
      res = unfoldr (\ls ->
        case ls of
          []  -> Nothing
          x1:y1:x2:y2:rest  ->
            let area = (x2-x1) * (y2-y1)
            in Just (1 + area, rest)
        ) vals
  sequence_ $ putStrLn . show <$> res

import Data.List (sort, foldl')
import Data.Traversable (for)
import Control.Applicative (liftA2)

solveCase :: ((Integer, Integer), (Integer, Integer)) -> Integer
solveCase ((p,q), (x,y)) = 1 + (x-p)*(y-q)

main :: IO ()
main = do
  t <- read <$> getLine :: IO Int
  _ <- for [1..t] $ \_ -> do
    nums <- (map read . words) <$> getLine :: IO [Integer]
    case  nums  of
      [p,q,x,y] -> print (solveCase ((p,q),(x,y)))
      _ -> putStrLn "bad input format"
  return ()

type Point = (Integer, Integer)

solve :: Integer -> Integer -> Integer -> Integer -> Integer
solve x1 y1 x2 y2 = 1 + ((x2-x1)*(y2-y1))

main :: IO ()
main = interact (unlines . map parse . tail . lines)

parse :: String -> String
parse input = show $ solve x1 y1 x2 y2
  where [x1, y1, x2, y2] = map (\x -> read x :: Integer) $ words input

import           Control.Arrow
import           Control.Monad.State
import           Data.Array
import           Data.Bits
import           Data.Bool
import qualified Data.ByteString.Lazy.Char8 as C
import           Data.Char
import           Data.Function
import           Data.List
import           Data.Map                   (Map, (!))
import qualified Data.Map                   as M
import           Data.Maybe
import           Data.Ord
import           Data.Ratio
import           Data.Set                   (Set)
import qualified Data.Set                   as S
import           Text.Printf

-- import Text.Parsec
-- import Text.Parsec.Expr
-- import Text.Parsec.Language (emptyDef)
-- import Text.Parsec.String
-- import qualified Text.Parsec.Token as T

infixl 0 >$>
(>$>) = flip ($)

main = C.interact $
  C.lines >>> drop 1 >>> map (C.words >>> map readInt >>> solve >>> show >>> C.pack) >>> C.unlines

readInt = C.readInt >>> fromJust >>> fst

solve [x1,y1,x2,y2] = n*m + 1
  where
    n = (x2-x1)
    m = (y2-y1)

solve :: [[Int]] -> [Int]
solve [] = []
solve (x:xs) = (count x) : (solve xs)

count :: [Int] -> Int
count [x1,y1,x2,y2]
	| x1 > x2 		= 		0
	| y1 > y2 		= 		0
	| x1 == x2		= 		1
	| y1 == y2 		= 		1
	| otherwise		= 		max (x2 - x1) (y2 - y1) + 1

main = do
	t' <- getLine
	let t = read t' :: Int
	fin <- getContents
	let input = map (map read) (map words (take t (lines fin))) :: [[Int]]
	let result = solve input
	mapM print result

solve :: [[Int]] -> [Int]
solve [] = []
solve (x:xs) = (count x) : (solve xs)

count :: [Int] -> Int
count [x1,y1,x2,y2]
	| x1 > x2 		= 		0
	| y1 > y2 		= 		0
	| x1 == x2		= 		1
	| y1 == y2 		= 		1
	| otherwise		= 		a * b - (a + b - 1) + 1
	where
		a = x2 - x1 + 1
		b = y2 - y1 + 1

main = do
	t' <- getLine
	let t = read t' :: Int
	fin <- getContents
	let input = map (map read) (map words (take t (lines fin))) :: [[Int]]
	let result = solve input
	mapM print result


You're given an array $$$a_1, \ldots, a_n$$$ of $$$n$$$ non-negative integers.Let's call it sharpened if and only if there exists an integer $$$1 \le k \le n$$$ such that $$$a_1 < a_2 < \ldots < a_k$$$ and $$$a_k > a_{k+1} > \ldots > a_n$$$. In particular, any strictly increasing or strictly decreasing array is sharpened. For example:  The arrays $$$[4]$$$, $$$[0, 1]$$$, $$$[12, 10, 8]$$$ and $$$[3, 11, 15, 9, 7, 4]$$$ are sharpened;  The arrays $$$[2, 8, 2, 8, 6, 5]$$$, $$$[0, 1, 1, 0]$$$ and $$$[2, 5, 6, 9, 8, 8]$$$ are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any $$$i$$$ ($$$1 \le i \le n$$$) such that $$$a_i>0$$$ and assign $$$a_i := a_i - 1$$$.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 15\ 000$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$). The second line of each test case contains a sequence of $$$n$$$ non-negative integers $$$a_1, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.

NoteIn the first and the second test case of the first test, the given array is already sharpened.In the third test case of the first test, we can transform the array into $$$[3, 11, 15, 9, 7, 4]$$$ (decrease the first element $$$97$$$ times and decrease the last element $$$4$$$ times). It is sharpened because $$$3 < 11 < 15$$$ and $$$15 > 9 > 7 > 4$$$.In the fourth test case of the first test, it's impossible to make the given array sharpened.

import Data.Ord
import Data.Int
import qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>))
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Prelude hiding (showList)
import Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if DSeq.null s then
                aux s
            else
                return $ toList s
        else
            aux $ s DSeq.|> x
    in aux DSeq.Empty

type EIO a = ExceptT String IO a

get :: Read a => EIO a
get = ExceptT $ liftM readEither getToken
gets :: EIO String
gets = ExceptT $ liftM Right getToken
puts :: String -> EIO ()
puts = lift . putStr
putsln :: String -> EIO ()
putsln = lift . putStrLn
put :: Show a => a -> EIO ()
put = putsln . show
putln :: Show a => a -> EIO ()
putln = putsln . show
showList :: Show a => [a] -> String
showList [] = []
showList (x : l) = shows x $ showChar ' ' $ showList l

main :: IO ()
main = do
    o <- runExceptT main_
    case o of
        Right () -> return ()
        Left s -> putStrLn s

main_ :: EIO ()
main_ = do
    t <- get :: EIO Int
    replicateM_ t f1

f1 :: EIO ()
f1 = do
    n <- get :: EIO Int
    as <- replicateM n get :: EIO [Int]
    if f2 as 0 n Nothing then
        putsln "Yes"
    else
        putsln "No"

f2 :: [Int] -> Int -> Int -> Maybe Int -> Bool
f2 [] i n b = True
f2 (a : rest) i n b = if (mod n 2) == 0 && i == (div n 2) - 1 then
                        if a < i then
                            False
                        else
                            f2 rest (i + 1) n $ Just a
                    else if i < (div n 2) then
                        if a < i then
                            False
                        else
                            f2 rest (i + 1) n b
                    else if (mod n 2) == 0 && i == (div n 2) then
                        if a < (n - 1 - i) then
                            False
                        else case b of
                            Nothing -> False
                            Just ap -> if (a /= (n - 1 - i) || ap /= (n - 1 - i)) then f2 rest (i + 1) n b else False
                    else
                        if a < (n - 1 - i) then
                            False
                        else
                            f2 rest (i + 1) n b


One of the Hedgehog and his friend's favorite entertainments is to take some sentence or a song and replace half of the words (sometimes even all of them) with each other's names.The friend's birthday is approaching and the Hedgehog decided to make a special present to his friend: a very long song, where his name will be repeated many times. But try as he might, he can't write a decent song!The problem is that the Hedgehog has already decided how long the resulting sentence should be (i.e. how many letters it should contain) and in which positions in the sentence the friend's name should occur, and it must not occur in any other position in the sentence. Besides, the Hedgehog decided to limit himself to using only the first K letters of an English alphabet in this sentence (so it will be not even a sentence, but one long word).The resulting problem is indeed quite complicated, that's why the Hedgehog asks you to help him and write a program that will make the desired word by the given name P, the length N of the required word, the given positions of the occurrences of the name P in the desired word and the alphabet's size K. Note that the occurrences of the name can overlap with each other.

The first line contains numbers N and K which are the length of the required string and the alphabet size accordingly. The limitations are: 1 ≤ N ≤ 100, 2 ≤ K ≤ 26. The second line contains the name P which is a non-empty string whose length does not exceed N characters. The string consists only of the first K lowercase symbols of an English alphabet. The third line contains the string of length N - length(P) + 1, consisting only of numbers zero and one. A number one in the i-th position means that an occurrence of the name P should start from i-th position of the desired word, while a zero means that there is no occurrence starting here.

Print the desired word S. If there are several answers, print any of them. If there is no solution, then print "No solution".

{-# LANGUAGE OverloadedStrings #-}

import Data.Array.IArray
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Monoid
import Control.Monad
import Debug.Trace
import Text.Printf

kmpJumpBack :: B.ByteString -> Array Int Int
kmpJumpBack str = arr
    where len    = B.length str
          arr    = listArray (0, len) $ [f i $ f'(i-1) | i <- [0..len]]
          f'     = (arr !)
          str' n = B.head $ B.drop (n-1) str
          f i k
            | i <= 1               = 0
            | str'(k+1) == str'(i) = k+1
            | k == 0               = 0
            | otherwise            = f i $ f' k

jumpTable :: B.ByteString -> Int -> Array (Int, Int) (Int, Int)
jumpTable str alph = arr
    where len    = B.length str
          arr    = listArray ((0,0), (len-1, alph-1)) $
                     [f st i | st <- [0..len-1], i <- [0..alph-1]]
          f'     = curry (arr !)
          str' n = B.head $ B.drop (n-1) str
          ch x   = chr $ ord 'a' + x
          f st i
             | str'(st+1) == ch i
                = if st + 1 == len
                     then (1, jumpBack(st+1))
                     else (0, st + 1)
             | st == 0    = (0,0)
             | otherwise  = f (jumpBack st) i

          jumpBack = (kmpJumpBack str !)

solve :: Int -> Int -> B.ByteString -> B.ByteString -> Maybe String
solve n alph str acc = f' 0 0
    where len = B.length str
          arr :: Array (Int, Int) (Maybe String)
          arr = listArray ((0,0), (n,len-1)) $
                   [f pos st | pos <- [0..n], st <- [0..len-1]]
          f'  = curry (arr !)

          acc' :: Int -> Int
          acc' pos = if pos < len then 0
                     else ord (B.head $ B.drop (pos - len) acc) - ord '0'

          jumpTable' = jumpTable str alph
          jump = curry (jumpTable'!)

          f pos st
           | pos == n   = Just []
           | otherwise  = getFirst $ mconcat [First $ tryJump i | i <- [0..alph-1]]
              where
                tryJump :: Int -> Maybe String
                tryJump i = do
                    let (a, st') = jump st i

                    guard $ a == acc'(pos+1)

                    ret <- f' (pos+1) st'
                    return $ chr (i + ord 'a'):ret

main = do
   [n, alph] <- (map read . words) `fmap` getLine
   [str]     <- B.words `fmap` B.getLine
   [acc]     <- B.words `fmap` B.getLine

   case solve n alph str acc of
      Just ans -> putStrLn ans
      Nothing  -> putStrLn "No solution"

{-# LANGUAGE OverloadedStrings #-}

import Data.Array.IArray
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Monoid
import Control.Monad
import Debug.Trace
import Text.Printf

kmpJumpBack :: B.ByteString -> Array Int Int
kmpJumpBack str = arr
    where len    = B.length str
          arr    = listArray (0, len) $ [f i $ f'(i-1) | i <- [0..len]]
          f'     = (arr !)
          str' n = B.head $ B.drop (n-1) str
          f i k
            | i <= 1               = 0
            | str'(k+1) == str'(i) = k+1
            | k == 0               = 0
            | otherwise            = f i $ f' k

solve :: Int -> Int -> B.ByteString -> B.ByteString -> Maybe String
solve n alph str acc = f' 0 0
    where len = B.length str
          arr :: Array (Int, Int) (Maybe String)
          arr = listArray ((0,0), (n,len-1)) $
                   [f pos st | pos <- [0..n], st <- [0..len-1]]
          f'  = curry (arr !)

          acc' :: Int -> Int
          acc' pos = if pos < len then 0
                     else ord (B.head $ B.drop (pos - len) acc) - ord '0'

          jumpBack = (kmpJumpBack str !)
          str' n = B.head $ B.drop (n-1) str
          ch n = chr $ ord 'a' + n

          jump st i
             | str'(st+1) == ch i
                = if st + 1 == len
                     then (1, jumpBack(st+1))
                     else (0, st + 1)
             | st == 0    = (0,0)
             | otherwise  = jump (jumpBack st) i

          f pos st
           | pos == n   = Just []
           | otherwise  = getFirst $ mconcat [First $ tryJump i | i <- [0..alph-1]]
              where
                tryJump :: Int -> Maybe String
                tryJump i = do
                    let (a, st') = jump st i

                    guard $ a == acc'(pos+1)

                    ret <- f' (pos+1) st'
                    return $ chr (i + ord 'a'):ret

main = do
   [n, alph] <- (map read . words) `fmap` getLine
   [str]     <- B.words `fmap` B.getLine
   [acc]     <- B.words `fmap` B.getLine

   case solve n alph str acc of
      Just ans -> putStrLn ans
      Nothing  -> putStrLn "No solution"

{-# LANGUAGE OverloadedStrings #-}

import Data.Array.IArray
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Monoid
import Control.Monad
import Debug.Trace
import Text.Printf

kmpJumpBack :: B.ByteString -> Array Int Int
kmpJumpBack str = arr
    where len    = B.length str
          arr    = listArray (0, len) $ [f i $ f'(i-1) | i <- [0..len]]
          f'     = (arr !)
          str' n = B.head $ B.drop (n-1) str
          f i k
            | i <= 1               = 0
            | str'(k+1) == str'(i) = k+1
            | k == 0               = 0
            | otherwise            = f i $ f' k

jumpTable :: B.ByteString -> Int -> Array (Int, Int) (Int, Int)
jumpTable str alph = arr
    where len    = B.length str
          arr    = listArray ((0,0), (len-1, alph-1)) $
                     [f st i | st <- [0..len-1], i <- [0..alph-1]]
          f'     = curry (arr !)
          str' n = B.head $ B.drop (n-1) str
          ch x   = chr $ ord 'a' + x
          f st i
             | str'(st+1) == ch i
                = if st + 1 == len
                     then (1, jumpBack(st+1))
                     else (0, st + 1)
             | st == 0    = (0,0)
             | otherwise  = f (jumpBack st) i

          jumpBack = (kmpJumpBack str !)

solve :: Int -> Int -> B.ByteString -> B.ByteString -> Maybe String
solve n alph str acc = f' 0 0
    where len = B.length str
          arr :: Array (Int, Int) (Maybe String)
          arr = listArray ((0,0), (n,len-1)) $
                   [f pos st | pos <- [0..n], st <- [0..len-1]]
          f'  = curry (arr !)

          acc' :: Int -> Int
          acc' pos = if pos < len then 0
                     else ord (B.head $ B.drop (pos - len) acc) - ord '0'

          jumpTable' = jumpTable str alph
          jump = curry (jumpTable'!)

          f pos st
           | pos == n   = Just []
           | otherwise  = getFirst $ mconcat [First $ tryJump i | i <- [0..alph-1]]
              where
                tryJump :: Int -> Maybe String
                tryJump i = do
                    let (a, st') = jump st i

                    guard $ a == acc'(pos+1)

                    ret <- f' (pos+1) st'
                    return $ chr (i + ord 'a'):ret

main = do
   [n, alph] <- (map read . words) `fmap` getLine
   str       <- B.getLine
   acc       <- B.getLine

   printf "%d %d %d %d\n" n alph (length $ B.unpack str) (length $ B.unpack acc)

   case solve n alph str acc of
      Just ans -> putStrLn ans
      Nothing  -> putStrLn "No solution"

{-# LANGUAGE OverloadedStrings #-}

import Data.Array.IArray
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Monoid
import Control.Monad
import Debug.Trace

kmpJumpBack :: B.ByteString -> Array Int Int
kmpJumpBack str = arr
    where len    = B.length str
          arr    = listArray (0, len) $ [f i $ f'(i-1) | i <- [0..len]]
          f'     = (arr !)
          str' n = B.head $ B.drop (n-1) str
          f i k
            | i <= 1               = 0
            | str'(k+1) == str'(i) = k+1
            | k == 0               = 0
            | otherwise            = f i $ f' k

jumpTable :: B.ByteString -> Int -> Array (Int, Int) (Int, Int)
jumpTable str alph = arr
    where len    = B.length str
          arr    = listArray ((0,0), (len-1, alph-1)) $
                     [f st i | st <- [0..len-1], i <- [0..alph-1]]
          f'     = curry (arr !)
          str' n = B.head $ B.drop (n-1) str
          ch x   = chr $ ord 'a' + x
          f st i
             | str'(st+1) == ch i
                = if st + 1 == len
                     then (1, jumpBack(st+1))
                     else (0, st + 1)
             | st == 0    = (0,0)
             | otherwise  = f (jumpBack st) i

          jumpBack = (kmpJumpBack str !)

solve :: Int -> Int -> B.ByteString -> B.ByteString -> Maybe String
solve n alph str acc = f' 0 0
    where len = B.length str
          arr :: Array (Int, Int) (Maybe String)
          arr = listArray ((0,0), (n,len-1)) $
                   [f pos st | pos <- [0..n], st <- [0..len-1]]
          f'  = curry (arr !)

          acc' :: Int -> Int
          acc' pos = if pos < len then 0
                     else ord (B.head $ B.drop (pos - len) acc) - ord '0'

          jumpTable' = jumpTable str alph
          jump = curry (jumpTable'!)

          f pos st
           | pos == n   = Just []
           | otherwise  = getFirst $ mconcat [First $ tryJump i | i <- [0..alph-1]]
              where
                tryJump :: Int -> Maybe String
                tryJump i = do
                    let (a, st') = jump st i

                    guard $ a == acc'(pos+1)

                    ret <- f' (pos+1) st'
                    return $ chr (i + ord 'a'):ret

main = do
   [n, alph] <- (map read . words) `fmap` getLine
   str       <- B.getLine
   acc       <- B.getLine

   case solve n alph str acc of
      Just ans -> putStrLn ans
      Nothing  -> putStrLn "No solution"


There are two infinite sources of water:  hot water of temperature $$$h$$$;  cold water of temperature $$$c$$$ ($$$c < h$$$). You perform the following procedure of alternating moves:  take one cup of the hot water and pour it into an infinitely deep barrel;  take one cup of the cold water and pour it into an infinitely deep barrel;  take one cup of the hot water $$$\dots$$$  and so on $$$\dots$$$ Note that you always start with the cup of hot water.The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.You want to achieve a temperature as close as possible to $$$t$$$. So if the temperature in the barrel is $$$t_b$$$, then the absolute difference of $$$t_b$$$ and $$$t$$$ ($$$|t_b - t|$$$) should be as small as possible.How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $$$t$$$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 3 \cdot 10^4$$$) — the number of testcases. Each of the next $$$T$$$ lines contains three integers $$$h$$$, $$$c$$$ and $$$t$$$ ($$$1 \le c < h \le 10^6$$$; $$$c \le t \le h$$$) — the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.

For each testcase print a single positive integer — the minimum number of cups required to be poured into the barrel to achieve the closest temperature to $$$t$$$.

NoteIn the first testcase the temperature after $$$2$$$ poured cups: $$$1$$$ hot and $$$1$$$ cold is exactly $$$20$$$. So that is the closest we can achieve.In the second testcase the temperature after $$$7$$$ poured cups: $$$4$$$ hot and $$$3$$$ cold is about $$$29.857$$$. Pouring more water won't get us closer to $$$t$$$ than that.In the third testcase the temperature after $$$1$$$ poured cup: $$$1$$$ hot is $$$18$$$. That's exactly equal to $$$t$$$.

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

main = getLine >>= flip replicateM_ test . read

test = do
    (h:c:t:_) <- map read . words <$> getLine
    if t == h
        then print 1
        else if t <= (c + h) `div` 2
                 then print 2
                 else do
                     let x = (t - h) `div` (c + h - 2 * t)
                     print $
                         ((+ 1) . (* 2)) $
                         minimumBy
                             (comparing (\x -> abs $ fromInteger t - (x * c + (x + 1) * h) % (2 * x + 1)))
                             [max (x - 5) 0 .. x + 5]

import Data.Int
import Data.Ratio

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

parse :: String -> (Int64, Int64, Int64)
parse s = (h, c, t)
  where
    [h, c, t] = map read . words $ s

solve :: (Int64, Int64, Int64) -> Int64
solve (h, c, t)
  | 2 * t <= h + c = 2
  | f n <= f (n + 1) = 2 * n + 1
  | otherwise = 2 * (n + 1) + 1
  where
    n = div (h - t) (2 * t - (h + c))
    f k = abs (fromIntegral t - ((k + 1) * h + k * c) % (2 * k + 1))

{-# LANGUAGE MultiWayIf #-}

import Data.List
import Data.Ratio

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

split = _split [] ""

oddRoundDown n
  | (n `mod` 2 == 0) = if n >= 2 then n - 1 else n + 1
  | otherwise = n

oddRoundUp n
  | (n `mod` 2 == 0) = n + 1
  | otherwise = n

mixTemp :: Rational -> Rational -> Integer -> Rational
mixTemp c h numCups =
  let numH = ((numCups + 1) `div` 2) % 1
      numC = (numCups `div` 2) % 1
  in (numC * c + numH * h) / (numC + numH)

main = do
  input <- getContents
  let (_:vals) = read <$> split input :: [Integer]
      res = unfoldr (\ls ->
        case ls of
          []  -> Nothing
          hInt:cInt:tgtInt:rest  -> Just (res, rest) where
            res = let
              h = hInt % 1
              c = cInt % 1
              tgt = tgtInt % 1
              avg = (c+h) / 2
              in if
              | tgt <= avg  -> 2
              | otherwise   ->
                  let diff = tgt - avg
                      exact = (h - avg) / diff
                      num = numerator exact
                      denom = denominator exact
                      near1 = oddRoundDown $ num `div` denom
                      near2 = oddRoundUp $ (num + denom - 1) `div` denom
                      temp1 = mixTemp c h near1
                      temp2 = mixTemp c h near2
                  in  if abs (temp1 - tgt) <= abs (temp2 - tgt) then near1 else near2
        ) vals
  sequence_ (putStrLn . show <$> res)

solve :: (Integer, Integer, Integer) -> Integer
solve (h, c, t)
  | 2 * t <= h + c     = 2
  | otherwise  = let
    n = 2 * t - h - c
    d = h - c
    q = quot d (2 * n)
    v1 = 2*q + 1
    v2 = v1 + 2
    in  if  (v1 + v2) * d <= v1 * v2 * 2 * n
         -- 1 / v1 - n / d <= n / d - 1 / v2
      then  v1  else  v2

parse :: String -> [(Integer, Integer, Integer)]
parse inp = [(h, c, t) | [h, c, t] <- map (map read . words) . tail $ lines inp]

main :: IO ()
main = interact (unlines . map (show . solve) . parse)

import Data.Ratio

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

parse :: String -> (Int, Int, Int)
parse s = (h, c, t)
  where
    [h, c, t] = map read . words $ s

solve :: (Int, Int, Int) -> Int
solve (h, c, t)
  | 2 * t <= h + c = 2
  | f n <= f (n + 1) = 2 * n + 1
  | otherwise = 2 * (n + 1) + 1
  where
    n = div (h - t) (2 * t - (h + c))
    f k = abs (fromIntegral t - ((k + 1) * h + k * c) % (2 * k + 1))

import Data.Ratio

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

parse :: String -> (Int, Int, Int)
parse s = (h, c, t)
  where
    [h, c, t] = map read . words $ s

solve :: (Int, Int, Int) -> Int
solve (h, c, t)
  | 2 * t <= h + c = 2
  | f n < f (n + 1) = 2 * n + 1
  | otherwise = 2 * (n + 1) + 1
  where
    n = div (h - t) (2 * t - (h + c))
    f k = abs (fromIntegral t - ((k + 1) * h + k * c) % (2 * k + 1))


You have a list of numbers from $$$1$$$ to $$$n$$$ written from left to right on the blackboard.You perform an algorithm consisting of several steps (steps are $$$1$$$-indexed). On the $$$i$$$-th step you wipe the $$$i$$$-th number (considering only remaining numbers). You wipe the whole number (not one digit).  When there are less than $$$i$$$ numbers remaining, you stop your algorithm. Now you wonder: what is the value of the $$$x$$$-th remaining number after the algorithm is stopped?

The first line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. The next $$$T$$$ lines contain queries — one per line. All queries are independent. Each line contains two space-separated integers $$$n$$$ and $$$x$$$ ($$$1 \le x < n \le 10^{9}$$$) — the length of the list and the position we wonder about. It's guaranteed that after the algorithm ends, the list will still contain at least $$$x$$$ numbers.

Print $$$T$$$ integers (one per query) — the values of the $$$x$$$-th number after performing the algorithm for the corresponding queries.

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

readInt = readLn :: IO Int
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readNInts = readInt >>= flip replicateM readInt

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

main = do
	t <- readInt
	replicateM t $ do
		[ x, n ] <- readInts
		print $ n * 2

solve :: Int -> IO ()
solve 0 = return ()
solve t = do
    line <- getLine
    let [_, b] = map (\x -> read x :: Int) $ words line
    print $ 2 * b
    solve $ t - 1

main :: IO ()
main = do
    line <- getLine
    let t = read line :: Int
    solve t

main = interact $ unlines . map (show . solve) . pairs . map read . tail . words
pairs (a:b:xs) = (a,b) : pairs xs
pairs [] = []
solve (_,x) = 2*x

import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import Data.Array
import qualified Data.Map as M

onecase = do
		[a,x]<-map read <$> words <$> getLine::IO [Int]
		print $ x+ x

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

process :: Int -> Int -> Int
process n x = 2*x

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    t <- fmap readInt getLine
    ts <- fmap (map (map readInt.words).lines) getContents
    mapM_ print $ map (\[n,x] -> process n x) ts

import Control.Monad (replicateM_)

main :: IO ()
main = do
	n <- getLine
	replicateM_ (read n) $ do
		zm <- fmap (read . head . tail . words) getLine
		print (zm*2)

import Data.Char (ord)
import Control.Monad (replicateM_)

parseInt :: String -> Int
parseInt = foldl (\acc c -> acc * 10 + ord c - 48) 0

solve :: [Int] -> Int
solve [_, x] = x * 2

main :: IO ()
main = do
  testNum <- fmap parseInt getLine
  replicateM_ testNum (print . solve . map parseInt . words =<< getLine)

main = interact $ unlines . map (show . solve) . pairs . map read . tail . words
pairs (a:b:xs) = (a,b) : pairs xs
pairs [] = []
solve (_,x) = s !! (x-1)
s = go 0 [1..] where
  go i xs | null r = xs
          | otherwise = l ++ go (i+1) (tail r)
    where (l,r) = splitAt i xs


$$$n$$$ distinct integers $$$x_1,x_2,\ldots,x_n$$$ are written on the board. Nezzar can perform the following operation multiple times.  Select two integers $$$x,y$$$ (not necessarily distinct) on the board, and write down $$$2x-y$$$. Note that you don't remove selected numbers. Now, Nezzar wonders if it is possible to have his favorite number $$$k$$$ on the board after applying above operation multiple times.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases.  The first line of each test case contains two integers $$$n,k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$-10^{18} \le k \le 10^{18}$$$). The second line of each test case contains $$$n$$$ distinct integers $$$x_1,x_2,\ldots,x_n$$$ ($$$-10^{18} \le x_i \le 10^{18}$$$). It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print "YES" on a single line if it is possible to have $$$k$$$ on the board. Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first test case, the number $$$1$$$ is already on the board.In the second test case, Nezzar could perform the following operations to write down $$$k=0$$$ on the board:   Select $$$x=3$$$ and $$$y=2$$$ and write down $$$4$$$ on the board.  Select $$$x=4$$$ and $$$y=7$$$ and write down $$$1$$$ on the board.  Select $$$x=1$$$ and $$$y=2$$$ and write down $$$0$$$ on the board. In the third test case, it is impossible to have the number $$$k = -1$$$ on the board.

import Control.Monad (replicateM_)
import Data.Functor ((<&>))

main :: IO ()
main = do
    let getList = getLine <&> words <&> map read
    [tests_n] <- getList
    replicateM_ tests_n $ do
        [n, k] <- getList
        xs <- getList
        let output = if canGetK k xs then "YES" else "NO"
        putStrLn output

canGetK :: Integral int => int -> [int] -> Bool
canGetK k [] = False
canGetK k (x:xs) = step `divides` (k - x)
    where
        relative_xs = map (subtract x) xs
        step = foldr gcd 0 relative_xs

divides :: (Integral int) => int -> int -> Bool
divides 0 x = x == 0
divides d x = mod x d == 0

module Main where

import           Control.Monad                  ( foldM
                                                , replicateM
                                                , replicateM_
                                                )
import           Data.Array                     ( listArray )
import           Data.Foldable                  ( maximumBy )
import           Data.Int                       ( Int64 )
import qualified Data.Map                      as Map

solve :: Int64 -> [Int64] -> Bool
solve _ []       = False
solve k [x     ] = k == x
solve k (x : xs) = k == x || not (null xs') && (k - x) `mod` foldl1 gcd xs' == 0 where xs' = filter (/= 0) (subtract x <$> xs)

main :: IO ()
main = readLn >>= flip replicateM_ go
  where
    go = do
        k <- (!! 1) . fmap read . words <$> getLine
        r <- solve k . fmap read . words <$> getLine
        if r then putStrLn "YES" else putStrLn "NO"

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

main :: IO ()
main = getLine >>= flip replicateM_ test . read

test :: IO ()
test = do
  [_, k] <- map read . words <$> getLine :: IO [Integer]
  xs <- map read . words <$> getLine :: IO [Integer]
  let d = foldl gcd 0 (zipWith (-) <*> tail $ sort xs)
  putStrLn $ bool "NO" "YES" $ k `mod` d == head xs `mod` d

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class

import qualified Data.ByteString.Lazy.Char8 as P

import Data.List
import Data.Int

type SIO = StateT P.ByteString IO

readLine :: SIO P.ByteString
readLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put . P.tail . snd $ P.break (== '\n') next
  pure out

readInts :: SIO [Int]
readInts = do
  currLine <- readLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

readInt64s :: SIO [Int64]
readInt64s = do
  currLine <- readLine
  pure [fromIntegral x | Just (x, _) <- P.readInteger <$> P.words currLine]

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [_n, k] <- readInt64s
    x1 : x <- readInt64s
    let
      w = foldl' gcd 0 $ map (x1 -) x
    lift . P.putStrLn . P.pack $ if  mod (k-x1) w == 0
      then  "YES"
      else  "NO"

module Main where

import           Control.Monad                  ( foldM
                                                , replicateM
                                                , replicateM_
                                                )
import           Data.Array                     ( listArray )
import           Data.Foldable                  ( maximumBy )
import qualified Data.Map                      as Map

solve :: Int -> [Int] -> Bool
solve _ []       = False
solve k [x     ] = k == x
solve k (x : xs) = k == x || not (null xs') && (k - x) `mod` foldl1 gcd xs' == 0 where xs' = filter (/= 0) (subtract x <$> xs)

main :: IO ()
main = readLn >>= flip replicateM_ go
  where
    go = do
        k <- (!! 1) . fmap read . words <$> getLine
        r <- solve k . fmap read . words <$> getLine
        if r then putStrLn "YES" else putStrLn "NO"

module Main where

import           Control.Monad                  ( foldM
                                                , replicateM
                                                , replicateM_
                                                )
import           Data.Array                     ( listArray )
import           Data.Foldable                  ( maximumBy )
import           Data.List
import qualified Data.Map                      as Map

-- >>> solve 1 $ sort [1,2]
-- True

solve :: Int -> [Int] -> Bool
solve _ []       = False
solve k [x     ] = k == x
solve k (x : xs) = k == x || not (null xs') && k - x `mod` foldl1 gcd xs' == 0 where xs' = filter (/= 0) (subtract x <$> xs)

main :: IO ()
main = readLn >>= flip replicateM_ go
  where
    go = do
        k <- (!! 1) . fmap read . words <$> getLine
        r <- solve k . fmap read . words <$> getLine
        if r then putStrLn "YES" else putStrLn "NO"