You are given a positive integer $$$m$$$ and two integer sequence: $$$a=[a_1, a_2, \ldots, a_n]$$$ and $$$b=[b_1, b_2, \ldots, b_n]$$$. Both of these sequence have a length $$$n$$$.Permutation is a sequence of $$$n$$$ different positive integers from $$$1$$$ to $$$n$$$. For example, these sequences are permutations: $$$[1]$$$, $$$[1,2]$$$, $$$[2,1]$$$, $$$[6,7,3,4,1,2,5]$$$. These are not: $$$[0]$$$, $$$[1,1]$$$, $$$[2,3]$$$.You need to find the non-negative integer $$$x$$$, and increase all elements of $$$a_i$$$ by $$$x$$$, modulo $$$m$$$ (i.e. you want to change $$$a_i$$$ to $$$(a_i + x) \bmod m$$$), so it would be possible to rearrange elements of $$$a$$$ to make it equal $$$b$$$, among them you need to find the smallest possible $$$x$$$.In other words, you need to find the smallest non-negative integer $$$x$$$, for which it is possible to find some permutation $$$p=[p_1, p_2, \ldots, p_n]$$$, such that for all $$$1 \leq i \leq n$$$, $$$(a_i + x) \bmod m = b_{p_i}$$$, where $$$y \bmod m$$$ — remainder of division of $$$y$$$ by $$$m$$$.For example, if $$$m=3$$$, $$$a = [0, 0, 2, 1], b = [2, 0, 1, 1]$$$, you can choose $$$x=1$$$, and $$$a$$$ will be equal to $$$[1, 1, 0, 2]$$$ and you can rearrange it to make it equal $$$[2, 0, 1, 1]$$$, which is equal to $$$b$$$.

The first line contains two integers $$$n,m$$$ ($$$1 \leq n \leq 2000, 1 \leq m \leq 10^9$$$): number of elemens in arrays and $$$m$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i < m$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \leq b_i < m$$$). It is guaranteed that there exists some non-negative integer $$$x$$$, such that it would be possible to find some permutation $$$p_1, p_2, \ldots, p_n$$$ such that $$$(a_i + x) \bmod m = b_{p_i}$$$.

Print one integer, the smallest non-negative integer $$$x$$$, such that it would be possible to find some permutation $$$p_1, p_2, \ldots, p_n$$$ such that $$$(a_i + x) \bmod m = b_{p_i}$$$ for all $$$1 \leq i \leq n$$$.

module Main where

import Control.Monad
import Data.List

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

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

main :: IO ()
main = do
    [n, m] <- getIntList
    a <- getIntList
    b <- sort <$> getIntList
    let b0 = head b;
        c = sort . map (\x -> mod (b0 - x + m) m) $ a
    print . head . filter (check a b m) $ c

check :: [Int] -> [Int] -> Int -> Int -> Bool
check a b m x = (sort . map (\e -> mod (e + x) m) $ a) == b


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. You have to choose a positive integer $$$d$$$ and paint all elements into two colors. All elements which are divisible by $$$d$$$ will be painted red, and all other elements will be painted blue.The coloring is called beautiful if there are no pairs of adjacent elements with the same color in the array. Your task is to find any value of $$$d$$$ which yields a beautiful coloring, or report that it is impossible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The first line of each testcase contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of elements of the array. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{18}$$$).

For each testcase print a single integer. If there is no such value of $$$d$$$ that yields a beautiful coloring, print $$$0$$$. Otherwise, print any suitable value of $$$d$$$ ($$$1 \le d \le 10^{18}$$$).

-- https://codeforces.com/contest/1618/problem/C
import Control.Monad (replicateM)
import qualified Data.ByteString.Char8 as B

getOddPos [] = []
getOddPos [o] = [o]
getOddPos (o:e:xs) = o : getOddPos xs
getEvenPos [] = []
getEvenPos [o] = []
getEvenPos (o:e:xs) = e : getEvenPos xs

main = getLine >>= flip replicateM run . read
run = do
    n <- B.getLine
    numbers <- (read . B.unpack <$>) . B.words <$> B.getLine
    let
        oddList = getOddPos numbers
        evenList = getEvenPos numbers
        oddListGcd = foldl1 gcd oddList
        evenListGcd = foldl1 gcd evenList
    print $
        if not $ any(\x->mod x evenListGcd == 0) oddList then evenListGcd else
        if not $ any(\x->mod x oddListGcd == 0) evenList then oddListGcd  else 0

-- https://codeforces.com/contest/1618/problem/C
import Control.Monad (replicateM)

getOddPos [] = []
getOddPos [o] = [o]
getOddPos (o:e:xs) = o : getOddPos xs
getEvenPos [] = []
getEvenPos [o] = []
getEvenPos (o:e:xs) = e : getEvenPos xs

main = getLine >>= flip replicateM run . read
run = do
    n <- getLine
    numbers <- (read <$>) . words <$> getLine
    let
        oddList = getOddPos numbers
        evenList = getEvenPos numbers
        oddListGcd = foldl1 gcd oddList
        evenListGcd = foldl1 gcd evenList
    print $
        if not $ any(\x->mod x evenListGcd == 0) oddList then evenListGcd else
        if not $ any(\x->mod x oddListGcd == 0) evenList then oddListGcd  else 0

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

solve :: IO ()
solve = do
    void C.getLine
    xs <- readInts
    let (as, bs) = splitEvenOdd xs
        ag = foldl' gcd 0 as
        bg = foldl' gcd 0 bs
        ans | all ((/=0) . (`mod` ag)) bs = ag
            | all ((/=0) . (`mod` bg)) as = bg
            | otherwise                   = 0
    print ans

splitEvenOdd :: [a] -> ([a], [a])
splitEvenOdd = foldr (\a ~(x, y) -> (a:y, x)) ([], [])

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

main :: IO ()
main = flip replicateM_ solve . head =<< readInts

-- https://codeforces.com/contest/1618/problem/C
import Control.Monad (replicateM)

getOddPos [] = []
getOddPos [o] = [o]
getOddPos (o:e:xs) = o : getOddPos xs
getEvenPos [] = []
getEvenPos [o] = []
getEvenPos (o:e:xs) = e : getEvenPos xs

main = getLine >>= flip replicateM run . read
run = do
    n <- getLine
    numbers <- (read <$>) . words <$> getLine
    let
        oddList = getOddPos numbers
        evenList = getEvenPos numbers
        oddListGcd = foldl1 gcd $ oddList
        evenListGcd = foldl1 gcd $ evenList
        biggerGcd = max oddListGcd evenListGcd
    print $ if any(\x->mod x biggerGcd == 0) oddList && any(\x->mod x biggerGcd == 0) evenList
    then 0
    else biggerGcd


Polycarp is playing a new computer game. This game has $$$n$$$ stones in a row. The stone on the position $$$i$$$ has integer power $$$a_i$$$. The powers of all stones are distinct.Each turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the rightmost stone). When Polycarp destroys the stone it does not exist any more.Now, Polycarp wants two achievements. He gets them if he destroys the stone with the least power and the stone with the greatest power. Help Polycarp find out what is the minimum number of moves he should make in order to achieve his goal.For example, if $$$n = 5$$$ and $$$a = [1, 5, 4, 3, 2]$$$, then Polycarp could make the following moves:   Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$;  Destroy the rightmost stone. After this move $$$a = [5, 4, 3]$$$;  Destroy the leftmost stone. After this move $$$a = [4, 3]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game. Please note that in the example above, you can complete the game in two steps. For example:   Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$;  Destroy the leftmost stone. After this move $$$a = [4, 3, 2]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stones. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — the power of the stones.

For each test case, output the minimum number of moves required to destroy the stones with the greatest and the lowest power.

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

-- (ghc -Werror -O1 -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  cat -- input.txt | ./a.out > temp.txt  &&  diff -sdu -- output.txt temp.txt)  &&  echo OKAY  ||  echo ERROR

import Prelude
import Control.Monad
import Data.List

main :: IO ()
main = do
    t <- readLn
    tcs <- replicateM t readTC

    (putStr . unlines . map solve) tcs

readTC = do
    _n <- readLn  :: IO Int
    readIListLn

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

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

solve nums = show $ length nums - length nums3
  where
    mn = minimum nums
    mx = maximum nums

    fnd = [mn, mx]

    (v2, nums2) = g fnd nums

    fnd2 = filter (/= v2) fnd

    (_, nums3) = g fnd2 nums2

g fnd nums = last . sortOn (length.snd) $ f <$> fnd <*> [nums, reverse nums]

f _ [] = error "impossible by condition"
f x (y:ys) | (x == y)  = (x, ys)
           | otherwise = f x ys

import Control.Monad
import Data.List
import Data.Maybe
readInts = fmap (map read.words) getLine :: IO [Int]
nElemIndex n xs = fromJust (elemIndex n xs)

solve l r n = minimum [x,y,z]
            where
                x = l + 1 + n - r
                y = r + 1
                z = n - l

printResult = do
    n <- readLn :: IO Int
    a <- readInts
    let i = nElemIndex (maximum a) a
        j = nElemIndex (minimum a) a
    print $ solve (min i j) (max i j) n

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

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

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

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

solve :: [Int] -> Int
solve xs = n - maximum [l, r, m]
  where
    n = length xs
    check = liftA2 (&&) (/= 1) (/= n)
    l = length $ takeWhile check xs
    r = length $ takeWhile check $ reverse xs
    m = n - l - r - 2

import Control.Monad
import Data.List
readInts = fmap (map read.words) getLine :: IO [Int]

printS = do
    n <- readLn::IO Int
    xs <- readInts
    let mini = head $ filter ((== minimum xs) . (xs !!)) [0..]
        maxi = head $ filter ((== maximum xs) . (xs !!)) [0..]
    let x = minimum [mini,maxi]
        y = maximum [mini,maxi]
    print $ minimum [y+1, n-x, x + 1 + n - y]
main = do
    t <- readLn::IO Int
    replicateM_ t printS

makeInteger :: [String] -> [Int]
makeInteger = map read

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

solve_multitest :: Int -> IO()
solve_multitest 0 = return ()
solve_multitest t = do
    solve_test
    solve_multitest (t - 1)

solve_test :: IO()
solve_test = do
    line <- getLine
    let n = (read line::Int)
    line <- getLine
    let inparr = words line
    let arr = makeInteger inparr
    let x = find_index_k arr 1
    let y = find_index_k arr n
    let mnpos = min x y
    let mxpos = max x y
    let ans = min (min mxpos (n - mnpos + 1)) (mnpos + n - mxpos + 1)
    putStrLn (show ans)

find_index_k :: [Int] -> Int -> Int
find_index_k a k = do
    let x = head a
    if x == k then
        1
    else
        find_index_k (drop 1 a) k + 1

--prewritten code: https://github.com/antma/algo
{-# LANGUAGE BangPatterns #-}
{-# Options_GHC -O2 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)
import Data.Char
import Data.List(minimum,maximum)

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

test' :: [Int] -> Int
test' a = minimum [res1, res2, res3]
  where
    n = length a
    f g = snd $ head $ filter ( (== g). fst) $ zip a [0 ..]
    u = f $ minimum a
    v = f $ maximum a
    u' = min u v
    v' = max u v
    res1 = 1 + v'
    res2 = n - u'
    res3 = 1 + u' + n - v'

nl = char7 '\r' <> char7 '\n'
test :: Builder -> Int -> [Int] -> Builder
test buf 0 _ = buf
test buf nt (n:a) = test (buf <> intDec (test' b) <> nl) (pred nt) c
  where
    (b, c) = splitAt n a

solve :: [Int] -> Builder
solve (nt:xs) = test mempty nt xs

main :: IO ()
main = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents


Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.

The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.

If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".

NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.

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

import Control.Applicative
import Control.Monad

data Status = Rated | Unrated | Unknown
              deriving (Show, Eq)

ratingChanged :: (Int, Int) -> Bool
ratingChanged (x, y) = x /= y

tails :: [a] -> [[a]]
tails [x] = [[x]]
tails xss@(x:xs) = xss : tails xs

solve :: [(Int, Int)] -> Status
solve rs | haveChanges = Rated
         | haveMisplaces = Unrated
         | otherwise = Unknown
    where haveChanges = not . null . filter id $ map ratingChanged rs
          haveMisplaces = not . null . concat $ [filter (> x) ys | (x:ys) <- tails bs]
          bs = map fst rs

test0 = [(3060,  3060)
        , (2194, 2194)
        , (2876, 2903)
        , (2624, 2624)
        , (3007, 2991)
        , (2884, 2884)
        ] :: [(Int, Int)]

test1 = [ (1500, 1500)
        , (1300, 1300)
        , (1200, 1200)
        , (1400, 1400)
        ] :: [(Int, Int)]

test2 = [ (3123, 3123)
        , (2777, 2777)
        , (2246, 2246)
        , (2246, 2246)
        , (1699, 1699)
        ] :: [(Int, Int)]

main :: IO ()
main = do
  n <- read <$> getLine
  rs <- replicateM n $ do
          [a, b] <- map read . words <$> getLine
          return (a, b)
  putStrLn $ case solve rs of
    Rated -> "rated"
    Unrated -> "unrated"
    Unknown -> "maybe"

module Main where

import Data.Functor
import Control.Applicative

main = do
    n <- read <$> getLine :: IO Int
    ps <- sequence $ replicate n $ (\[a, b] -> (read a, read b)) . words <$> getLine :: IO [(Int, Int)]
    if any (uncurry (/=)) ps then
        putStr "rated"
    else if and $ zipWith (>=) ps $ tail ps then
        putStr "maybe"
    else
        putStr "unrated"
    return ()

f::[String]->Bool
f []=True
f (s:str)=let (a:b:[])=words s
          in if a==b then f str else False

f2::[String]->Bool
f2 (s:[])=True
f2 (s:s2:str)=let (a:b:[])=map read (words s)::[Int]
                  (c:d:[])=map read (words s2)::[Int]
              in if a<c then False else f2 (s2:str)

main = do
       e<-getLine
       es<-getContents
       let xs=lines es
       putStrLn $ if (f xs) && ((f2 xs)==False) then "unrated"
                          else if (f xs) && (f2 xs) then "maybe" else "rated"

import Control.Monad( replicateM)
import Control.Applicative( (<$>))

main = do
    n_ <- readLn
    let
	readPair = do
	    [before, after] <- map read . words <$> getLine
	    return (before, after)

    pairs_ <- replicateM n_ readPair::IO [(Int,Int)]
    let
	isDesc [] = True
	isDesc [_] = True
	isDesc (a:tl@(b:rem))	| a>=b	    = isDesc tl
				| otherwise = False

	(befores, afters) = unzip pairs_

	sames = and $ zipWith (==) befores afters

    putStr $ if sames
		then if isDesc befores
			then "maybe"
			else "unrated"
		else "rated"

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

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

solve bas = if any (\(b, a) -> b /= a) bas
  then Just True
  else if any (\((_, a1), (_, a2)) -> a1 < a2) $ zip bas (tail bas) then Just False else Nothing

main = do
  n <- readInt <$> B.getLine
  bas <- replicateM n ((\(b:a:_) -> (b,a)) . readInts <$> B.getLine)
  putStr $ maybe "maybe" (\b -> if b then "rated" else "unrated") $ solve bas


Screen resolution of Polycarp's monitor is $$$a \times b$$$ pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates $$$(x, y)$$$ ($$$0 \le x < a, 0 \le y < b$$$). You can consider columns of pixels to be numbered from $$$0$$$ to $$$a-1$$$, and rows — from $$$0$$$ to $$$b-1$$$.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.

In the first line you are given an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. In the next lines you are given descriptions of $$$t$$$ test cases. Each test case contains a single line which consists of $$$4$$$ integers $$$a, b, x$$$ and $$$y$$$ ($$$1 \le a, b \le 10^4$$$; $$$0 \le x < a$$$; $$$0 \le y < b$$$) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that $$$a+b>2$$$ (e.g. $$$a=b=1$$$ is impossible).

Print $$$t$$$ integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.

NoteIn the first test case, the screen resolution is $$$8 \times 8$$$, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.

import Control.Monad
main :: IO ()
main = do
  n <- readLn
  replicateM_ n routine

routine :: IO ()
routine = do
  [a,b,x,y] <- (map read.words) <$> getLine
  print $ solve a b x y

solve :: Int -> Int -> Int -> Int -> Int
solve a b x y = max (xm*b) (ym*a)
  where
    x1=x
    x2=a-x-1
    xm=max x1 x2
    y1=y
    y2=b-y-1
    ym=max y1 y2

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

onecase = do
		[r,c,x,y]<- map read <$> words <$> getLine ::IO [Int]
		let ml = max x (r-x-1)
		let mw = max y (c-y-1)
		print $ max (ml*c) (mw*r)

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

main = interact $ unlines . map solve . tail . lines

solve s = show $ foldl max 0 [ a * y
                             , b * x
                             , a * (b-y-1)
                             , b * (a-x-1) ]
      where [a, b, x, y] = map (read :: String -> Int) (words s)

maxOkayArea :: Int -> Int -> Int -> Int -> Int
maxOkayArea a b x y = max ((max x x') * b) ((max y y') * a)
    where
        x' = a - 1 - x
        y' = b - 1 - y

readInt :: String -> Int
readInt = read

main = do
    n <- fmap readInt getLine
    s <- fmap (map (map readInt.words).lines) getContents
    putStrLn.unlines.map show.map (\[a,b,x,y] -> maxOkayArea a b x y) $ s

import Control.Monad

data Rect = Rect { l :: Int,  r :: Int, b :: Int, t :: Int } deriving (Show)

main :: IO ()
main = do
  examples <- read <$> getLine :: IO Int
  _ <- forM (replicate examples ()) $ \_ -> do
     [xMax, yMax, x, y] <- (\str -> read <$> words str) <$> getLine :: IO [Int]
     putStrLn $ show $ solve xMax yMax x y
  return ()

area :: Rect -> Int
area (Rect l r b t)
  | (l <= r) && (b <= t) = (r - l + 1) * (t - b + 1)
  | otherwise = 0

solve :: Int -> Int -> Int -> Int -> Int
solve xMax yMax x y = foldl1 max $ area <$>
  [ Rect 0 (xMax-1) 0 (y-1) -- bottom to Y
  , Rect 0 (x-1) 0 (yMax-1) -- left to X
  , Rect (x+1) (xMax-1) 0 (yMax-1) -- right to X
  , Rect 0 (xMax-1) (y+1) (yMax-1) -- top to Y
  ]

import Control.Arrow
import Data.List

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

solve :: [Integer] -> Integer
solve [a, b, x, y] = max ((max x (a - x - 1)) * b)
                        ((max y (b - y - 1)) * a)

pop :: [a] -> (a, [a])
pop ([x]) = (x, [])
pop (x:xs) = (x, xs)
pop _ = undefined

cal :: Int -> IO ()
cal 0 = return ()
cal n = do
  line <- getLine
  let xs = map (read :: String -> Int) $ words line
  let (a, x1) = pop xs
  let (b, x2) = pop x1
  let (x, x3) = pop x2
  let (y, x4) = pop x3
  let (x1, x2) = (x, a - 1 - x)
  let (y1, y2) = (y, b - 1 - y)
  let area = maximum [calArea (x1, b), calArea (x2, b),calArea (a, y1), calArea (a, y2)]
  putStrLn $ show area
  cal (n - 1)
  where calArea (w, h) =  w * h

main :: IO ()
main = do
  a <- getLine
  let n = (read a) :: Int
  cal n

import Control.Monad

data Rect = Rect { l :: Int,  r :: Int, b :: Int, t :: Int }

main :: IO ()
main = do
  examples <- read <$> getLine :: IO Int
  _ <- forM (replicate examples ()) $ \_ -> do
     [xMax, yMax, x, y] <- (\str -> read <$> words str) <$> getLine :: IO [Int]
     putStrLn $ show $ solve xMax yMax x y
  return ()

area :: Rect -> Int
area (Rect l r b t)
  | (l < r) && (b < t) = (r - l + 1) * (t - b + 1)
  | otherwise = 0

solve :: Int -> Int -> Int -> Int -> Int
solve xMax yMax x y = foldl1 max $ area <$>
  [ Rect 0 (xMax-1) 0 (y-1)
  , Rect 0 (x-1) 0 (yMax-1)
  , Rect (x+1) (xMax-1) 0 (yMax-1)
  , Rect 0 (xMax-1) (y+1) (yMax-1)
  ]


Little John aspires to become a plumber! Today he has drawn a grid consisting of n rows and m columns, consisting of n × m square cells.In each cell he will draw a pipe segment. He can only draw four types of segments numbered from 1 to 4, illustrated as follows:  Each pipe segment has two ends, illustrated by the arrows in the picture above. For example, segment 1 has ends at top and left side of it.Little John considers the piping system to be leaking if there is at least one pipe segment inside the grid whose end is not connected to another pipe's end or to the border of the grid. The image below shows an example of leaking and non-leaking systems of size 1 × 2.  Now, you will be given the grid that has been partially filled by Little John. Each cell will either contain one of the four segments above, or be empty. Find the number of possible different non-leaking final systems after Little John finishes filling all of the empty cells with pipe segments. Print this number modulo 1000003 (106 + 3).Note that rotations or flipping of the grid are not allowed and so two configurations that are identical only when one of them has been rotated or flipped either horizontally or vertically are considered two different configurations.

The first line will contain two single-space separated integers n and m (1 ≤ n, m, n·m ≤ 5·105) — the number of rows and columns respectively. Then n lines follow, each contains exactly m characters — the description of the grid. Each character describes a cell and is either one of these:    "1" - "4" — a pipe segment of one of four types as described above  "." — an empty cell

Print a single integer denoting the number of possible final non-leaking pipe systems modulo 1000003 (106 + 3). If there are no such configurations, print 0.

NoteFor the first example, the initial configuration of the grid is as follows.   The only two possible final non-leaking pipe configurations are as follows:    For the second example, the initial grid is already leaking, so there will be no final grid that is non-leaking.For the final example, there's only one possible non-leaking final grid as follows.

import Data.List
c=cycle[1>0,0>1]
z h l=length$filter(all(\(a,c)->a=='.'||c==(a`elem`h)).zip l)[c,tail c]
s s=foldr1(((`mod`1000003).).(*))$z"14"`map`transpose s++z"12"`map`s
main=interact$show.s.tail.lines

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
{-# OPTIONS_GHC -O2 #-}

import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
--import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph

parseInput = do
    n <- readInt
    m <- readInt
    grid <- replicateM n (BS.unpack <$> readString)
    return (n, m, grid)
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

main = print =<< solve . evalState parseInput <$> BS.getContents

modulo = 1000003

newtype ModP = ModP Integer deriving Eq

instance Show ModP where
    show (ModP a) = show a

instance Num ModP where
    ModP a + ModP b = ModP $ (a + b) `mod` modulo
    ModP a - ModP b = ModP $ (a - b) `mod` modulo
    ModP a * ModP b = ModP $ (a * b) `mod` modulo
    signum = undefined
    abs = undefined
    fromInteger = ModP . (`mod` modulo)

solve (n, m, grid)
    | isConflict = 0
    | otherwise  = fromInteger 2 ^ frees :: ModP
  where
    lst = concat [ map (process (i, j)) (getD cij)
                 | (i, row) <- zip [0..] grid
                 , (j, cij) <- zip [0..] row
                 ]

    process (x, y) L = (x, even y)
    process (x, y) R = (x, odd y)
    process (x, y) U = (n + y, even x)
    process (x, y) D = (n + y, odd x)

    arr = accumArray merge None (0, n + m - 1) lst :: Array Int Info

    answer = elems arr

    isConflict = any (==Conflict) answer
    frees = length $ filter (==None) answer

    merge (Unique bool) b
        | bool == b = Unique bool
        | otherwise = Conflict

    merge Conflict _ = Conflict
    merge None x = Unique x

data Direction = L | R | U | D deriving (Show, Eq)

data Info = None
          | Unique Bool
          | Conflict deriving (Show, Eq)

getD '1' = [L, U]
getD '2' = [L, D]
getD '3' = [R, D]
getD '4' = [R, U]
getD _   = []

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

class (Monad m) => MonadState s m | m -> s where
	get :: m s
	put :: s -> m ()

modify :: (MonadState s m) => (s -> s) -> m ()
modify f = do
	s <- get
	put (f s)

gets :: (MonadState s m) => (s -> a) -> m a
gets f = do
	s <- get
	return (f s)

newtype State s a = State { runState :: s -> (a, s) }

instance Functor (State s) where
	fmap f m = State $ \s -> let
		(a, s') = runState m s
		in (f a, s')

instance Applicative (State s) where
    pure = return
    (<*>) = ap

instance Monad (State s) where
	return a = State $ \s -> (a, s)
	m >>= k  = State $ \s -> let
		(a, s') = runState m s
		in runState (k a) s'

instance MonadState s (State s) where
	get   = State $ \s -> (s, s)
	put s = State $ \_ -> ((), s)

evalState :: State s a -> s -> a
evalState m s = fst (runState m s)

execState :: State s a -> s -> s
execState m s = snd (runState m s)

mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
mapState f m = State $ f . runState m

withState :: (s -> s) -> State s a -> State s a
withState f m = State $ runState m . f

state = State

import Data.List
import Control.Applicative

newtype I=I Int deriving (Show, Eq, Ord)
mmm :: Integral a => a -> a
mmm x=x `mod` 1000003

instance Num I where
  I x+I y=I(mmm$x+y)
  I x*I y|y<10^3 || x < 10^3 = I $ mmm $ x * y
   | otherwise = I $ fromInteger $ mmm $
                   (fromIntegral x :: Integer) * fromIntegral y
  fromInteger n = I $ fromInteger $ mmm n

instance Real I
instance Enum I
instance Integral I where
  toInteger (I i) = toInteger i

s1 :: (Char -> Bool) -> [Char] -> I
s1 is1 l = goN l where
  goN [] = 2
  goN ('.':t) = goN t
  goN (some:t) = goS (not $ is1 some) t
  goS need1 [] = 1
  goS need1 ('.':t) = goS (not need1) t
  goS need1 (some:t) | is1 some /= need1 = 0
   | 1>0 = goS (not need1) t

solve s = product (map (s1 ((||) <$> (=='1') <*>  (=='4'))) $ transpose s) * product (map (s1 ((||) <$> (=='1') <*> (=='2')))  s)

ss = show . toInteger . solve
main=interact$ss.tail.lines

import Data.List
import Control.Applicative

newtype I=I Int deriving (Show, Eq, Ord)
mmm :: Integral a => a -> a
mmm x=x `mod` 1000003

instance Num I where
  I x+I y=I(mmm$x+y)
  I x*I y|y<10^3 || x < 10^3 = I $ mmm $ x * y
   | otherwise = I $ mmm $ fromInteger $
                   (fromIntegral x :: Integer) * fromIntegral y
  fromInteger n = I $ fromInteger $ mmm n

instance Real I
instance Enum I
instance Integral I where
  toInteger (I i) = toInteger i

s1 :: (Char -> Bool) -> [Char] -> I
s1 is1 l = goN l where
  goN [] = 2
  goN ('.':t) = goN t
  goN (some:t) = goS (not $ is1 some) t
  goS need1 [] = 1
  goS need1 ('.':t) = goS (not need1) t
  goS need1 (some:t) | is1 some /= need1 = 0
   | 1>0 = goS (not need1) t

solve s = product (map (s1 ((||) <$> (=='1') <*>  (=='4'))) $ transpose s) * product (map (s1 ((||) <$> (=='1') <*> (=='2')))  s)

main=interact$show . toInteger . solve . tail . lines

import Data.List
import Control.Applicative

newtype I=I Int deriving (Show, Eq)
mmm :: Integral a => a -> a
mmm x=x `mod` 1000003

instance Num I where
  I x+I y=I(mmm$x+y)
  I x*I y|y<10^3 || x < 10^3 = I $ mmm $ x * y
   | otherwise = I $ mmm $ fromInteger $
                   (fromIntegral x :: Integer) * fromIntegral y
  fromInteger n = I $ fromInteger $ mmm n

s1 :: (Char -> Bool) -> [Char] -> I
s1 is1 l = goN l where
  goN [] = 2
  goN ('.':t) = goN t
  goN (some:t) = goS (not $ is1 some) t
  goS need1 [] = 1
  goS need1 ('.':t) = goS (not need1) t
  goS need1 (some:t) | is1 some /= need1 = 0
   | 1>0 = goS (not need1) t

solve s = product (map (s1 ((||) <$> (=='1') <*>  (=='4'))) $ transpose s) * product (map (s1 ((||) <$> (=='1') <*> (=='2')))  s)

main=interact$show . solve . tail . lines

import Data.List
import Control.Applicative

s1 is1 l = goN l where
  goN [] = 2
  goN ('.':t) = goN t
  goN (some:t) = goS (not $ is1 some) t
  goS need1 [] = 1
  goS need1 ('.':t) = goS (not need1) t
  goS need1 (some:t) | is1 some /= need1 = 0
   | 1>0 = goS (not need1) t

solve s = product (map (s1 ((||) <$> (=='1') <*>  (=='4'))) $ transpose s) * product (map (s1 ((||) <$> (=='1') <*> (=='2')))  s)

main=interact$show . solve . tail . lines

import Data.List
c=cycle[1>0,0>1]
z h l = length$filter(o l)[c,tail c]where o=(all g.).zip;g(a,c)=a=='.'||c==(a`elem`h)
s s=foldr1((.(`mod`1000003)).(*))$z"14"`map`transpose s++z"12"`map`s
main=interact$show.s.tail.lines


Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed!Vasya knows that the matrix consists of n rows and m columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence a1, a2, ..., an denotes the xor of elements in rows with indices 1, 2, ..., n, respectively. Similarly, for each column, he knows the xor of the elements in this column. The sequence b1, b2, ..., bm denotes the xor of elements in columns with indices 1, 2, ..., m, respectively.Help Vasya! Find a matrix satisfying the given constraints or tell him that there is no suitable matrix.

The first line contains two numbers n and m (2 ≤ n, m ≤ 100) — the dimensions of the matrix. The second line contains n numbers a1, a2, ..., an (0 ≤ ai ≤ 109), where ai is the xor of all elements in row i. The third line contains m numbers b1, b2, ..., bm (0 ≤ bi ≤ 109), where bi is the xor of all elements in column i.

If there is no matrix satisfying the given constraints in the first line, output "NO". Otherwise, on the first line output "YES", and then n rows of m numbers in each ci1, ci2, ... , cim (0 ≤ cij ≤ 2·109) — the description of the matrix. If there are several suitable matrices, it is allowed to print any of them.

import           Control.Applicative
import           Data.Bits
import qualified Data.Foldable       as F

main :: IO ()
main = do
    [n, m] <- map read.words <$> getLine
    xs <- map read.words <$> getLine
    ys <- map read.words <$> getLine
    case solve n m xs ys of
        Just res -> do
            putStrLn "YES"
            putStr.unlines.map(unwords.map show) $ res
        Nothing -> putStrLn "NO"

solve :: Int -> Int -> [Int] -> [Int] -> Maybe [[Int]]
solve n m (x:xs) (y:ys)
    | F.foldl' xor x xs == F.foldl' xor y ys = Just $ hd : tl
    | otherwise = Nothing
  where
    hd = F.foldl' xor y xs : ys
    tl = zipWith (:) xs . repeat $ replicate (m - 1) 0


The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thus, Sereja orders a number of pizzas so they can eat right after the end of the competition.Teams plan to train for n times during n consecutive days. During the training session Sereja orders exactly one pizza for each team that is present this day. He already knows that there will be ai teams on the i-th day.There are two types of discounts in Sereja's favourite pizzeria. The first discount works if one buys two pizzas at one day, while the second is a coupon that allows to buy one pizza during two consecutive days (two pizzas in total).As Sereja orders really a lot of pizza at this place, he is the golden client and can use the unlimited number of discounts and coupons of any type at any days.Sereja wants to order exactly ai pizzas on the i-th day while using only discounts and coupons. Note, that he will never buy more pizzas than he need for this particular day. Help him determine, whether he can buy the proper amount of pizzas each day if he is allowed to use only coupons and discounts. Note, that it's also prohibited to have any active coupons after the end of the day n.

The first line of input contains a single integer n (1 ≤ n ≤ 200 000) — the number of training sessions. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 10 000) — the number of teams that will be present on each of the days.

If there is a way to order pizzas using only coupons and discounts and do not buy any extra pizzas on any of the days, then print "YES" (without quotes) in the only line of output. Otherwise, print "NO" (without quotes).

NoteIn the first sample, Sereja can use one coupon to buy one pizza on the first and the second days, one coupon to buy pizza on the second and the third days and one discount to buy pizzas on the fourth days. This is the only way to order pizzas for this sample.In the second sample, Sereja can't use neither the coupon nor the discount without ordering an extra pizza. Note, that it's possible that there will be no teams attending the training sessions on some days.

import Data.List.Split

solve :: [Int] -> Bool
solve [] = True
solve [x] = even x && x >= 0
solve (x:y:nums)
  | x < 0 = False
  | even x = solve (y:nums)
  | otherwise = solve ((y-1):nums)

main :: IO ()
main = do
    _ <- getLine
    line <- getLine
    let nums = map read $ splitOn " " line
    putStrLn $ if solve nums then "YES" else "NO"

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

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

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

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

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

  solve :: Bool -> [Int] -> Bool
  solve acc  [] = acc
  solve True (x:xs)
    | x `mod` 2 == 0 = solve True xs
    | x `mod` 2 == 1 = solve False xs
  solve False (0:xs) = False
  solve False (1:xs) = solve True xs
  solve False (x:xs)
    | x `mod` 2 == 0 = solve False xs
    | x `mod` 2 == 1 = solve True xs

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

  main :: IO()
  main = do
    n <- getLine
    xs <- getLine >>= return . map readInt .  words
    let canDo = solve True xs
    putStrLn $ getOutput canDo

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

readInt :: B.ByteString -> Int
readInt bs=case B.readInt bs of{Just(n,_)->n;_->error$"readInt error : bs = "++show bs;}

main = do
  _ <- getLine
  xs <- map readInt.B.words <$> B.getLine
  putStrLn.bool"NO""YES" $ solve xs

solve :: [Int] -> Bool
solve xs = all isValid $ split xs
  where
    isValid (x:xs) | even x = isValid xs
    isValid (x:y:xs) = isValid $ (y-1):xs
    isValid (_:_) = False
    isValid [] = True

split :: [Int] -> [[Int]]
split xs = case span (0/=) xs of
  (ys, 0:zs) -> ys : split zs
  (ys, []) -> [ys]
  _ -> undefined

xor :: Bool -> Bool -> Bool
xor a b = a && not b || b && not a

doit :: [Int] -> Bool -> Bool
doit [] last = not last
doit (x:xs) last
	| last && x == 0 = False
	| otherwise = doit xs $ last `xor` (x `mod` 2 == 1)

main = do
	getLine
	a <- getLine >>= return . map read . words
	putStrLn $ if doit a False then "YES" else "NO"

import Data.List
import Data.Array

main = do
  getLine
  aStr <- getLine
  putStrLn $
    if solve $ map (read :: String -> Int) (words aStr)
      then "YES"
      else "NO"

solve a = dp n 0
  where
        n = length a
        a' = listArray (1, n) a

        dp :: Int -> Int -> Bool
        dp 0 0 = True
        dp 0 1 = False
        dp i 0 = dps ! (i-1, (a' ! i) `mod` 2)
        dp i 1 = if (a' ! i) `mod` 2 == 0
                    then (if (a' ! i) /= 0 then dps ! (i-1, 1) else False)
                    else dps ! (i-1, 0)

        dps = listArray bounds [dp i j | (i, j) <- range bounds]
        bounds = ((0, 0), (n, 1))


You are given a string $$$s$$$ consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode: res = 0for init = 0 to inf    cur = init    ok = true    for i = 1 to |s|        res = res + 1        if s[i] == '+'            cur = cur + 1        else            cur = cur - 1        if cur < 0            ok = false            break    if ok        breakNote that the $$$inf$$$ denotes infinity, and the characters of the string are numbered from $$$1$$$ to $$$|s|$$$.You have to calculate the value of the $$$res$$$ after the process ends.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only lines of each test case contains string $$$s$$$ ($$$1 \le |s| \le 10^6$$$) consisting only of characters + and -. It's guaranteed that sum of $$$|s|$$$ over all test cases doesn't exceed $$$10^6$$$.

For each test case print one integer — the value of the $$$res$$$ after the process ends.

import Control.Monad
import Data.Int

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

parse :: String -> [Int64]
parse = map f
  where
    f '+' = 1
    f '-' = -1

solve :: [Int64] -> Int64
solve = helper 0 1 0 . scanl1 (+)
  where
    helper :: Int64 -> Int64 -> Int64 -> [Int64] -> Int64
    helper i x acc [] = acc + i
    helper i x acc (a:as)
      | a == -x = helper (succ i) (succ x) (acc + i + 1) as
      | otherwise = helper (succ i) x acc as

import Control.Monad

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

parse :: String -> [Int]
parse = map f
  where
    f '+' = 1
    f '-' = -1

solve :: [Int] -> Int
solve = helper 0 1 0 . scanl1 (+)
  where
    helper :: Int -> Int -> Int -> [Int] -> Int
    helper i x acc [] = acc + i
    helper i x acc (a:as)
      | a == -x = helper (succ i) (succ x) (acc + i + 1) as
      | otherwise = helper (succ i) x acc as


A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at point (x1, y1), and the distress signal came from the point (x2, y2).Due to Gadget's engineering talent, the rescuers' dirigible can instantly change its current velocity and direction of movement at any moment and as many times as needed. The only limitation is: the speed of the aircraft relative to the air can not exceed  meters per second.Of course, Gadget is a true rescuer and wants to reach the destination as soon as possible. The matter is complicated by the fact that the wind is blowing in the air and it affects the movement of the dirigible. According to the weather forecast, the wind will be defined by the vector (vx, vy) for the nearest t seconds, and then will change to (wx, wy). These vectors give both the direction and velocity of the wind. Formally, if a dirigible is located at the point (x, y), while its own velocity relative to the air is equal to zero and the wind (ux, uy) is blowing, then after  seconds the new position of the dirigible will be .Gadget is busy piloting the aircraft, so she asked Chip to calculate how long will it take them to reach the destination if they fly optimally. He coped with the task easily, but Dale is convinced that Chip has given the random value, aiming only not to lose the face in front of Gadget. Dale has asked you to find the right answer.It is guaranteed that the speed of the wind at any moment of time is strictly less than the maximum possible speed of the airship relative to the air.

The first line of the input contains four integers x1, y1, x2, y2 (|x1|,  |y1|,  |x2|,  |y2| ≤ 10 000) — the coordinates of the rescuers' headquarters and the point, where signal of the distress came from, respectively.  The second line contains two integers  and t (0 < v, t ≤ 1000), which are denoting the maximum speed of the chipmunk dirigible relative to the air and the moment of time when the wind changes according to the weather forecast, respectively.  Next follow one per line two pairs of integer (vx, vy) and (wx, wy), describing the wind for the first t seconds and the wind that will blow at all the remaining time, respectively. It is guaranteed that  and .

Print a single real value — the minimum time the rescuers need to get to point (x2, y2). You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

module Main where

import System.IO
import Prelude

class Vec a where
    (⊙) :: a -> a -> Double
    (⊕) :: a -> a -> a
    (⊖) :: a -> a -> a
    (⊛) :: Double -> a -> a
    (⊘) :: a -> Double -> a
    mag :: a -> Double
    norm :: a -> a

data V2 = V2 { _x :: Double, _y :: Double }
        deriving(Show,Eq)

instance Vec V2 where
  (⊙) (V2 x1 y1) (V2 x2 y2) = (x1 * x2) + (y1 * y2)
  (⊕) (V2 x1 y1) (V2 x2 y2) = V2 (x1 + x2) (y1 + y2)
  (⊖) (V2 x1 y1) (V2 x2 y2) = V2 (x1 - x2) (y1 - y2)
  (⊛) s (V2 x y) = V2 (s * x) (s * y)
  (⊘) (V2 x y) s = V2 (x / s) (y / s)
  mag (V2 x y) = sqrt (x * x + y * y)
  norm v = v ⊘ (mag v)

rd :: String -> Double
rd = read

windOffset :: V2 -> V2 -> Double -> Double -> V2
windOffset v w t s = ((min s t) ⊛ v) ⊕ ((max (s-t) 0.0) ⊛ w)

canMake :: V2 -> V2 -> Double -> Double -> V2 -> V2 -> Double -> Bool
canMake p1 p2 vmax t v w s =
  --s*vmax grows at rate vmax
  --dist grows at a rate that approaches |w| <= vmax
  dist <= s*vmax
  --alternatively: dist - s*vmax <= 0
  where
    --dist is unimodal (cup) with respect to s
    --why? wo.x^2 is unimodal (cup) wrt s, wo.y^2 is unimodal (cup) wrt s
    --cup + cup = cup
    --sqrt(cup) = cup
    --we need to know more than just this, though
    --we also need to know that its derivative is bounded above by vmax
    dist = mag $ (p1 ⊕ wo) ⊖ p2
    --the components of wo have s-derivatives proportional to
    --the components of w. they are either monotone or antitone.
    --ds(|wo|) <= s*vmax, since |w| <= vmax
    wo = windOffset v w t s

binSearch :: (Double -> Bool) -> Double -> Double -> Double
binSearch f lo hi =
  if hi - lo < 10e-8 then
    mid
  else
    if fmid then
      binSearch f lo mid
    else
      binSearch f mid hi
  where
    mid  = (lo + hi) / 2.0
    fmid = f mid

main :: IO ()
main = do h <- return stdin
          [x1,y1,x2,y2] <- fmap ((map rd) . words) $ hGetLine h
          [vmax, t] <- fmap ((map rd) . words) $ hGetLine h
          [vx, vy] <- fmap ((map rd) . words) $ hGetLine h
          [wx, wy] <- fmap ((map rd) . words) $ hGetLine h
          let p1 = V2 x1 y1
          let p2 = V2 x2 y2
          let v = V2 vx vy
          let w = V2 wx wy
          putStrLn (show (binSearch (canMake p1 p2 vmax t v w) 0.0 2.0e32))
          return ()

module Main where

import System.IO
import Prelude

class Vec a where
    (⊙) :: a -> a -> Double
    (⊕) :: a -> a -> a
    (⊖) :: a -> a -> a
    (⊛) :: Double -> a -> a
    (⊘) :: a -> Double -> a
    mag :: a -> Double
    norm :: a -> a

data V2 = V2 { _x :: Double, _y :: Double }
        deriving(Show,Eq)

instance Vec V2 where
  (⊙) (V2 x1 y1) (V2 x2 y2) = (x1 * x2) + (y1 * y2)
  (⊕) (V2 x1 y1) (V2 x2 y2) = V2 (x1 + x2) (y1 + y2)
  (⊖) (V2 x1 y1) (V2 x2 y2) = V2 (x1 - x2) (y1 - y2)
  (⊛) s (V2 x y) = V2 (s * x) (s * y)
  (⊘) (V2 x y) s = V2 (x / s) (y / s)
  mag (V2 x y) = sqrt (x * x + y * y)
  norm v = v ⊘ (mag v)

rd :: String -> Double
rd = read

windOffset :: V2 -> V2 -> Double -> Double -> V2
windOffset v w t s = (t ⊛ v) ⊕ ( (max (s - t) 0.0) ⊛ w )

canMake :: V2 -> V2 -> Double -> Double -> V2 -> V2 -> Double -> Bool
canMake p1 p2 vmax t v w s =
  --s*vmax grows at rate vmax
  --dist grows at a rate that approaches |w| <= vmax
  dist <= s*vmax
  --alternatively: dist - s*vmax <= 0
  where
    --dist is unimodal (cup) with respect to s
    --why? wo.x^2 is unimodal (cup) wrt s, wo.y^2 is unimodal (cup) wrt s
    --cup + cup = cup
    --sqrt(cup) = cup
    --we need to know more than just this, though
    --we also need to know that its derivative is bounded above by vmax
    dist = mag $ (p1 ⊕ wo) ⊖ p2
    --the components of wo have s-derivatives proportional to
    --the components of w. they are either monotone or antitone.
    --ds(|wo|) <= s*vmax, since |w| <= vmax
    wo = windOffset v w t s

binSearch :: (Double -> Bool) -> Double -> Double -> Double
binSearch f lo hi =
  if hi - lo < 10e-8 then
    mid
  else
    if fmid then
      binSearch f lo mid
    else
      binSearch f mid hi
  where
    mid  = (lo + hi) / 2.0
    fmid = f mid

main :: IO ()
main = do h <- return stdin
          [x1,y1,x2,y2] <- fmap ((map rd) . words) $ hGetLine h
          [vmax, t] <- fmap ((map rd) . words) $ hGetLine h
          [vx, vy] <- fmap ((map rd) . words) $ hGetLine h
          [wx, wy] <- fmap ((map rd) . words) $ hGetLine h
          let p1 = V2 x1 y1
          let p2 = V2 x2 y2
          let v = V2 vx vy
          let w = V2 wx wy
          putStrLn (show (binSearch (canMake p1 p2 vmax t v w) 0.0 2.0e32))
          return ()


On a strip of land of length $$$n$$$ there are $$$k$$$ air conditioners: the $$$i$$$-th air conditioner is placed in cell $$$a_i$$$ ($$$1 \le a_i \le n$$$). Two or more air conditioners cannot be placed in the same cell (i.e. all $$$a_i$$$ are distinct).Each air conditioner is characterized by one parameter: temperature. The $$$i$$$-th air conditioner is set to the temperature $$$t_i$$$.    Example of strip of length $$$n=6$$$, where $$$k=2$$$, $$$a=[2,5]$$$ and $$$t=[14,16]$$$. For each cell $$$i$$$ ($$$1 \le i \le n$$$) find it's temperature, that can be calculated by the formula $$$$$$\min_{1 \le j \le k}(t_j + |a_j - i|),$$$$$$where $$$|a_j - i|$$$ denotes absolute value of the difference $$$a_j - i$$$.In other words, the temperature in cell $$$i$$$ is equal to the minimum among the temperatures of air conditioners, increased by the distance from it to the cell $$$i$$$.Let's look at an example. Consider that $$$n=6, k=2$$$, the first air conditioner is placed in cell $$$a_1=2$$$ and is set to the temperature $$$t_1=14$$$ and the second air conditioner is placed in cell $$$a_2=5$$$ and is set to the temperature $$$t_2=16$$$. In that case temperatures in cells are:  temperature in cell $$$1$$$ is: $$$\min(14 + |2 - 1|, 16 + |5 - 1|)=\min(14 + 1, 16 + 4)=\min(15, 20)=15$$$;  temperature in cell $$$2$$$ is: $$$\min(14 + |2 - 2|, 16 + |5 - 2|)=\min(14 + 0, 16 + 3)=\min(14, 19)=14$$$;  temperature in cell $$$3$$$ is: $$$\min(14 + |2 - 3|, 16 + |5 - 3|)=\min(14 + 1, 16 + 2)=\min(15, 18)=15$$$;  temperature in cell $$$4$$$ is: $$$\min(14 + |2 - 4|, 16 + |5 - 4|)=\min(14 + 2, 16 + 1)=\min(16, 17)=16$$$;  temperature in cell $$$5$$$ is: $$$\min(14 + |2 - 5|, 16 + |5 - 5|)=\min(14 + 3, 16 + 0)=\min(17, 16)=16$$$;  temperature in cell $$$6$$$ is: $$$\min(14 + |2 - 6|, 16 + |5 - 6|)=\min(14 + 4, 16 + 1)=\min(18, 17)=17$$$. For each cell from $$$1$$$ to $$$n$$$ find the temperature in it.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the input. Then test cases follow. Before each test case, there is an empty line. Each test case contains three lines. The first line contains two integers $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) and $$$k$$$ ($$$1 \le k \le n$$$) — the length of the strip of land and the number of air conditioners respectively. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — positions of air conditioners on the strip of land. The third line contains $$$k$$$ integers $$$t_1, t_2, \ldots, t_k$$$ ($$$1 \le t_i \le 10^9$$$) — temperatures of air conditioners. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case output $$$n$$$ integers separated by space: temperatures of air in cells.

{-# LANGUAGE LambdaCase #-}

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

inf = 2*10^9

accTemp :: [Integer] -> [Integer]
accTemp acs = [] where
  calcTemp minprev ac = min (minprev + 1) ac

fillList :: Ord a => Int -> a ->  [(Int, a)] -> [a]
fillList n fillVal = go n . sort where
  go 0 _ = []
  go i [] = fillVal : go (i - 1) []
  go i vals@((j, x) : xs) = if n - i + 1 == j
    then x : go (i - 1) xs
    else fillVal : go (i - 1) vals

solve :: Int -> [Int] -> [Integer ] -> [Integer]
solve n pos temp = zipWith min l r where
  acs = fillList n inf $ zip pos temp
  calcTemp minprev ac = min (minprev + 1) ac
  l = scanl1 calcTemp acs
  r = reverse $ scanl1 calcTemp $ reverse acs

-- IO from https://github.com/byorgey/comprog-hs/blob/master/Scanner.hs
type Scanner = State [C.ByteString]

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

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

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

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

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

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

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

solveCase :: Scanner [Integer]
solveCase = do
  (n, k) <- pair int int
  pos <- replicateM k int
  temp <- replicateM k integer
  return $ solve n pos temp

main :: IO ()
main = C.interact $ runScanner (numberOf (C.pack . unwords . map show <$> solveCase)  ) >>> C.unlines

-- main :: IO ()
-- main = do
--   q <- readLn
--   replicateM_ q $ do
--     getLine
--     [n, _] <- map read . words <$> getLine :: IO [Int]
--     pos <- map read . words <$> getLine :: IO [Int]
--     temp <- map read . words <$> getLine :: IO [Integer]
--     let ans = solve n $ M.fromList (zip pos temp)
--     putStrLn $ unwords $ map show ans

{-# LANGUAGE LambdaCase #-}

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

inf = 2*10^9

accTemp :: [Integer] -> [Integer]
accTemp acs = [] where
  calcTemp minprev ac = min (minprev + 1) ac

solve :: Int -> M.IntMap Integer -> [Integer]
solve n acMap = zipWith min l r where
  find x = M.findWithDefault inf x acMap
  acs = map find [1..n]
  calcTemp minprev ac = min (minprev + 1) ac
  l = scanl1 calcTemp acs
  r = reverse $ scanl1 calcTemp $ reverse acs

-- IO from https://github.com/byorgey/comprog-hs/blob/master/Scanner.hs
type Scanner = State [C.ByteString]

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

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

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

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

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

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

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

solveCase :: Scanner [Integer]
solveCase = do
  (n, k) <- pair int int
  pos <- replicateM k int
  temp <- replicateM k integer
  return $ solve n $ M.fromList (zip pos temp)

main :: IO ()
main = C.interact $ runScanner (numberOf (C.pack . unwords . map show <$> solveCase)  ) >>> C.unlines

-- main :: IO ()
-- main = do
--   q <- readLn
--   replicateM_ q $ do
--     getLine
--     [n, _] <- map read . words <$> getLine :: IO [Int]
--     pos <- map read . words <$> getLine :: IO [Int]
--     temp <- map read . words <$> getLine :: IO [Integer]
--     let ans = solve n $ M.fromList (zip pos temp)
--     putStrLn $ unwords $ map show ans

{-# LANGUAGE LambdaCase #-}

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

-- https://github.com/byorgey/comprog-hs/blob/master/ScannerBS.hs
type Scanner = State [C.ByteString]

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

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

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

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

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

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

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

main :: IO ()
main = C.interact $ runScanner (numberOf (C.pack . unwords . map show <$> testCase)) >>> C.unlines

testCase :: Scanner [Int]
testCase = do
  (n, k) <- pair int int
  as <- replicateM k int
  ts <- replicateM k int
  return $ solve [[n, k], as, ts]

solve :: [[Int]] -> [Int]
solve [[n, k], as, ts] = zipWith min (compute xs) (reverse . compute . reverse $ xs)
  where
    xs = tail . snd . foldr upd (n + 1, []) . sort $ ((0, 0) : zip as ts)
    upd (a, t) (i, xs) = (a, t : replicate (i - a - 1) inf ++ xs)
    inf = 2 * 10 ^ 9

compute :: [Int] -> [Int]
compute = scanl1 (\p x -> min (p + 1) x)


You are given a permutation $$$p_1, p_2, \ldots, p_n$$$ of length $$$n$$$ of numbers $$$0, \ldots, n - 1$$$. Count the number of subsegments $$$1 \leq l \leq r \leq n$$$ of this permutation such that $$$mex(p_l, p_{l+1}, \ldots, p_r) > med(p_l, p_{l+1}, \ldots, p_r)$$$.$$$mex$$$ of $$$S$$$ is the smallest non-negative integer that does not occur in $$$S$$$. For example: $$$mex({0, 1, 2, 3}) = 4$$$ $$$mex({0, 4, 1, 3}) = 2$$$ $$$mex({5, 4, 0, 1, 2}) = 3$$$$$$med$$$ of the set $$$S$$$ is the median of the set, i.e. the element that, after sorting the elements in non-decreasing order, will be at position number $$$\left \lfloor{ \frac{|S| + 1}{2} } \right \rfloor$$$ (array elements are numbered starting from $$$1$$$ and here $$$\left \lfloor{v} \right \rfloor$$$ denotes rounding $$$v$$$ down.). For example: $$$med({0, 1, 2, 3}) = 1$$$ $$$med({0, 4, 1, 3}) = 1$$$ $$$med({5, 4, 0, 1, 2}) = 2$$$A sequence of $$$n$$$ numbers is called a permutation if it contains all the numbers from $$$0$$$ to $$$n - 1$$$ exactly once.

The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$), the number of test cases. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$), the length of the permutation $$$p$$$. The second line of each test case contains exactly $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$0 \leq p_i \leq n - 1$$$), elements of permutation $$$p$$$. 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 answer in a single line: the number of subsegments $$$1 \leq l \leq r \leq n$$$ of this permutation such that $$$mex(p_l, p_{l+1}, \ldots, p_r) > med(p_l, p_{l+1}, \ldots, p_r)$$$.

NoteThe first test case contains exactly one subsegment and $$$mex({0}) = 1 > med({0}) = 0$$$ on it.In the third test case, on the following subsegments: $$$[1, 0]$$$, $$$[0]$$$, $$$[1, 0, 2]$$$ and $$$[0, 2]$$$, $$$mex$$$ is greater than $$$med$$$.In the fourth test case, on the following subsegments: $$$[0, 2]$$$, $$$[0]$$$, $$$[0, 2, 1]$$$ and $$$[0, 2, 1, 3]$$$, $$$mex$$$ greater than $$$med$$$.

{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections  #-}
{-# LANGUAGE Strict #-}
-- {-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}
#ifndef DEBUG
{-# LANGUAGE Safe #-}
#endif

import qualified Data.ByteString.Char8 as B8
import qualified Data.String as S

import Control.Arrow ((>>>))
import Data.Functor ((<&>))
import Data.Maybe
import qualified Data.Traversable as T

import qualified Control.Applicative as A
import qualified Control.Monad as M
import qualified Control.Monad.State as MS
import qualified Control.Monad.Trans as MT
import qualified Control.Monad.Trans.Maybe as M

import qualified Data.List as L
import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import qualified Data.IntSet as IS
import qualified Data.IntMap as IM
import qualified Data.Set as S
import Data.List (sortBy, sortOn)

import Data.Char
import Data.Int

import System.IO (stdin, stdout, hFlush)
import Text.Printf

#ifdef DEBUG
import Debug.Trace (trace, traceM, traceShowM)
debug = flip trace

tracing t x = trace (t ++ " = " ++ show x) x
debugging x t = tracing t x

tracingM t x = traceM $ t ++ " = " ++ show x

#else

debug x _ = x
trace _ x = x
tracing _ x = x
debugging x _ = x

traceM _ = pure ()
tracingM _ _ = pure ()
#endif

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

readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))

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

readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

{- writing -}
putsYesNo :: Bool -> IO ()
putsYesNo value = do
    let result :: String =
            if value
                then "YES"
                else "NO"
    printf "%s\n" result

{- aux -}
modifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray arr ix f = do
    value <- MA.readArray arr ix
    MA.writeArray arr ix $ f value

{- solution -}

solve :: Int -> [Int] -> Int64
solve n ps = flip MS.evalState (n + 1, -1) $ do
    let pArr :: UA.UArray Int Int = UA.listArray (0, n - 1) ps
    let pInvArr :: UA.UArray Int Int = UA.array (0, n - 1) $ L.zipWith (\i p -> (p, i)) [0 ..] ps
    cnts <- M.forM [1 .. n] $ \len -> do
        let midLen = (len + 1) `div` 2
        let idx = pInvArr UA.! (midLen - 1)
        MS.modify $ \(l, r) -> (min l idx, max r idx)
        ~(l, r) <- MS.get <&> tracing "(l, r)"
        let maxR = tracing "maxR" $ min (l + len - 1) (n - 1)
            minL = tracing "minL" $ max (r - len + 1) 0
            mLLength = tracing "mLLength" $ (maxR - minL + 1)
            count = tracing "count" $ max 0 $ mLLength - len + 1

        return . fromIntegral $ count
    tracingM "cnts" $ seq cnts cnts
    return $ sum cnts

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    M.replicateM_ t $ do
        n <- B8.getLine <&> readIntB8
        ps <- B8.getLine <&> readIntB8s
        let answer = solve n ps
        printf "%lld\n" answer
        traceM "-----------"

{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections  #-}
{-# LANGUAGE Strict #-}
-- {-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}
#ifndef DEBUG
{-# LANGUAGE Safe #-}
#endif

import qualified Data.ByteString.Char8 as B8
import qualified Data.String as S

import Control.Arrow ((>>>))
import Data.Functor ((<&>))
import Data.Maybe
import qualified Data.Traversable as T

import qualified Control.Applicative as A
import qualified Control.Monad as M
import qualified Control.Monad.State as MS
import qualified Control.Monad.Trans as MT
import qualified Control.Monad.Trans.Maybe as M

import qualified Data.List as L
import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import qualified Data.IntSet as IS
import qualified Data.IntMap as IM
import qualified Data.Set as S
import Data.List (sortBy, sortOn)

import Data.Char
import Data.Int

import System.IO (stdin, stdout, hFlush)
import Text.Printf

#ifdef DEBUG
import Debug.Trace (trace, traceM, traceShowM)
debug = flip trace

tracing t x = trace (t ++ " = " ++ show x) x
debugging x t = tracing t x

tracingM t x = traceM $ t ++ " = " ++ show x

#else

debug x _ = x
trace _ x = x
tracing _ x = x
debugging x _ = x

traceM _ = pure ()
tracingM _ _ = pure ()
#endif

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

readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))

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

readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

{- writing -}
putsYesNo :: Bool -> IO ()
putsYesNo value = do
    let result :: String =
            if value
                then "YES"
                else "NO"
    printf "%s\n" result

{- aux -}
modifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray arr ix f = do
    value <- MA.readArray arr ix
    MA.writeArray arr ix $ f value

{- solution -}

solve :: Int -> [Int] -> Int64
solve n ps = flip MS.evalState (n + 1, -1) $ do
    let pArr :: UA.UArray Int Int = UA.listArray (0, n - 1) ps
    let pInvArr :: UA.UArray Int Int = UA.array (0, n - 1) $ L.zipWith (\i p -> (p, i)) [0 ..] ps
    cnts <- M.forM [1 .. n] $ \len -> do
        let midLen = (len + 1) `div` 2
        let idx = pInvArr UA.! (midLen - 1)
        MS.modify $ \(l, r) -> (min l idx, max r idx)
        ~(l, r) <- MS.get <&> tracing "(l, r)"
        let maxR = tracing "maxR" $ min (l + len - 1) (n - 1)
            minL = tracing "minL" $ max (r - len + 1) 0
            mLLength = tracing "mLLength" $ (maxR - minL + 1)
            count = tracing "count" $ mLLength - len + 1

        return . fromIntegral $ count
    tracingM "cnts" $ seq cnts cnts
    return $ sum cnts

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    M.replicateM_ t $ do
        n <- B8.getLine <&> readIntB8
        ps <- B8.getLine <&> readIntB8s
        let answer = solve n ps
        printf "%lld\n" answer
        traceM "-----------"


You are given two positive integers $$$a$$$ and $$$b$$$.In one move, you can change $$$a$$$ in the following way:  Choose any positive odd integer $$$x$$$ ($$$x > 0$$$) and replace $$$a$$$ with $$$a+x$$$;  choose any positive even integer $$$y$$$ ($$$y > 0$$$) and replace $$$a$$$ with $$$a-y$$$. You can perform as many such operations as you want. You can choose the same numbers $$$x$$$ and $$$y$$$ in different moves.Your task is to find the minimum number of moves required to obtain $$$b$$$ from $$$a$$$. It is guaranteed that you can always obtain $$$b$$$ from $$$a$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is given as two space-separated integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case, print the answer — the minimum number of moves required to obtain $$$b$$$ from $$$a$$$ if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain $$$b$$$ from $$$a$$$.

NoteIn the first test case, you can just add $$$1$$$.In the second test case, you don't need to do anything.In the third test case, you can add $$$1$$$ two times.In the fourth test case, you can subtract $$$4$$$ and add $$$1$$$.In the fifth test case, you can just subtract $$$6$$$.

module Main where

import Control.Monad
import Data.List

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

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

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [x, y] <- getIntList
        print $ f x y

f :: Int -> Int -> Int
f x y
    | x == y = 0
    | or [(sameP x y) && (x > y), not (sameP x y) && (x < y)] = 1
    | otherwise = 2

sameP :: Int -> Int -> Bool
sameP x y = odd x == odd y

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

main = getLine >>= test.read
test 0 = return ()
test n = getLine >>= print.(\(a:b:_) -> solve a b).map read.words >> test (n - 1)

solve a b
	| a == b = 0
	| even (a - b) = 1 + fromEnum (a < b)
	| otherwise = 1 + fromEnum (a > b)

import Control.Monad
main :: IO ()
main = do
  n <- readLn
  replicateM_ n routine

routine :: IO ()
routine = do
  [a,b] <- (map read.words) <$> getLine
  print $ solve (a-b)

solve :: Int -> Int
solve 0 = 0
solve n
  {-|n>=8 = (n `div` 8) + solve (n `mod` 8)
  |n<=(-9) = (n `div` (-9)) + solve (n `mod` (-9))-}
  |(n>0) && even n = 1
  |(n<0) && odd n = 1
  |otherwise = 2

{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
import Data.Ord
import Data.Int
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 Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if s then
                aux s
            else
                return id
        else
            liftM ((.) $ showChar x) $ aux False
    in liftM (flip ($) []) $ aux True

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

class IOInteract a where
    convertEither :: String -> Either String a
    toShowS :: a -> String -> String
    toShow :: a -> String
    toShow x = toShowS x []

instance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where
    convertEither = convertEitherp (undefined :: flag)
    toShowS = toShowSp (undefined :: flag)

type family IOType x where
    IOType String = HString
    IOType [x] = HList
    IOType x = HNormal

class IOInteractp flag a where
    convertEitherp :: flag -> String -> Either String a
    toShowSp :: flag -> a -> String -> String

instance (Show a, Read a) => IOInteractp HNormal a where
    convertEitherp _ x = readEither x
    toShowSp _ x = shows x

instance IOInteractp HString String where
    convertEitherp _ x = Right x
    toShowSp _ x = showString x

instance (IOInteract a) => IOInteractp HList [a] where
    convertEitherp _ x = mapM convertEither $ words x
    toShowSp _ [] = id
    toShowSp _ (x : []) = toShowS x
    toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs

get :: IOInteract a => EIO a
get = ExceptT $ liftM convertEither getToken
put :: IOInteract a => a -> EIO ()
put = lift . putStr . toShow
putln :: IOInteract a => a -> EIO ()
putln = lift . putStrLn . toShow

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

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

f1 :: EIO ()
f1 = do
    (a, b) <- liftM2 (,) get get
    putln $ f2 a b

f2 :: Int64 -> Int64 -> Int
f2 a b =    if b > a then
                if (mod (b - a) 2) == 1 then
                    1
                else
                    2
            else
                if b < a then
                    if (mod (b - a) 2) == 1 then
                        2
                    else
                        1
                else
                    0

import Control.Monad (replicateM_)

solve :: Int -> Int -> Int
solve x y | x == y = 0
          | x < y && x `mod` 2 /= y `mod` 2 = 1
          | x > y && x `mod` 2 == y `mod` 2 = 1
          | otherwise = 2

main :: IO ()
main = readLn >>= flip replicateM_ (getLine >>= print . (\[x,y] -> solve x y) . map read . words)

import Control.Monad

readInts :: IO [Int]
readInts = do
    ls <- fmap words getLine
    return $ map read ls

main = do
    [n] <- readInts
    replicateM_ n $ do
        [a,b] <- readInts
        print $ solve a b

solve a b
    | a == b = 0
    | a > b  = if mod (a-b) 2 == 0 then 1 else 2
    | a < b  = if mod (b-a) 2 == 1 then 1 else 2

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

process a b | a==b = 0
            | b>a && odd (b-a) =1
	    | b>a = 2
	    | a>b && even (b-a) = 1
	    | otherwise = 2

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

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

--ghc 7.10

countMoves :: (Integral a) => (a,a) -> a
countMoves (a,b)
    | a < b = 1 + e
    | a > b = 2 - e
    | otherwise = 0
    where e = if even (a-b) then 1 else 0

readPair :: String -> (Int,Int)
readPair str = (a,b)
    where [a,b] = map read . words $ str

main = do
    nStr <- getLine
    contents <- getContents
    let qPairs = map readPair . lines $ contents
    sequence . map print $ map countMoves qPairs

solve :: Int -> Int -> Int
solve a b
  | a == b = 0
  | b > a && odd (b-a) = 1
  | b > a && even (b-a) = 2
  | b < a && odd (a-b) = 2
  | b < a && even (a-b) = 1

parse :: String -> String
parse line = show $ solve a b
  where [a, b] = map (\x -> read x :: Int) $ words line

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

import Control.Monad
main :: IO ()
main = do
  n <- readLn
  replicateM_ n routine

routine :: IO ()
routine = do
  [a,b] <- (map read.words) <$> getLine
  print $ solve (a-b)

solve :: Int -> Int
solve 0 = 0
solve n
  |n>=8 = (n `div` 8) + solve (n `mod` 8)
  |n<=(-9) = (n `div` (-9)) + solve (n `mod` (-9))
  |(n>0) && even n = 1
  |(n<0) && odd n = 1
  |otherwise = 2

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

process a b | a==b = 0
            | even a && b>a = 1
	    | even a = 2
	    | odd a && a<b = 1
	    | otherwise = 2

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

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


Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties:  the upper half of matrix c (rows with numbers from 1 to x) exactly matches b;  the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?

The first line contains two integers, n and m (1 ≤ n, m ≤ 100). Each of the next n lines contains m integers — the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≤ aij ≤ 1) — the i-th row of the matrix a.

In the single line, print the answer to the problem — the minimum number of rows of matrix b.

NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001

{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import Text.Printf

readInt = ( readLn :: IO Int )
getInts = map ( read :: String -> Int ) . words <$> getLine

mp [ a, b ] = ( a, b )

main = do
	[ h, w ] <- getInts
	rows <- replicateM h getInts

	let
		mirrors rs
			| length rs < h = mirrors $ rs ++ reverse rs
			| otherwise = rs

	print $ head $ filter ( ( == rows ) . mirrors . ( flip take rows ) ) [ 1 .. h ]

input :: Int -> [String] -> IO ([String])
input 0 acc = return acc
input n acc = do
              r <- getLine
              input (n-1) (r:acc)

symmetric matrix | odd (length matrix) = False
                 | otherwise = (top == reverse bottom)
                 where
                     top = take (div n 2) matrix
                     bottom = drop (div n 2) matrix
                     n = length matrix

fold :: [String] -> Int
fold matrix | symmetric matrix = fold (take (div (length matrix) 2) matrix)
            | otherwise        = length matrix

main = do
  s <- getLine
  let n = read (head (words s)) ::Int
  matr <- (input n [])
  print (fold matr)

import Control.Monad

solve :: [[Int]] -> Int

solve m | odd rowCount = rowCount
        | upperPart == reverse lowerPart = solve upperPart
        | otherwise = rowCount

    where rowCount = length m
          upperPart = take (rowCount `div` 2) m
          lowerPart = drop (rowCount `div` 2) m

main = do
    [n,m] <- fmap (map read . words) getLine
    as <- forM [1..n] (\_ -> fmap (map read . words) getLine)
    print $ solve as

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

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

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

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

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

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

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

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

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

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

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

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

hash :: [Int] -> Integer
hash [] = 0
hash (x:xs) = (fi x + 12347 * hash xs) `mod` 0x3de1f1ed

solve :: (Eq a) => [a] -> Int
solve xs = case n `quotRem` 2 of
	(k,0) -> let (x1, x2) = splitAt k xs in
		if reverse x1 == x2 then solve x2 else n
	_ -> n
	where n = length xs

main :: IO ()
main = do
	[n,_] <- inputInts
	mat <- replicateM n (hash <$> inputInts)
	print $ solve mat


Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting.Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e.  or  (or both).Pari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover.They have agreed to give you their graph and you need to find two disjoint subsets of its vertices A and B, such that both A and B are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself).

The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the prize graph, respectively. Each of the next m lines contains a pair of integers ui and vi (1  ≤  ui,  vi  ≤  n), denoting an undirected edge between ui and vi. It's guaranteed the graph won't contain any self-loops or multiple edges.

If it's impossible to split the graph between Pari and Arya as they expect, print "-1" (without quotes). If there are two disjoint sets of vertices, such that both sets are vertex cover, print their descriptions. Each description must contain two lines. The first line contains a single integer k denoting the number of vertices in that vertex cover, and the second line contains k integers — the indices of vertices. Note that because of m ≥ 1, vertex cover cannot be empty.

NoteIn the first sample, you can give the vertex number 2 to Arya and vertices numbered 1 and 3 to Pari and keep vertex number 4 for yourself (or give it someone, if you wish).In the second sample, there is no way to satisfy both Pari and Arya.

{-# LANGUAGE FlexibleContexts #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Char
import Data.List
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

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

main = do
  [n, m] <- getInts
  es <- replicateM m $ (\[a, b] -> (a, b)) <$> getInts

  let
    g = accumArray (flip (:)) [] (1, n) $ es ++ map swap es

    (ok, m) = flip runState IntMap.empty $
        and <$> (forM [1..n] $ \u -> do
          m <- get
          if u `IntMap.notMember` m
             then dfs True u
             else return True)
      where
        dfs c u = do
          modify $ IntMap.insert u c
          and <$> (forM (g!u) $ \v -> do
            m <- get
            case v `IntMap.lookup` m of
              Nothing -> dfs (not c) v
              Just c' -> return $ c /= c')

    s1 = map fst $ filter (\x -> snd x) $ IntMap.assocs m
    s2 = map fst $ filter (\x -> not $ snd x) $ IntMap.assocs m

  if ok
    then do
      print $ length s1
      putStrLn $ unwords $ map show s1
      print $ length s2
      putStrLn $ unwords $ map show s2
    else
      print $ -1


There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i < n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.

The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.

Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl.  Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.

NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.

import Control.Monad (liftM)

solve :: Int -> Int -> String
solve 0 m  =  replicate m 'G'
solve n 0  =  replicate n 'B'
solve n m
  | n > m  =  'B' : 'G' : solve (n - 1) (m - 1)
  | otherwise  =  'G' : 'B' : solve (n - 1) (m - 1)

main :: IO ()
main  =  do
    [n, m]  <-  liftM (map read . words) (readFile "input.txt")
    writeFile "output.txt" $ solve n m

import Control.Applicative
import Control.Monad
import System.IO

main = do

  hin  <- openFile "input.txt"  ReadMode
  hout <- openFile "output.txt" WriteMode

  [n,m] <- map read.words <$> hGetLine hin

  if n>m
     then hPutStrLn hout $ ([1..m]>>"BG")++replicate (n-m) 'B'
     else hPutStrLn hout $ ([1..n]>>"GB")++replicate (m-n) 'G'

  hClose hin
  hClose hout

import Control.Applicative
import Control.Monad
import System.IO

main = do

  hin  <- openFile "input.txt"  ReadMode
  hout <- openFile "output.txt" WriteMode

  [n,m] <- map read.words <$> hGetLine hin

  if n>m
     then hPutStrLn hout $ ([1..m]>>"BG")++replicate (n-m) 'B'
     else hPutStrLn hout $ ([1..n]>>"GB")++replicate (n-m) 'G'

  hClose hin
  hClose hout