And while Mishka is enjoying her trip...Chris is a little brown bear. No one knows, where and when he met Mishka, but for a long time they are together (excluding her current trip). However, best friends are important too. John is Chris' best friend.Once walking with his friend, John gave Chris the following problem:At the infinite horizontal road of width w, bounded by lines y = 0 and y = w, there is a bus moving, presented as a convex polygon of n vertices. The bus moves continuously with a constant speed of v in a straight Ox line in direction of decreasing x coordinates, thus in time only x coordinates of its points are changing. Formally, after time t each of x coordinates of its points will be decreased by vt.There is a pedestrian in the point (0, 0), who can move only by a vertical pedestrian crossing, presented as a segment connecting points (0, 0) and (0, w) with any speed not exceeding u. Thus the pedestrian can move only in a straight line Oy in any direction with any speed not exceeding u and not leaving the road borders. The pedestrian can instantly change his speed, thus, for example, he can stop instantly.Please look at the sample note picture for better understanding.We consider the pedestrian is hit by the bus, if at any moment the point he is located in lies strictly inside the bus polygon (this means that if the point lies on the polygon vertex or on its edge, the pedestrian is not hit by the bus).You are given the bus position at the moment 0. Please help Chris determine minimum amount of time the pedestrian needs to cross the road and reach the point (0, w) and not to be hit by the bus.

The first line of the input contains four integers n, w, v, u (3 ≤ n ≤ 10 000, 1 ≤ w ≤ 109, 1 ≤ v,  u ≤ 1000) — the number of the bus polygon vertices, road width, bus speed and pedestrian speed respectively. The next n lines describes polygon vertices in counter-clockwise order. i-th of them contains pair of integers xi and yi ( - 109 ≤ xi ≤ 109, 0 ≤ yi ≤ w) — coordinates of i-th polygon point. It is guaranteed that the polygon is non-degenerate.

Print the single real t — the time the pedestrian needs to croos the road and not to be hit by the bus. The answer is considered correct if its relative or absolute error doesn't exceed 10 - 6.

NoteFollowing image describes initial position in the first sample case:

module Main where

import Control.Monad
import Control.Monad.State
import Data.Int
import Data.List (foldl', sortBy)
import Text.Printf
import qualified Data.ByteString.Lazy.Char8 as L

type Velocity = Int64

data Point = Point { getX :: Int64
                   , getY :: Int64
                   } deriving (Show, Eq)

ordByY :: Point -> Point -> Ordering
ordByY (Point x1 y1) (Point x2 y2) | y1 < y2 = LT
                                   | y1 > y2 = GT
                                   | otherwise = compare x1 x2

data Bus = Bus [Point] Velocity
         deriving (Show, Eq)

data Test = Test { bus :: Bus
                 , pedestrian :: Velocity
                 , width :: Int64
                 } deriving (Show, Eq)

fastPath :: Test -> Double
fastPath (Test (Bus ps v) u w) | all inTime ps = (fromIntegral w) / (fromIntegral u)
                               | otherwise = -1.0
    where inTime (Point x y) = y * v <= x * u

slowPath :: Test -> Double
slowPath (Test (Bus ps v) u w) = pt + (fromIntegral $ w - py) / (fromIntegral u)
    where (py, pt) = foldl' update (0, 0.0) (sortBy ordByY ps)

          update :: (Int64, Double) -> Point -> (Int64, Double)
          update (py, pt) (Point bx by) = (by, max bt pt')
              where bt = (fromIntegral bx) / (fromIntegral v)
                    pt' = pt + (fromIntegral $ by - py) / (fromIntegral u)

solve :: Test -> Double
solve test | fp > -1.0 = fp
           | otherwise = sp
    where fp = fastPath test
          sp = slowPath test

test0 = Test { bus = Bus [Point 1 2, Point 3 1, Point 4 3, Point 3 4, Point 1 4] 1
             , pedestrian = 2
             , width = 5
             }

type Tokenizer = State [L.ByteString]

nextInt :: Tokenizer Int
nextInt = state $ \(s:ss) -> case L.readInt s of
                               Just (x, _) -> (x, ss)
                               Nothing -> error $ "Can't parse Int:" ++ (show s)

nextInt64 :: Tokenizer Int64
nextInt64 = liftM fromIntegral nextInt

go :: Tokenizer Double
go = do
  n <- nextInt
  w <- nextInt64
  v <- nextInt64
  u <- nextInt64
  ps <- replicateM n (liftM2 Point nextInt64 nextInt64)
  return $ solve Test { bus = Bus ps v, pedestrian = u, width = w }

main :: IO ()
main = do
  input <- L.getContents
  let result = evalState go (L.words input)
  printf "%.7f\n" result

import Control.Monad
import Data.Int
import Data.Maybe
import Data.Ratio
import Text.Printf
import qualified Data.ByteString.Char8 as B

intLine :: IO [Integer]
intLine = fmap (map (fromIntegral . fst . fromJust . B.readInt) . B.words) B.getLine

main = do
    [n,w,v,u] <- intLine
    ts <- replicateM (fromIntegral n) $ do
        [x,y] <- intLine
        return $ x % v - y % u;
    let t = if minimum ts >= 0 then 0 else max 0 (maximum ts)
    let res = t + w % u
    putStrLn $ printf "%.12f" $ (fromRational res :: Double)

import Control.Monad
import Data.Int
import Data.Maybe
import Data.Ratio
import Text.Printf
import qualified Data.ByteString.Char8 as B

intLine :: IO [Integer]
intLine = fmap (map (fromIntegral . fst . fromJust . B.readInt) . B.words) B.getLine

main = do
    [n,w,v,u] <- intLine
    ts <- replicateM (fromIntegral n) $ do
        [x,y] <- intLine
        return $ fromIntegral x - fromIntegral v * y % u;
    let t = if minimum ts >= 0 then 0 else maximum ts
    let res = t + w % u
    putStrLn $ printf "%.12f" $ (fromRational res :: Double)

import Control.Monad
import Data.Int
import Data.Maybe
import Data.Ratio
import Text.Printf
import qualified Data.ByteString.Char8 as B

intLine :: IO [Integer]
intLine = fmap (map (fromIntegral . fst . fromJust . B.readInt) . B.words) B.getLine

main = do
    [n,w,v,u] <- intLine
    ts <- replicateM (fromIntegral n) $ do
        [x,y] <- intLine
        return $ fromIntegral x - fromIntegral v * y % u;
    let t = if minimum ts >= 0 then 0 else max 0 (maximum ts)
    let res = t + w % u
    putStrLn $ printf "%.12f" $ (fromRational res :: Double)


You are given two integers $$$l$$$ and $$$r$$$, where $$$l < r$$$. We will add $$$1$$$ to $$$l$$$ until the result is equal to $$$r$$$. Thus, there will be exactly $$$r-l$$$ additions performed. For each such addition, let's look at the number of digits that will be changed after it.For example:   if $$$l=909$$$, then adding one will result in $$$910$$$ and $$$2$$$ digits will be changed;  if you add one to $$$l=9$$$, the result will be $$$10$$$ and $$$2$$$ digits will also be changed;  if you add one to $$$l=489999$$$, the result will be $$$490000$$$ and $$$5$$$ digits will be changed. Changed digits always form a suffix of the result written in the decimal system.Output the total number of changed digits, if you want to get $$$r$$$ from $$$l$$$, adding $$$1$$$ each time.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case is characterized by two integers $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le 10^9$$$).

For each test case, calculate the total number of changed digits if you want to get $$$r$$$ from $$$l$$$, adding one each time.

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

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

    (putStr . unlines . map solve) tcs

readTC = do
    [l, r] <- readIListLn
    return (l, r)

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

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

solve (l, r) = show $ sum . take 20 $ ps
  where
    ps = zipWith (flip (-)) (iterate (`div` 10) l) (iterate (`div` 10) r)

import Control.Arrow ((>>>))

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

solve :: [Int] -> Int
solve [l, r] = cost r - cost l
  where
    cost = sum . takeWhile (> 0) . iterate (`div` 10)

--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.Int

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

cnt :: Int -> Int64
cnt x = f (fromIntegral x) x
  where
    f !acc 0 = acc
    f !acc !x = let !t = div x 10 in f (acc + fromIntegral t) t

test' :: Int -> Int -> Int64
test' l r = cnt r - cnt l

nl = char7 '\n'
test :: Builder -> Int -> [Int] -> Builder
test buf 0 _ = buf
test buf nt (a:b:xs) = test (buf <> int64Dec (test' a b) <> nl) (pred nt) xs

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

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


Ashish and Vivek play a game on a matrix consisting of $$$n$$$ rows and $$$m$$$ columns, where they take turns claiming cells. Unclaimed cells are represented by $$$0$$$, while claimed cells are represented by $$$1$$$. The initial state of the matrix is given. There can be some claimed cells in the initial state.In each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends.If Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves.

The first line consists of a single integer $$$t$$$ $$$(1 \le t \le 50)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case consists of two space-separated integers $$$n$$$, $$$m$$$ $$$(1 \le n, m \le 50)$$$ — the number of rows and columns in the matrix. The following $$$n$$$ lines consist of $$$m$$$ integers each, the $$$j$$$-th integer on the $$$i$$$-th line denoting $$$a_{i,j}$$$ $$$(a_{i,j} \in \{0, 1\})$$$.

For each test case if Ashish wins the game print "Ashish" otherwise print "Vivek" (without quotes).

NoteFor the first case: One possible scenario could be: Ashish claims cell $$$(1, 1)$$$, Vivek then claims cell $$$(2, 2)$$$. Ashish can neither claim cell $$$(1, 2)$$$, nor cell $$$(2, 1)$$$ as cells $$$(1, 1)$$$ and $$$(2, 2)$$$ are already claimed. Thus Ashish loses. It can be shown that no matter what Ashish plays in this case, Vivek will win. For the second case: Ashish claims cell $$$(1, 1)$$$, the only cell that can be claimed in the first move. After that Vivek has no moves left.For the third case: Ashish cannot make a move, so Vivek wins.For the fourth case: If Ashish claims cell $$$(2, 3)$$$, Vivek will have no moves left.

import Control.Monad
import Data.List

solve :: [[Int]] -> String
solve x = let free_rows = countTrue (map isArrayFree x)
              free_cols = countTrue (map isArrayFree $ transpose x) in
                  if even (min free_rows free_cols)
                      then "Vivek"
                      else "Ashish"

countTrue :: [Bool] -> Int
countTrue = length . filter (==True)

isArrayFree :: [Int] -> Bool
isArrayFree x = not $ elem 1 x

main = do
  t <- read <$> getLine
  replicateM_ t testCase

testCase = do
    (n:_)  <- map read . words <$> getLine
    matrix <- replicateM n (map read . words <$> getLine)
    putStrLn (solve matrix)

{-# LANGUAGE BlockArguments #-}

import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.List

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t do
    [n, _] <- getInts
    matrix <- replicateM n getInts
    let steps = free matrix `min` free (transpose matrix)
        winner = ["Vivek", "Ashish"] !! mod steps 2
    putStrLn winner
  where
    free = length . filter (not . elem 1)

getInts :: IO [Int]
getInts = go <$> BS.getLine
  where
    go s = case BS.readInt s of
      Nothing -> []
      Just (x, s') -> x : go (BS.drop 1 s')

import Control.Monad
import Data.Array

main :: IO ()
main = do
	n <- readLn
	replicateM_ n routine

routine :: IO ()
routine = do
	[n,m] <- (map read.words) <$> getLine
	xs <- replicateM n ((map read.words) <$> getLine)
	putStrLn $ if solve n m xs then "Vivek" else "Ashish"

solve :: Int -> Int -> [[Int]] -> Bool
solve n m xs = even $ min ns ms
	where
		arr = listArray ((1,1),(n,m)) $ concat xs
		ns = length $ filter not [ any (== 1) [ arr!(i,j) | j <- [1..m]] | i <- [1..n]]
		ms = length $ filter not [ any (== 1) [ arr!(i,j) | i <- [1..n]] | j <- [1..m]]

import           Control.Monad
import           Data.List

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

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

countOptions :: [[Int]] -> Int
countOptions []     = 0
countOptions (x:xs) = (if all (==0) x then 1 else 0) + countOptions xs

solve :: IO()
solve = do
  [n,m] <- readInts
  r <- replicateM n readInts
  let c = transpose r
  let rZeros = countOptions r
  let cZeros = countOptions c
  let zeros = min rZeros cZeros
  putStrLn (if even zeros then "Vivek" else "Ashish")

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE BangPatterns #-}

import Data.List

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

split = _split [] ""

(|>) = flip ($)

boolToInt bool
  | bool = 1
  | otherwise = 0

main = do
  input <- getContents
  let _:vals = read <$> split input :: [Int]
      res = vals |> unfoldr (\case
        []  -> Nothing
        n:m:rest0   ->
          let (cells, rest1) = splitAt (n*m) rest0
              rows = cells |> unfoldr (\case
                []  -> Nothing
                ls  -> Just $ splitAt m ls
                )
              numAvailableRows = sum $ boolToInt <$> isZeroRows where
                isZeroRows = all (== 0) <$> rows
              numAvailableCols = sum $ zeroCols where
                zeroCols = (\x -> 1-x) <$> oneCols
                oneCols = foldl (\acc ls -> uncurry max <$> zip acc ls) allZeros rows where
                  allZeros = replicate m 0
              numTurns = min numAvailableRows numAvailableCols
              subres = if numTurns `mod` 2 == 1 then "Ashish" else "Vivek"
          in Just (subres, rest1)
        )
  sequence_ (putStrLn <$> res)

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE BangPatterns #-}

import Data.List

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

split = _split [] ""

(|>) = flip ($)

boolToInt bool
  | bool = 1
  | otherwise = 0

main = do
  input <- getContents
  let _:vals = read <$> split input :: [Int]
      res = vals |> unfoldr (\case
        []  -> Nothing
        n:m:rest0   ->
          let (cells, rest1) = splitAt (n*m) rest0
              rows = cells |> unfoldr (\case
                []  -> Nothing
                ls  -> Just $ splitAt m ls
                )
              numAvailableRows = sum $ boolToInt <$> isZeroRows where
                isZeroRows = all (== 0) <$> rows
              numAvailableCols = sum $ zeroCols where
                zeroCols = (\x -> 1-x) <$> oneCols
                oneCols = foldl (\acc ls -> uncurry max <$> zip acc ls) allZeros rows where
                  allZeros = replicate n 0
              numTurns = min numAvailableRows numAvailableCols
              subres = if numTurns `mod` 2 == 1 then "Ashish" else "Vivek"
          in Just (subres, rest1)
        )
  sequence_ (putStrLn <$> res)


Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$.    An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).

The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d < n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.

Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).

NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.

import           Control.Monad

isInside :: (Int, Int) -> (Int, Int) -> Bool
isInside (n, d) (x, y) = su >= down && su <= up && di >= right && di <= left
  where
    su = x + y
    di = x - y
    down = d
    up = (2 * n - d)
    left = d
    right = (-d)

main :: IO ()
main = do
  [n, d] <- map (read :: String -> Int) . words <$> getLine
  m <- (read :: String -> Int) <$> getLine
  replicateM_ m $ do
    [x, y] <- map (read :: String -> Int) . words <$> getLine
    putStrLn $ if isInside (n, d) (x, y) then "YES" else "NO"

import Control.Applicative
import Control.Monad

cross (x1,y1) (x2,y2) = x1*y2-x2*y1
sub (x1,y1) (x2,y2) = (x1-x2,y1-y2)
inRect n d x y = all (>=0) t || all (<=0) t
  where
    t = [cross (-1,1) ((x,y) `sub` (d,0)), cross (1,1) ((x,y) `sub` (0,d)),
         cross (1,-1) ((x,y) `sub` (n-d,n)), cross (-1,-1) ((x,y) `sub` (n,n-d))]

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

  replicateM m $ do
    [x,y] <- map read . words <$> getLine :: IO [Int]
    putStrLn $ if inRect n d x y then "YES" else "NO"

main = getContents >>= putStr . unlines . solve . map read . words

solve (n:d:0:_) = []
solve (n:d:m:x:y:xys) = (contain n d x y) : solve (n:d:m - 1:xys)

contain n d x y = if d <= x + y && x + y <= 2 * n - d && -d <= x - y && x - y <= d
                  then "YES"
                  else "NO"


You are given an integer $$$n$$$ and an array $$$a_1,a_2,\ldots,a_n$$$.In one operation, you can choose an index $$$i$$$ ($$$1 \le i \lt n$$$) for which $$$a_i \neq a_{i+1}$$$ and delete both $$$a_i$$$ and $$$a_{i+1}$$$ from the array. After deleting $$$a_i$$$ and $$$a_{i+1}$$$, the remaining parts of the array are concatenated.For example, if $$$a=[1,4,3,3,6,2]$$$, then after performing an operation with $$$i=2$$$, the resulting array will be $$$[1,3,6,2]$$$.What is the maximum possible length of an array of equal elements obtainable from $$$a$$$ by performing several (perhaps none) of the aforementioned operations?

Each test contains multiple test cases. The first line of input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The following lines contain the descriptions of the test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le n$$$) — the elements of array $$$a$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10\,000$$$.

For each testcase, print a single integer, the maximum possible length of an array of equal elements obtainable from $$$a$$$ by performing a sequence of operations.

NoteFor the first testcase, an optimal sequence of operations would be: $$$[1,2,3,2,1,3,3] \rightarrow [3,2,1,3,3] \rightarrow [3,3,3]$$$.For the second testcase, all elements in the array are already equal.For the third testcase, the only possible sequence of operations is: $$$[1,1,1,2,2,2] \rightarrow [1,1,2,2] \rightarrow [1,2] \rightarrow []$$$. Note that, according to the statement, the elements deleted at each step must be different.For the fourth testcase, the optimal sequence of operations is: $$$[1,1,2,2,3,3,1,1] \rightarrow [1,1,2,3,1,1] \rightarrow [1,1,1,1]$$$.For the fifth testcase, one possible reachable array of two equal elements is $$$[4,4]$$$.

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

import Control.Arrow ((>>>))
import Control.Monad (
    MonadPlus (mplus),
    foldM_,
    forM_,
    guard,
    join,
    replicateM,
    replicateM_,
 )
import qualified Control.Monad as M
import qualified Control.Monad.ST.Strict as ST
import qualified Control.Monad.State.Strict as S
import qualified Control.Monad.Trans.Class as T

import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.IO.Safe as IOA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import Data.Bits
import qualified Data.ByteString.Char8 as B8
import Data.Char
import Data.Int

import Data.Function (on)
import Data.Functor ((<&>))
import Data.Bifunctor (bimap)
import Data.Maybe (fromJust, fromMaybe, isJust)
import qualified Data.Maybe as MB

import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import qualified Data.List   as L
import Data.List (
    elemIndices,
    find,
    findIndices,
    intersect,
    isPrefixOf,
    nub,
    sort,
    sortOn,
 )
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Ix as Ix
import qualified Data.Ratio as R

import Control.Monad.Cont (MonadIO (liftIO))
import Data.IORef (modifyIORef, newIORef, readIORef)
import GHC.IO.Handle (hDuplicateTo)
import System.IO (
    IOMode (ReadMode, WriteMode),
    openFile,
    stdin,
    stdout,
    hFlush
 )
import System.Posix.Internals (puts)
import Text.Printf (printf)
import qualified Data.Array.IO.Safe as UOA

-- import Debug.Trace (trace, traceM, traceShowM)
-- debug = flip trace
--
-- tracing t x = trace (t ++ " = " ++ show x) x
-- debugging x t = tracing t x
--
-- debug x t = x
-- trace t x = x
-- tracing t x = x
-- debugging x t = x

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

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

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

m :: Int64
-- m = 998_244_353
m = 10 ^ 9 + 7

newtype M = M { unM :: Int64 }
  deriving (Eq, Ord)

mI :: Int -> M
mI = M . fromIntegral

instance Show M where
    show (M v) = "M" ++ show v

instance Num M where
    fromInteger n = M $ fromInteger (n `mod` fromIntegral m)

    (M a) + (M b) | a + b >= m = M $ a + b - m
    (M a) + (M b) = M $ a + b

    (M a) - (M b) | a - b < 0 = M $ m + a - b
    (M a) - (M b) = M $ a - b

    (M a) * (M b) = M $ (a * b) `mod` m

    abs    = id
    signum = undefined

powM :: M -> Int64 -> M
powM a@(M ma) x
    | x == 0 = M 1
    | x == 1 = a
    | even x = let t = powM a (x `div` 2) in t * t
    | odd x = a * powM a (x - 1)

instance Fractional M where
    recip a = powM a $ m - 2
    fromRational d = (M . fromInteger . R.numerator $ d) * (recip . M . fromInteger . R.denominator $ d)

type GraphA = A.Array Int [Int]

graphFromEdges :: Int -> [(Int, Int)] -> GraphA
graphFromEdges n edges = graph
    where
        graph = STA.runSTArray $ do
            graphA <- MA.newArray (1, n) ([] :: [Int])
            forM_ edges $ \(u, v) -> do
                modifyArray graphA u (v:)
                modifyArray graphA v (u:)
            return graphA

{- END OF GENERAL -}

solve :: Int -> [Int] -> Int
solve n as = dp UA.! (n + 1)
    where
        asA :: UA.UArray Int Int
        asA = UA.array (0, n + 1) $ zip [0 .. n + 1] (0 : as ++ [0])

        deletable :: UA.UArray (Int, Int) Bool
        deletable = STA.runSTUArray $ do
            deletableA <- MA.newArray ((1, 1), (n, n)) False
            cntsA <- MA.newArray (1, n) (0 :: Int) :: ST.ST s (STA.STUArray s Int Int)

            forM_ [1 .. n] $ \i -> do
                flip S.evalStateT 0 $ do
                    M.forM_ [i .. n] $ \j -> do
                        let a = asA UA.! j
                        let k = j - i + 1
                        T.lift $ modifyArray cntsA a succ
                        cnt <- T.lift $ MA.readArray cntsA a
                        S.modify $ max cnt
                        maxCnt <- S.get
                        M.when (even k && maxCnt <= (k `div` 2)) $ do
                            T.lift $ MA.writeArray deletableA (i, j) True

                forM_ [i .. n] $ \j -> do
                    let a = asA UA.! j
                    MA.writeArray cntsA a 0

            return deletableA

        dp :: UA.UArray Int Int
        dp = STA.runSTUArray $ do
            dpA <- MA.newArray (0, n + 1) (minBound :: Int)
            MA.writeArray dpA 0 (-1)
            forM_ [1 .. n + 1] $ \r -> do
                let a = asA UA.! r
                M.forM_ [0 .. r - 1] $ \l -> do
                    let b = asA UA.! l
                    let k = r - l - 1
                    M.when ((a == b || a == 0 || b == 0) && even k) $ do
                        let ll = l + 1
                        let rr = r - 1
                        let isDeletable = k == 0 || (1 <= rr && ll <= n && deletable UA.! (ll, rr))
                        M.when isDeletable $ do
                            dpV <- MA.readArray dpA l
                            modifyArray dpA r $ max (dpV + 1)
            return dpA

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


Fox Ciel is playing a card game with her friend Jiro.Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.Now is Ciel's battle phase, Ciel can do the following operation many times:  Choose one of her cards X. This card mustn't be chosen before.  If Jiro has no alive cards at that moment, he gets the damage equal to (X's strength). Otherwise, Ciel needs to choose one Jiro's alive card Y, then:   If Y's position is Attack, then (X's strength)  ≥  (Y's strength) must hold. After this attack, card Y dies, and Jiro gets the damage equal to (X's strength) - (Y's strength).  If Y's position is Defense, then (X's strength)  >  (Y's strength) must hold. After this attack, card Y dies, but Jiro gets no damage.  Ciel can end her battle phase at any moment (so, she can use not all her cards). Help the Fox to calculate the maximal sum of damage Jiro can get.

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of cards Jiro and Ciel have. Each of the next n lines contains a string position and an integer strength (0 ≤ strength ≤ 8000) — the position and strength of Jiro's current card. Position is the string "ATK" for attack, and the string "DEF" for defense. Each of the next m lines contains an integer strength (0 ≤ strength ≤ 8000) — the strength of Ciel's current card.

Output an integer: the maximal damage Jiro can get.

NoteIn the first test case, Ciel has 3 cards with same strength. The best strategy is as follows. First she uses one of these 3 cards to attack "ATK 2000" card first, this attack destroys that card and Jiro gets 2500 - 2000 = 500 damage. Then she uses the second card to destroy the "DEF 1700" card. Jiro doesn't get damage that time. Now Jiro has no cards so she can use the third card to attack and Jiro gets 2500 damage. So the answer is 500 + 2500 = 3000.In the second test case, she should use the "1001" card to attack the "ATK 100" card, then use the "101" card to attack the "ATK 10" card. Now Ciel still has cards but she can choose to end her battle phase. The total damage equals (1001 - 100) + (101 - 10) = 992.In the third test case note that she can destroy the "ATK 0" card by a card with strength equal to 0, but she can't destroy a "DEF 0" card with that card.

import Control.Monad
import Control.Applicative

import Data.List
import Data.Maybe

filt [] ys = Just ys
filt (x:xs) [] = Nothing
filt (x:xs) (y:ys) =
    if y <= x
        then filt (x:xs) ys >>= return . (y:)
        else filt xs ys

solve (c0, ja0, jd0) = max s1 s2
    where
        [c, ja, jd] = map sort [c0, ja0, jd0]

        s1 = sum $ zipWith (\a b -> max 0 $ a - b) (reverse c) ja

        s2 = fromMaybe 0 $ do
            c' <- filt jd c
            return $ if length c' >= length ja && and (zipWith (<=) (reverse ja) (reverse c'))
                        then sum c' - sum ja
                        else 0

input = do
    [n, m] <- map read . words <$> getLine
    j <- replicateM n $ (\[p, s] -> (p == "ATK", read s)) . words <$> getLine
    let (ja0, jd0) = partition fst j
    c <- replicateM m $ read <$> getLine
    return (c, map snd ja0, map snd jd0)

main = print . solve =<< input

import Data.List
import Data.Maybe

import Control.Monad
import Control.Applicative

filt [] ys = Just ys
filt (x:xs) [] = Nothing
filt (x:xs) (y:ys) =
    if y <= x
        then filt (x:xs) ys >>= return . (y:)
        else filt xs ys

solve (c0, ja0, jd0) =
    max s1 s2
        where
            [c, ja, jd] = map sort [c0, ja0, jd0]

            s1 = sum $ zipWith (\a b -> max 0 $ a - b) (reverse c) ja

            s2 = fromMaybe 0 $ do
                c' <- filt jd c
                return $ if length c' >= length ja && and (zipWith (<=) (reverse ja) (reverse c'))
                            then sum c' - sum ja
                            else 0

readInput = do
    [n, m] <- map read . words <$> getLine
    j <- replicateM n $ words <$> getLine >>= \[p, s] -> return (p == "ATK", read s)
    let (ja0, jd0) = partition fst j
    c <- replicateM m $ read <$> getLine
    return (c, map snd ja0, map snd jd0)

main = print . solve =<< readInput

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

main = do
    [n,m] <- map read . words <$> getLine
    jiro <- replicateM n (parseJiro <$> getLine)
    ciel <- replicateM m (parseCiel <$> getLine)
    print $ solve jiro ciel

parseJiro :: String -> (Bool,Int)
parseJiro ('A':'T':'K':' ':s) = (True,read s)
parseJiro ('D':'E':'F':' ':s) = (False,read s)

parseCiel :: String -> Int
parseCiel = read

solve jiro ciel | canDefeatAll = max a1 a2
                | otherwise    = a1
    where
        attacks = sort [ s | (True,s) <- jiro]
        defenses = sort [ s | (False,s) <- jiro ]
        canDefeatAll = all (uncurry (<=)) $ zip (reverse $ sort (attacks ++ map succ defenses)) (reverse $ sort ciel)
        a1 = sum $ map (\(a,b) -> if a > b then a - b else 0)
                 $ zip (reverse (sort ciel)) attacks
        a2 = sum (remove defenses (sort ciel)) - sum attacks

remove [] ciel = ciel
remove (x:xs) ciel = remove xs (deleteBy (<) x ciel)

import Data.List (foldl', sort)
import qualified Data.IntMap as Map
import Data.Maybe (maybeToList)
import Data.Function (on)
import Control.Monad

-- x is supposed to be descending, att is so too
-- def is supposed to be ascending
rush :: ([Int], [Int]) -> [Int] -> Int
rush (att, []) x = let planA = (sum . takeWhile (>= 0) . zipWith (-) x) (att ++ repeat 0)
                       planB = (sum . takeWhile (>= 0) . zipWith (-) x) (reverse att ++ repeat 0)
                   in  max planA planB
rush (att, def) x = let x' = concat . maybeToList $ x `kill` def
                        x'' = take (length att) x in
                    (max `on` rush (att, [])) x' x''

kill :: [Int] -> [Int] -> Maybe [Int]
kill x def = let xs = foldl' cons Map.empty x
                 cons m y = Map.insertWith (+) y 1 m
                 xs' = foldl' f (return xs) def
                 f ms d = ms >>= \s -> let att = Map.lookupGT d s in fmap (del s . fst) att
                 del = flip $ Map.update (\y -> if y == 1 then Nothing else Just (y - 1))
                 toList  = Map.foldlWithKey' (\l y c -> l  ++ replicate c y) []
             in fmap (reverse . toList) xs'

main :: IO ()
main = do
  m:n:_ <- fmap (map read . words) getLine
  jiro <- fmap (map words) (replicateM m getLine)
  fox <- fmap (map read) (replicateM n getLine)
  let jiros = jiroParse jiro
--  print jiros
  print $ rush (jiroParse jiro) (reverse (sort fox))

jiroParse :: [[String]] -> ([Int], [Int])
jiroParse s = let (att, def) = categorize s ([],[])
                  in (reverse (sort att), sort def)

categorize :: [[String]] -> ([Int], [Int]) -> ([Int], [Int])
categorize [] x = x
categorize (("ATK":x:_):rest) (atk, def) = categorize rest (read x : atk, def)
categorize ((_:x:_):rest) (atk, def) = categorize rest (atk, read x : def)

import Data.List
import Data.Maybe

import Control.Monad
import Control.Applicative

filt [] ys = Just ys
filt (x:xs) [] = Nothing
filt (x:xs) (y:ys) =
    if y <= x
        then filt (x:xs) ys >>= (return . (y:))
        else filt xs ys

solve (c0, ja0, jd0) =
    max s1 s2
        where
            [c, ja, jd] = map sort [c0, ja0, jd0]

            s1 = sum $ zipWith (\a b -> max 0 $ a - b) (reverse c) ja

            s2 = fromMaybe 0 $ do
                c' <- filt jd c
                return $ if length c' >= length ja && and (zipWith (<=) ja $ reverse c')
                            then sum c' - sum ja
                            else 0

readInput = do
    [n, m] <- map read . words <$> getLine
    j <- replicateM n $ words <$> getLine >>= \[p, s] -> return (p == "ATK", read s)
    let (ja, jd) = partition fst j
    c <- replicateM m $ read <$> getLine
    return (c, map snd ja, map snd jd)

main = print . solve =<< readInput

import Data.List (foldl', sort)
import qualified Data.IntMap as Map
import Data.Maybe (maybeToList)
import Data.Function (on)
import Control.Monad

-- x is supposed to be descending, att is so too
-- def is supposed to be ascending
rush :: ([Int], [Int]) -> [Int] -> Int
rush (att, []) x = let-- planA = (sum . takeWhile (> 0) . zipWith (-) x) (att ++ repeat 0)
                       planB = (sum . takeWhile (> 0) . zipWith (-) x) (reverse att ++ repeat 0)
                   in  planB
rush (att, def) x = let x' = concat . maybeToList $ x `kill` def
                        x'' = take (length att) x in
                    (max `on` rush (att, [])) x' x''

kill :: [Int] -> [Int] -> Maybe [Int]
kill x def = let xs = foldl' cons Map.empty x
                 cons m y = Map.insertWith (+) y 1 m
                 xs' = foldl' f (return xs) def
                 f ms d = ms >>= \s -> let att = Map.lookupGT d s in fmap (del s . fst) att
                 del = flip $ Map.update (\y -> if y == 1 then Nothing else Just (y - 1))
                 toList  = Map.foldlWithKey' (\l y c -> l  ++ replicate c y) []
             in fmap (reverse . toList) xs'

main :: IO ()
main = do
  m:n:_ <- fmap (map read . words) getLine
  jiro <- fmap (map words) (replicateM m getLine)
  fox <- fmap (map read) (replicateM n getLine)
  print $ rush (jiroParse jiro) (reverse (sort fox))

jiroParse :: [[String]] -> ([Int], [Int])
jiroParse s = let (att, def) = categorize s ([],[])
                  in (reverse (sort att), sort def)

categorize :: [[String]] -> ([Int], [Int]) -> ([Int], [Int])
categorize [] x = x
categorize (("ATK":x:_):rest) (atk, def) = categorize rest (read x : atk, def)
categorize ((_:x:_):rest) (atk, def) = categorize rest (atk, read x : def)

import Data.List (foldl', sort)
import qualified Data.IntMap as Map
import Data.Maybe (maybeToList)
import Data.Function (on)
import Control.Monad

-- x is supposed to be descending, att is so too
-- def is supposed to be ascending
rush :: ([Int], [Int]) -> [Int] -> Int
rush (att, []) x = let-- planA = (sum . takeWhile (> 0) . zipWith (-) x) (att ++ repeat 0)
                       planB = (sum . takeWhile (>= 0) . zipWith (-) x) (reverse att ++ repeat 0)
                   in  planB
rush (att, def) x = let x' = concat . maybeToList $ x `kill` def
                        x'' = take (length att) x in
                    (max `on` rush (att, [])) x' x''

kill :: [Int] -> [Int] -> Maybe [Int]
kill x def = let xs = foldl' cons Map.empty x
                 cons m y = Map.insertWith (+) y 1 m
                 xs' = foldl' f (return xs) def
                 f ms d = ms >>= \s -> let att = Map.lookupGT d s in fmap (del s . fst) att
                 del = flip $ Map.update (\y -> if y == 1 then Nothing else Just (y - 1))
                 toList  = Map.foldlWithKey' (\l y c -> l  ++ replicate c y) []
             in fmap (reverse . toList) xs'

main :: IO ()
main = do
  m:n:_ <- fmap (map read . words) getLine
  jiro <- fmap (map words) (replicateM m getLine)
  fox <- fmap (map read) (replicateM n getLine)
  print $ rush (jiroParse jiro) (reverse (sort fox))

jiroParse :: [[String]] -> ([Int], [Int])
jiroParse s = let (att, def) = categorize s ([],[])
                  in (reverse (sort att), sort def)

categorize :: [[String]] -> ([Int], [Int]) -> ([Int], [Int])
categorize [] x = x
categorize (("ATK":x:_):rest) (atk, def) = categorize rest (read x : atk, def)
categorize ((_:x:_):rest) (atk, def) = categorize rest (atk, read x : def)


Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 × n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1 × 5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture:  As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.

The first line contains a positive integer n (1 ≤ n ≤ 1000). The second line contains n positive integers which are the height of the sections. All the numbers are no less than 1 and not more than 1000.

Print a single number, the maximal number of watered sections if we create artificial rain above exactly one section.

main = interact in2out

in2out input
  = output
  where
    output = show $ maximum l2
    items = [read x::Int | x<-tail$words input]
    l1 = 1:tl1
    l2 = 1:tl2
    (tl1,tl2) = solve l1 l2 items
    solve (x1:t1) (x2:t2) (a:b:rest)
      | a == b
      = ((x1+1):a1, (x2+1):a2)
      | a < b
      = ((x1+1):a1, (x1+1):a2)
      | a > b
      = (1:a1, (x2+1):a2)
      where
        (a1,a2) = solve t1 t2 (b:rest)
    solve _ _ _
      = ([],[])

main :: IO ()
main = do
        n <- getLine
        s <- getLine
        let ss = map (read :: String -> Int) (words s)
        print (solve ss)

solve :: [Int] -> Int
solve s = maximum (zipWith (\x y -> x + y + 1) (f s 0) (reverse (f (reverse s) 0)))

f :: [Int] -> Int -> [Int]
f [] a = []
f [x] a = [a]
f (x : y : xs) a
        | x <= y = a : (f (y : xs) (a + 1))
        | otherwise = a : (f (y : xs) 0)

main :: IO ()
main = do
	n <- getLine
	s <- getLine
	let ss = map (read :: String -> Int) (words s)
	print (solve ss)

solve :: [Int] -> Int
solve s = fst (findmaxind (zipWith (\x y -> x + y + 1) (f s 0) (reverse (f (reverse s) 0))))

f :: [Int] -> Int -> [Int]
f [] a = []
f [x] a = [a]
f (x : y : xs) a
	| x <= y = a : (f (y : xs) (a + 1))
	| otherwise = a : (f (y : xs) 0)

findmaxind :: [Int] -> (Int, Int)
findmaxind [] = (-1, -1)
findmaxind [x] = (x, 0)
findmaxind (x : xs)
	| x > fst maxt = (x, 0)
	| otherwise = (fst maxt, snd maxt + 1)
	where maxt = findmaxind xs

notLess :: [Int] -> [Int]
notLess [] = []
notLess (x:xs) = notLess_ 0 0 (x:xs)
    where notLess_ _ _ [] = []
          notLess_ pred count (x:xs) = if (pred > x) then 1:(notLess_ x 1 xs) else ((count + 1):notLess_ x (count + 1) xs)

solve :: [Int] -> Int
solve a = maximum d - 1
    where
        d = zipWith (+) (notLess a) (reverse (notLess (reverse a)))

main = do
    n <- readLn::(IO Int)
    line <- getLine
    a <- return (map read (words line))
    putStr (show (solve a))

import Data.List
solve = maximum . flip phaseA 0 . group
phaseA (x:y:zs) a | head x < head y = phaseA (y:zs) $! a + length x
                  | otherwise       = phaseB (y:zs) $! a + length x
phaseA [y] a = [a + length y]
phaseB (x:y:zs) a | head x > head y = phaseB (y:zs) $! a + length x
                  | otherwise       = (a+length y) : phaseA (y:zs) (length x)
phaseB [y] a = [a + length y]
main = do
  getLine
  print . solve . map (read :: String -> Int) . words =<< getLine

import Data.Array

left a (-1) = 0
left a i
    | a ! i <= a ! (i + 1) = 1 + left a (i - 1)
    | otherwise = 0

right a i
    | snd (bounds a) < i = 0
    | a ! i <= a ! (i - 1) = 1 + right a (i + 1)
    | otherwise = 0

doJob a (-1) = 0
doJob a i = max (doJob a (i - 1)) (1 + (left a (i - 1)) + (right a (i + 1)))

solve input =
    let (nn:[l]) = lines input in
    let n = (read nn)::Int in
    let a = listArray (0, n - 1) ((map (\x -> (read x)::Int) . words) l) in

    show (doJob a (n - 1))

main = interact(solve)

import Data.List
import Data.Array
main = do
    n <- readIO =<< getLine :: IO Int
    l <- (map read . words) `fmap` getLine :: IO [Int]
    let gl = map (\s'@(s:ss) -> (s, length s')) $ group l
        lgl = length gl
        arr = array (1, lgl) $ zip [1..] gl
        f (l, r) res | l > 1 && fst (arr ! (l - 1)) < fst (arr ! l) = f (l - 1, r) (res
                        + snd (arr ! (l - 1)))
                     | r < lgl && fst (arr ! (r + 1)) < fst (arr ! r) = f (l, r+1) (res
                        + snd (arr ! (r + 1)))
                     | otherwise = res
        r = maximum $ map (\i -> f (i, i) (snd $ arr ! i)) [1..lgl]
    print r

module Main where
import Control.Applicative
import Data.List
import Data.Maybe

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

h xs = (takeWhile (> -1))  $ (zipWith  (-) xs (tail xs))

h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)

g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

g' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs
g'' xs = zipWith (+) (g' . init . tails $ xs)  ((g' . (map reverse) .  tail . inits) $xs)

main :: IO ()
main =
    do {_ : ns <-  (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents
    ; let ns' = g'' ns in print $ (+1) $ (maximum ns')
    }

module Main where
import Control.Applicative
import Data.List
import Data.Maybe

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

h xs = (takeWhile (> -1))  $ (zipWith  (-) xs (tail xs))
--h' :: [Int] -> [Int]
h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)

g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

g' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs
g'' xs = zipWith (+) (g' . init . tails $ xs)  ((g' . (map reverse) .  tail . inits) $xs)

--(flip find' ns )
main :: IO ()
main =
    do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile "input.txt"
         _ : ns <-  (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents
    ; let ns' = g'' ns in print $ (+1) $ (maximum ns')
    }

module Main where
import Control.Applicative
import Data.List
import Data.Maybe
import Data.Function (on)

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

--h xs = (takeWhile (> -1))  $ (zipWith  (-) xs (tail xs))
h xs = head . groupBy (>) $ xs
h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)

-- 増加しているどうかを調べる
g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

-- 増加している箇所長さを取得
g' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs
g'' xs = zipWith (+) (g' . init . tails $ xs)  ((g' . (map reverse) .  tail . inits) $xs)

main :: IO ()
main =
    do {_:ns <- (map ((+0) . read)).(concatMap split)<$>lines<$>getContents
    ; let ns' = g'' ns in print $ (+1) $ (maximum ns')
    }

import Data.List;

gao' :: [Int] -> Int -> Int
gao' xs i = go (reverse $ take (i - 1) xs) n + go (drop i xs) n + 1 where
	n :: Int
	n = last $ take i xs
	go :: [Int] -> Int -> Int
	go [] _ = 0
	go (x:xs) n
		| n >= x = 1 + go xs x
		| otherwise = 0

gao :: [Int] -> String
gao xs = show $ maximum $ map (gao' xs) [1 .. length xs]

main' :: String -> String
main' input = unlines [gao $ map read $ words $ last $ lines input]

main = interact main'

module Main where

import Control.Monad

main = do
    getLine
    sections <- ( map read . words ) `liftM` getLine

    let (_, _, best) = compute sections
    putStrLn $ show best

compute :: [Int] -> (Int, Int, Int)
compute (s1:s2:ss) =
    let (up', down', best') = compute (s2:ss)
        up = 1 + if s1 <= s2 then up' else down'
        down = if s1 >= s2 then down' + 1 else 1
        best = max best' up
    in (up, down, best)
compute _ = (1, 1, 1)

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

foldl' :: (a -> b -> a) -> a -> [b] -> a
foldl' _ a [] = a
foldl' f a (x:xs) = a' `seq` foldl' f a' xs
	where a' = f a x

left hs x = d ! x
	where
		d = array (0,n-1) [(i, left' i) | i <- [0..n-1]]
		n = length hs
		left' 0 = 0
		left' i
			| (hs !! (i-1)) <= (hs !! i) = d ! (i-1)
			| otherwise = i

right hs x = d ! x
	where
		d = array (0,n-1) [(i, right' i) | i <- reverse [0..n-1]]
		n = length hs
		right' i
			| i == n-1 = n-1
			| (hs !! (i+1)) <= (hs !! i) = d ! (i+1)
			| otherwise = i

main = do
	hs <- C.hGetContents stdin >>= return . (map (fst . fromJust . C.readInt)) . tail . C.words
	let n = length hs
	putStrLn . show $ foldl' max 0 [right hs i - left hs i + 1 | i <- [0..n-1]]
	-- print [lowest hs i 1 - lowest hs i (-1) + 1 | i <- [0..n-1]]

module Main where
import Control.Applicative
import Data.List
import Data.Maybe
import Data.Function (on)

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

h xs = head . groupBy (>) $ xs
h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)
-- 増加しているどうかを調べる
g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

-- 増加している箇所長さを取得
g' xs = (map (toInteger . length)) . (map (head . groupBy (<))) $ xs
g'' xs = zipWith (+) (g' . init . tails $ xs)  ((g' . (map reverse) .  tail . inits) $xs)

main :: IO ()
main =
    do {_:ns <- (map ((+0) . read)).(concatMap split)<$>lines<$>getContents
    ; let ns' = g'' ns in print $ (+1) $ (maximum ns')
    }

module Main where
import Control.Applicative
import Data.List
import Data.Maybe

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

h xs = (takeWhile (> -1))  $ (zipWith  (-) xs (tail xs))
--h' :: [Int] -> [Int]
h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)

g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

g' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs
g'' xs = zipWith (+) (g' . tails $ xs)  ((g' . (map reverse) .  inits) $xs)

--(flip find' ns )
main :: IO ()
main =
    do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile "input.txt"
         _ : ns <-  (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents
       --; let n' =  snd . maximum . (map f) .  gr $ ns
       --; let n' =  h $ ns
    ; let ns' = g' . tails $ ns in print $  ((maximum ns'),ns')
    }

module Main where
import Control.Applicative
import Data.List
import Data.Maybe

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

h xs = (takeWhile (> -1))  $ (zipWith  (-) xs (tail xs))
--h' :: [Int] -> [Int]
h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)

g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

g' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs
g'' xs = zipWith (+) (g' . init . tails $ xs)  ((g' . (map reverse) . tail . inits) $xs)

--(flip find' ns )
main :: IO ()
main =
    do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile "input.txt"
         _ : ns <-  (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents
       --; let n' =  snd . maximum . (map f) .  gr $ ns
       --; let n' =  h $ ns
    ; let ns' = g' . tails $ ns in print $  (+1) . fromJust $ (findIndex (==(maximum ns')) ns')
    }

module Main where
import Control.Applicative
import Data.List
import Data.Maybe
import Data.Function (on)

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

h xs = head . groupBy (>) $ xs
h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)
-- 増加しているどうかを調べる
g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

-- 増加している箇所長さを取得
g' xs = (map (toInteger . length)) . (map (head . groupBy (>))) $ xs
g'' xs = zipWith (+) (g' . init . tails $ xs)  ((g' . (map reverse) .  tail . inits) $xs)

main :: IO ()
main =
    do {_:ns <- (map ((+0) . read)).(concatMap split)<$>lines<$>getContents
    ; let ns' = g'' ns in print $ (+1) $ (maximum ns')
    }

module Main where
import Control.Applicative
import Data.List
import Data.Maybe

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

h xs = (takeWhile (> -1))  $ (zipWith  (-) xs (tail xs))
--h' :: [Int] -> [Int]
h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)

g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

g' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs
g'' xs = zipWith (+) (g' . init . tails $ xs)  ((g' . (map reverse) . tail . inits) $xs)

--(flip find' ns )
main :: IO ()
main =
    do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile "input.txt"
         _ : ns <-  (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents
       --; let n' =  snd . maximum . (map f) .  gr $ ns
       --; let n' =  h $ ns
    ; let ns' = g' . tails $ ns in print $  ((maximum ns'),ns')
    }

module Main where
import Control.Applicative
import Data.List
import Data.Maybe

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

h xs = (takeWhile (> -1))  $ (zipWith  (-) xs (tail xs))
--h' :: [Int] -> [Int]
h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)

g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

g' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs
g'' xs = zipWith (+) (g' . init . tails $ xs)  ((g' . (map reverse) . tail . inits) $xs)

--(flip find' ns )
main :: IO ()
main =
    do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile "input.txt"
         _ : ns <-  (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents
       --; let n' =  snd . maximum . (map f) .  gr $ ns
       --; let n' =  h $ ns
    ; let ns' = g' . tails $ ns in print $  (maximum ns')
    }

module Main where
import Control.Applicative
import Data.List
import Data.Maybe

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

h xs = (takeWhile (> -1))  $ (zipWith  (-) xs (tail xs))
--h' :: [Int] -> [Int]
h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)

g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

g' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs
g'' xs = zipWith (+) (g' . tails $ xs)  ((g' . (map reverse) . inits) $xs)

--(flip find' ns )
main :: IO ()
main =
    do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile "input.txt"
         _ : ns <-  (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents
       --; let n' =  snd . maximum . (map f) .  gr $ ns
       --; let n' =  h $ ns
    ; let ns' = g' . tails $ ns in print $ (+1) . fromJust $ (findIndex (==(maximum ns')) ns')
    }

module Main where
import Control.Applicative
import Data.List
import Data.Maybe

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

h xs = (takeWhile (> -1))  $ (zipWith  (-) xs (tail xs))
--h' :: [Int] -> [Int]
h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)

g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

g' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs
g'' xs = zipWith (+) (g' . init . tails $ xs)  ((g' . (map reverse) . tail . inits) $xs)

--(flip find' ns )
main :: IO ()
main =
    do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile "input.txt"
         _ : ns <-  (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents
       --; let n' =  snd . maximum . (map f) .  gr $ ns
       --; let n' =  h $ ns
    ; let ns' = g' . tails $ ns in print $  (fromJust $ (findIndex (==(maximum ns')) ns'),ns)
    }

module Main where
import Control.Applicative
import Data.List
import Data.Maybe

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

h xs = (takeWhile (> -1))  $ (zipWith  (-) xs (tail xs))
--h' :: [Int] -> [Int]
h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)

g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

g' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs
g'' xs = zipWith (+) (g' . tails $ xs)  ((g' . (map reverse) . inits) $xs)

--(flip find' ns )
main :: IO ()
main =
    do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile "input.txt"
         _ : ns <-  (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents
       --; let n' =  snd . maximum . (map f) .  gr $ ns
       --; let n' =  h $ ns
    ; let ns' = g' . tails $ ns in print $  fromJust $ (findIndex (==(maximum ns')) ns')
    }

module Main where
import Control.Applicative
import Data.List
import Data.Maybe

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

h xs = (takeWhile (> -1))  $ (zipWith  (-) xs (tail xs))
--h' :: [Int] -> [Int]
h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)

g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

g' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs
g'' xs = zipWith (+) (g' . tails $ xs)  ((g' . (map reverse) .  inits) $xs)

--(flip find' ns )
main :: IO ()
main =
    do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile "input.txt"
         _ : ns <-  (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents
       --; let n' =  snd . maximum . (map f) .  gr $ ns
       --; let n' =  h $ ns
    ; let ns' = g' . tails $ ns in print $ (+1) $ (maximum ns')
    }

module Main where
import Control.Applicative
import Data.List
import Data.Maybe
import Data.Function (on)

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

h xs = head . groupBy (>) $ xs
h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)
-- 増加しているどうかを調べる
g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

-- 増加している箇所長さを取得
g' xs = (map (toInteger . length)) . (map (head . groupBy (>=))) $ xs
g'' xs = zipWith (+) (g' . init . tails $ xs)  ((g' . (map reverse) .  tail . inits) $xs)

main :: IO ()
main =
    do {_:ns <- (map ((+0) . read)).(concatMap split)<$>lines<$>getContents
    ; let ns' = g'' ns in print $ (+1) $ (maximum ns')
    }

module Main where
import Control.Applicative
import Data.List
import Data.Maybe

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

h xs = (takeWhile (> -1))  $ (zipWith  (-) xs (tail xs))
--h' :: [Int] -> [Int]
h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)

g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

g' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs
g'' xs = zipWith (+) (g' . init . tails $ xs)  ((g' . (map reverse) . tail . inits) $xs)

--(flip find' ns )
main :: IO ()
main =
    do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile "input.txt"
         _ : ns <-  (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents
       --; let n' =  snd . maximum . (map f) .  gr $ ns
       --; let n' =  h $ ns
    ; let ns' = g' . tails $ ns in print $  ((+1) . fromJust $ (findIndex (==(maximum ns')) ns'),ns)
    }

module Main where
import Control.Applicative
import Data.List
import Data.Maybe

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

gr :: [a] -> [[a]]
gr xs = zipWith (++)  (tails xs) (inits xs)

f :: (Num a, Ord a) => [a] -> (Int, a)
f (n:ns) = ((length  xs) , (head xs))
  where
   xs = (takeWhile (<=n)  (n:ns))
f [] = (0,0)

find' x xs = find (==x) xs

h xs = (takeWhile (> -1))  $ (zipWith  (-) xs (tail xs))
--h' :: [Int] -> [Int]
h' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)

g :: [Integer] -> [Integer]
g xs = zipWith (-) xs (tail xs)

g' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs
g'' xs = zipWith (+) (g' . init . tails $ xs)  ((g' . (map reverse) . tail . inits) $xs)

--(flip find' ns )
main :: IO ()
main =
    do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile "input.txt"
         _ : ns <-  (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents
       --; let n' =  snd . maximum . (map f) .  gr $ ns
       --; let n' =  h $ ns
    ; let ns' = g' . tails $ ns in print $  (fromJust $ (findIndex (==(maximum ns')) ns'),ns')
    }

lowest hs 0 _ = 0
lowest hs x d
	| length hs - 1 == x = x
	| (hs !! x+d) <= (hs !! x) = lowest hs (x+d) d
	| otherwise = x

main = do
	n <- getLine >>= return . read :: IO Int
	hs <- getLine >>= return . map read . words :: IO [Int]
	putStrLn . show $ foldl max 0 [lowest hs i (1) - lowest hs i (-1) | i <- [0..n-1]]


There are $$$n$$$ Christmas trees on an infinite number line. The $$$i$$$-th tree grows at the position $$$x_i$$$. All $$$x_i$$$ are guaranteed to be distinct.Each integer point can be either occupied by the Christmas tree, by the human or not occupied at all. Non-integer points cannot be occupied by anything.There are $$$m$$$ people who want to celebrate Christmas. Let $$$y_1, y_2, \dots, y_m$$$ be the positions of people (note that all values $$$x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$$$ should be distinct and all $$$y_j$$$ should be integer). You want to find such an arrangement of people that the value $$$\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$$$ is the minimum possible (in other words, the sum of distances to the nearest Christmas tree for all people should be minimized).In other words, let $$$d_j$$$ be the distance from the $$$j$$$-th human to the nearest Christmas tree ($$$d_j = \min\limits_{i=1}^{n} |y_j - x_i|$$$). Then you need to choose such positions $$$y_1, y_2, \dots, y_m$$$ that $$$\sum\limits_{j=1}^{m} d_j$$$ is the minimum possible.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of Christmas trees and the number of people. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$), where $$$x_i$$$ is the position of the $$$i$$$-th Christmas tree. It is guaranteed that all $$$x_i$$$ are distinct.

In the first line print one integer $$$res$$$ — the minimum possible value of $$$\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$$$ (in other words, the sum of distances to the nearest Christmas tree for all people). In the second line print $$$m$$$ integers $$$y_1, y_2, \dots, y_m$$$ ($$$-2 \cdot 10^9 \le y_j \le 2 \cdot 10^9$$$), where $$$y_j$$$ is the position of the $$$j$$$-th human. All $$$y_j$$$ should be distinct and all values $$$x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$$$ should be distinct. If there are multiple answers, print any of them.

{-# LANGUAGE TupleSections #-}

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

solve :: Int -> Integer -> [Int] -> Seq (Integer, Int) -> Set.Set Int -> (Integer, [Int])
solve 0 c ans _  _ = (c, ans)
solve m c ans qs s = solve m' (c + dist) ans' qs' s'
  where ((dist, pos) :< qs'') = viewl qs
        new_elts = List.filter (flip Set.notMember s . snd) [(dist+1, pos-1), (dist+1, pos+1)]
        qs' = foldl (|>) qs'' new_elts
        s' = foldr (Set.insert . snd) s new_elts
        (ans', m') = if dist == 0 then (ans, m) else (pos : ans, m - 1)

main :: IO ()
main = do
  (_:m:_) <- map read . words <$> getLine
  trees   <- map read . words <$> getLine
  let (cost, ans) = solve m 0 [] (fromList $ map (0,) trees) (Set.fromList trees)
  print cost
  mapM_ (putStr . show >=> const (putStr " ")) ans >> putStrLn ""

{-# LANGUAGE TupleSections #-}

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

solve :: Int -> Integer -> [Int] -> Seq (Int, Int) -> Set.Set Int -> (Integer, [Int])
solve 0 c ans _  _ = (c, ans)
solve m c ans qs s = solve m' (c + (fromIntegral dist)) ans' qs' s'
  where ((dist, pos) :< qs'') = viewl qs
        new_elts = List.filter (flip Set.notMember s . snd) [(dist+1, pos-1), (dist+1, pos+1)]
        qs' = foldl (|>) qs'' new_elts
        s' = foldr (Set.insert . snd) s new_elts
        (ans', m') = if dist == 0 then (ans, m) else (pos : ans, m - 1)

main :: IO ()
main = do
  (_:m:_) <- map read . words <$> getLine
  trees   <- map read . words <$> getLine
  let (cost, ans) = solve m 0 [] (fromList $ map (0,) trees) (Set.fromList trees)
  print cost
  mapM_ (putStr . show >=> const (putStr " ")) ans >> putStrLn ""

{-# LANGUAGE TupleSections #-}

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

solve :: Int -> Integer -> [Int] -> Seq (Int, Int) -> Set.Set Int -> (Integer, [Int])
solve 0 c ans _  _ = (c, ans)
solve m c ans qs s = solve m' c' ans' qs' s'
  where ((dist, pos) :< qs'') = viewl qs
        new_elts = List.take m $ List.filter (flip Set.notMember s . snd) [(dist+1, pos-1), (dist+1, pos+1)]
        qs' = foldl (|>) qs'' new_elts
        s' = foldr (Set.insert . snd) s new_elts
        ans' = map snd new_elts ++ ans
        l = List.length new_elts
        m' = m - l
        c' = c + (fromIntegral $ (dist+1) * l)

main :: IO ()
main = do
  (_:m:_) <- map read . words <$> getLine
  trees   <- map read . words <$> getLine
  let (cost, ans) = solve m 0 [] (fromList $ map (0,) trees) (Set.fromList trees)
  print cost
  mapM_ (putStr . show >=> const (putStr " ")) ans >> putStrLn ""

{-# LANGUAGE TupleSections #-}

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

solve :: Int -> Int -> [Int] -> Seq (Int, Int) -> Set.Set Int -> (Int, [Int])
solve 0 c ans _  _ = (c, ans)
solve m c ans qs s = solve m' (c + dist) ans' qs' s'
  where ((dist, pos) :< qs'') = viewl qs
        new_elts = List.filter (flip Set.notMember s . snd) [(dist+1, pos-1), (dist+1, pos+1)]
        qs' = foldl (|>) qs'' new_elts
        s' = foldr (Set.insert . snd) s new_elts
        (ans', m') = if dist == 0 then (ans, m) else (pos : ans, m - 1)

main :: IO ()
main = do
  (_:m:_) <- map read . words <$> getLine
  trees   <- map read . words <$> getLine
  let (cost, ans) = solve m 0 [] (fromList $ map (0,) trees) (Set.fromList trees)
  print cost
  mapM_ (putStr . show >=> const (putStr " ")) ans >> putStrLn ""


Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny.He has a special interest to create difficult problems for others to solve. This time, with many $$$1 \times 1 \times 1$$$ toy bricks, he builds up a 3-dimensional object. We can describe this object with a $$$n \times m$$$ matrix, such that in each cell $$$(i,j)$$$, there are $$$h_{i,j}$$$ bricks standing on the top of each other.However, Serval doesn't give you any $$$h_{i,j}$$$, and just give you the front view, left view, and the top view of this object, and he is now asking you to restore the object. Note that in the front view, there are $$$m$$$ columns, and in the $$$i$$$-th of them, the height is the maximum of $$$h_{1,i},h_{2,i},\dots,h_{n,i}$$$. It is similar for the left view, where there are $$$n$$$ columns. And in the top view, there is an $$$n \times m$$$ matrix $$$t_{i,j}$$$, where $$$t_{i,j}$$$ is $$$0$$$ or $$$1$$$. If $$$t_{i,j}$$$ equals $$$1$$$, that means $$$h_{i,j}>0$$$, otherwise, $$$h_{i,j}=0$$$.However, Serval is very lonely because others are bored about his unsolvable problems before, and refused to solve this one, although this time he promises there will be at least one object satisfying all the views. As his best friend, can you have a try?

The first line contains three positive space-separated integers $$$n, m, h$$$ ($$$1\leq n, m, h \leq 100$$$) — the length, width and height. The second line contains $$$m$$$ non-negative space-separated integers $$$a_1,a_2,\dots,a_m$$$, where $$$a_i$$$ is the height in the $$$i$$$-th column from left to right of the front view ($$$0\leq a_i \leq h$$$). The third line contains $$$n$$$ non-negative space-separated integers $$$b_1,b_2,\dots,b_n$$$ ($$$0\leq b_j \leq h$$$), where $$$b_j$$$ is the height in the $$$j$$$-th column from left to right of the left view. Each of the following $$$n$$$ lines contains $$$m$$$ numbers, each is $$$0$$$ or $$$1$$$, representing the top view, where $$$j$$$-th number of $$$i$$$-th row is $$$1$$$ if $$$h_{i, j}>0$$$, and $$$0$$$ otherwise. It is guaranteed that there is at least one structure satisfying the input.

Output $$$n$$$ lines, each of them contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th line should be equal to the height in the corresponding position of the top view. If there are several objects satisfying the views, output any one of them.

Note  The graph above illustrates the object in the first example.    The first graph illustrates the object in the example output for the second example, and the second graph shows the three-view drawing of it.

import Control.Monad
import Data.List

solve ::[Int]           -> [Int] -> [Int] ->[[Int]] ->[[Int]]
solve [breite,tiefe,hoehe] front    seite    oben =foben oben $   ffront fseite
	where
		fseite :: [[Int]]
		fseite =map (replicate breite) seite
		ffront :: [[Int]] -> [[Int]]
		ffront g = map (zipWith min front) g

foben :: [[Int]]->[[Int]]->[[Int]]
foben oben g2 = zipWith helper oben g2
	where
		helper :: [Int] -> [Int] -> [Int]
		helper oben z2 = zipWith (\o z -> if o==1 then z else 0) oben z2

main :: IO ()
main = do
	[tiefe,breite,hoehe] <- fmap ((map read).words) getLine
	front <- fmap ((map read).words) getLine
	seite <- fmap ((map read).words) getLine
	oben <- replicateM tiefe $ fmap ((map read).words) getLine
	putStrLn $           intercalate "\n" $ map (concat.(intersperse " ")) $ map (map show) $ solve [breite,tiefe,hoehe] front seite oben
	return ()

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}

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

main :: IO ()
main = do
  [n,m,h] <- map readInt . words <$> getLine
  as <- unfoldr (runStateT rIntS) <$> BS.getLine
  bs <- unfoldr (runStateT rIntS) <$> BS.getLine
  forM_ bs $ \ !b -> do
    hs <- unfoldr (runStateT rIntS) <$> BS.getLine
    putStrLn $ unwords $ map show
      $ zipWith (\h a -> if h==0 then 0 else min a b) hs as

rInt :: StateT BSL.ByteString Maybe Int
rInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')
rIntS :: StateT BS.ByteString Maybe Int
rIntS = StateT $ BS.readInt . BS.dropWhile (<'!')

#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read
#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling
C(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)
C(toInt,readInt,floorInt,ceilInt,Int)
C(toI8,readI8,floorI8,ceilI8,Int8)
C(toI16,readI16,floorI16,ceilI16,Int16)
C(toI32,readI32,floorI32,ceilI32,Int32)
C(toI64,readI64,floorI64,ceilI64,Int64)
C(toWord,readWord,floorWord,ceilWord,Word)
C(toW8,readW8,floorW8,ceilW8,Word8)
C(toW16,readW16,floorW16,ceilW16,Word16)
C(toW32,readW32,floorW32,ceilW32,Word32)
C(toW64,readW64,floorW64,ceilW64,Word64)
D(toDouble,readDouble,Double)
D(toFloat,readFloat,Float)
#undef D
#undef C

{-# INLINE wrA #-}
wrA = A.writeArray
{-# INLINE rdA #-}
rdA = A.readArray
{-# INLINE mdA #-}
mdA arr f i = do
  ai <- rdA arr i
  let fai = f ai
  wrA arr i fai
  return (ai,fai)
{-# INLINE mdA' #-}
mdA' arr f i = do
  !ai <- rdA arr i
  let !fai = f ai
  wrA arr i fai
  return (ai,fai)
{-# INLINE swapA #-}
swapA arr i j = do
  ai <- rdA arr i
  wrA arr i =<< rdA arr j
  wrA arr j ai

#define N(f,g,a,m)\
  f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\
  g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_
#define C(a,m)
N(newIOA,newIOA_,IOArray,IO)
N(newSTA,newSTA_,STArray s,ST s)
#undef C
#define C(a,m) MArray (a) e (m),
N(newIOUA,newIOUA_,IOUArray,IO)
N(newSTUA,newSTUA_,STUArray s,ST s)
#undef C
#undef N


The Queen of England has n trees growing in a row in her garden. At that, the i-th (1 ≤ i ≤ n) tree from the left has height ai meters. Today the Queen decided to update the scenery of her garden. She wants the trees' heights to meet the condition: for all i (1 ≤ i < n), ai + 1 - ai = k, where k is the number the Queen chose.Unfortunately, the royal gardener is not a machine and he cannot fulfill the desire of the Queen instantly! In one minute, the gardener can either decrease the height of a tree to any positive integer height or increase the height of a tree to any positive integer height. How should the royal gardener act to fulfill a whim of Her Majesty in the minimum number of minutes?

The first line contains two space-separated integers: n, k (1 ≤ n, k ≤ 1000). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 1000) — the heights of the trees in the row.

In the first line print a single integer p — the minimum number of minutes the gardener needs. In the next p lines print the description of his actions.  If the gardener needs to increase the height of the j-th (1 ≤ j ≤ n) tree from the left by x (x ≥ 1) meters, then print in the corresponding line "+ j x". If the gardener needs to decrease the height of the j-th (1 ≤ j ≤ n) tree from the left by x (x ≥ 1) meters, print on the corresponding line "- j x". If there are multiple ways to make a row of trees beautiful in the minimum number of actions, you are allowed to print any of them.

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i judge incr step = sub i
    where
    sub i | judge i = step i >> sub (incr i) | otherwise = return ()
inf = maxBound `div` 2 :: Int

main = do
    (n,k) <- readIntPair
    as <- readInts
    let l = head $ sortBy cmpLen $ do
        i <- [1..1000]
        let result = [i + k * j | j <- [0..]]
        return $ filter ((/=0).snd) $ zip [1..] $ zipWith (-) result as
    print $ length l
    forM_ l $ \(i,x) ->
        putStrLn $ unwords [(if x > 0 then "+" else "-"),show i,show $ abs x]

import Data.List
import Data.Char
import Data.Maybe
import Data.Tuple
import Debug.Trace
import Data.Array
import Data.Array.IO
import Control.Monad
import Control.Applicative
import Control.Arrow
import qualified Data.ByteString.Char8 as B
import qualified Data.Map as M
import Text.Printf

readInt :: B.ByteString -> Int
readInt = fst . fromJust . B.readInt

readInt2 :: B.ByteString -> (Int, Int)
readInt2 = l2t . map readInt . B.words
l2t [x,y] = (x,y)

(|>) x f = f x; infixl 1 |>
car = head
cadr = head . tail

main :: IO ()
main = do
    ls <- B.lines <$> B.getContents
    let (n, k) = car ls |> readInt2
        xs = cadr ls |> B.words |> map (fst . fromJust . B.readInt)
        xs' = map (\(x, i) -> x - i * k) $ zip xs [0 .. ]
        m = majority $ filter (> 0) xs'
        cs = xs' |> zip [1 .. ]
                 |> filter (\e -> (snd e) /= m)
                 |> map (diff m)

    -- print xs'
    -- print m
    print $ length cs
    forM_ cs putStrLn

majority ls =
    head $ snd $ head $ reverse $ sort $ map (\l -> (length l, l)) $ group $ sort ls

diff m (i, x) =
    (if x < m then "+ " else "- ") ++ show i ++ " " ++ show (abs (m - x))

import Data.List
import Data.Char
import Data.Maybe
import Data.Tuple
import Debug.Trace
import Data.Array
import Data.Array.IO
import Control.Monad
import Control.Applicative
import Control.Arrow
import qualified Data.ByteString.Char8 as B
import qualified Data.Map as M
import Text.Printf

readInt :: B.ByteString -> Int
readInt = fst . fromJust . B.readInt

readInt2 :: B.ByteString -> (Int, Int)
readInt2 = l2t . map readInt . B.words
l2t [x,y] = (x,y)

(|>) x f = f x; infixl 1 |>
car = head
cadr = head . tail

main :: IO ()
main = do
    ls <- B.lines <$> B.getContents
    let (n, k) = car ls |> readInt2
        xs = cadr ls |> B.words |> map (fst . fromJust . B.readInt)
        xs' = map (\(x, i) -> x - i * k) $ zip xs [0 .. ]
        m = majority xs'
        cs = xs' |> zip [1 .. ]
                 |> filter (\e -> (snd e) /= m)
                 |> map (diff m)

    print $ length cs
    forM_ cs putStrLn

majority ls =
    head $ snd $ head $ reverse $ sort $ map (\l -> (length l, l)) $ group $ sort ls

diff m (i, x) =
    (if x < m then "+ " else "- ") ++ show i ++ " " ++ show (abs (m - x))


Danny, the local Math Maniac, is fascinated by circles, Omkar's most recent creation. Help him solve this circle problem!You are given $$$n$$$ nonnegative integers $$$a_1, a_2, \dots, a_n$$$ arranged in a circle, where $$$n$$$ must be odd (ie. $$$n-1$$$ is divisible by $$$2$$$). Formally, for all $$$i$$$ such that $$$2 \leq i \leq n$$$, the elements $$$a_{i - 1}$$$ and $$$a_i$$$ are considered to be adjacent, and $$$a_n$$$ and $$$a_1$$$ are also considered to be adjacent. In one operation, you pick a number on the circle, replace it with the sum of the two elements adjacent to it, and then delete the two adjacent elements from the circle. This is repeated until only one number remains in the circle, which we call the circular value.Help Danny find the maximum possible circular value after some sequences of operations.

The first line contains one odd integer $$$n$$$ ($$$1 \leq n < 2 \cdot 10^5$$$, $$$n$$$ is odd)  — the initial size of the circle. The second line contains $$$n$$$ integers $$$a_{1},a_{2},\dots,a_{n}$$$ ($$$0 \leq a_{i} \leq 10^9$$$)  — the initial numbers in the circle.

Output the maximum possible circular value after applying some sequence of operations to the given circle.

NoteFor the first test case, here's how a circular value of $$$17$$$ is obtained:Pick the number at index $$$3$$$. The sum of adjacent elements equals $$$17$$$. Delete $$$7$$$ and $$$10$$$ from the circle and replace $$$2$$$ with $$$17$$$.Note that the answer may not fit in a $$$32$$$-bit integer.

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List

main :: IO ()
main =  interact $  lines >>> drop 0 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (_ : as : rest) = (itoline . solve . linetois) as : tcio rest where
    linetoi = read
    itoline = show
    linetois = (map linetoi) . words
    istoline = unwords . (map itoline)
    linestoiss = (map linetois) . lines
    isstolines = unlines . (map istoline)

solve :: [Integer] -> Integer
solve (a:[]) = a
solve as = maximum $ map (uncurry (+)) $ zip (0:ls) rs where
  [ls,rs] = map concat $ map ($ ((zipWith (+)), chunk as)) (map uncurry [scanl1, scanr1])
  chunk (a:[]) = [[a,0]]
  chunk (a:b:xs) = [a,b] : chunk xs

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List

main :: IO ()
main =  interact $  lines >>> drop 0 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (_ : as : rest) = (itoline . solve . linetois) as : tcio rest where
    linetoi = read
    itoline = show
    linetois = (map linetoi) . words
    istoline = unwords . (map itoline)
    linestoiss = (map linetois) . lines
    isstolines = unlines . (map istoline)

solve :: [Integer] -> Integer
solve (a:[]) = a
solve as = maximum $ map (uncurry (+)) $ zip (0:ls) rs where
  [ls,rs] = fmap concat [lss, rss]
  lss = scanl1 (zipWith (+)) $ chunk as;
  rss = scanr1 (zipWith (+)) $ chunk as;
  chunk (a:[]) = [[a,0]]
  chunk (a:b:xs) = [a,b] : chunk xs

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List

main :: IO ()
main =  interact $  lines >>> drop 0 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (_ : as : rest) = (itoline . solve . linetois) as : tcio rest where
    linetoi = read
    itoline = show
    linetois = (map linetoi) . words
    istoline = unwords . (map itoline)
    linestoiss = (map linetois) . lines
    isstolines = unlines . (map istoline)

split :: [Integer] -> ([Integer],[Integer])
split [] = ([],[])
split (x:zs) = ((x:ys), xs) where (xs,ys) = split zs

merge :: [Integer] -> [Integer] -> [Integer]
merge [] ys = ys
merge (x:xs) ys = x:(merge ys xs)

solve :: [Integer] -> Integer
solve (a:[]) = a
solve as = maximum $ map (uncurry (+)) $ zip (0:ls) rs where
  ls = merge lsum1 lsum2
  lsum1 = scanl1 (+) odds
  lsum2 = scanl1 (+) evens
  rs = merge rsum1 rsum2
  rsum1 = scanr1 (+) odds
  rsum2 = scanr1 (+) evens
  (odds,evens) = split as

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List

main :: IO ()
main =  interact $  lines >>> drop 0 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (_ : as : rest) = (itoline . solve . linetois) as : tcio rest where
    linetoi = read
    itoline = show
    linetois = (map linetoi) . words

solve :: [Integer] -> Integer
solve (a:[]) = a
solve as = maximum $ add (0:ls) rs where
  [ls,rs] = map (\f-> concat $ f add $ chunk as) [scanl1, scanr1]
  add xs ys = map (uncurry (+)) $ zip xs ys
  chunk (a:[]) = [[a,0]]
  chunk (a:b:xs) = [a,b] : chunk xs

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List

main :: IO ()
main =  interact $  lines >>> drop 0 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (_ : as : rest) = (itoline . solve . linetois) as : tcio rest where
    linetoi = read
    itoline = show
    linetois = (map linetoi) . words
    istoline = unwords . (map itoline)
    linestoiss = (map linetois) . lines
    isstolines = unlines . (map istoline)

split :: [Integer] -> ([Integer],[Integer])
split [] = ([],[])
split (x:zs) = ((x:ys), xs) where (xs,ys) = split zs

merge :: [Integer] -> [Integer] -> [Integer]
merge [] ys = ys
merge (x:xs) ys = x:(merge ys xs)

solve :: [Integer] -> Integer
solve (a:[]) = a
solve as = maximum $ map (uncurry (+)) $ zip ls (drop 1 rs) where
  ls = merge lsum1 lsum2
  lsum1 = scanl1 (+) odds
  lsum2 = scanl1 (+) evens
  rs = merge rsum1 rsum2
  rsum1 = scanr1 (+) odds
  rsum2 = scanr1 (+) evens
  (odds,evens) = split as

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List

main :: IO ()
main =  interact $  lines >>> drop 0 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (_ : as : rest) = (itoline . solve . linetois) as : tcio rest where
    linetoi = read
    itoline = show
    linetois = (map linetoi) . words
    istoline = unwords . (map itoline)
    linestoiss = (map linetois) . lines
    isstolines = unlines . (map istoline)

split :: [Int] -> ([Int],[Int])
split [] = ([],[])
split (x:zs) = ((x:ys), xs) where (xs,ys) = split zs

merge :: [Int] -> [Int] -> [Int]
merge [] ys = ys
merge (x:xs) ys = x:(merge ys xs)

solve :: [Int] -> Int
solve (a:[]) = a
solve as = maximum $ map (uncurry (+)) $ zip ls (drop 1 rs) where
  ls = merge lsum1 lsum2
  lsum1 = scanl1 (+) odds
  lsum2 = scanl1 (+) evens
  rs = merge rsum1 rsum2
  rsum1 = scanr1 (+) odds
  rsum2 = scanr1 (+) evens
  (odds,evens) = split as


Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored A·B·C hay blocks and stored them in a barn as a rectangular parallelepiped A layers high. Each layer had B rows and each row had C blocks.At the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing (A - 1) × (B - 2) × (C - 2) hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single 1 × 1 × 1 blocks and scattered them around the barn. After the theft Sam counted n hay blocks in the barn but he forgot numbers A, B и C.Given number n, find the minimally possible and maximally possible number of stolen hay blocks.

The only line contains integer n from the problem's statement (1 ≤ n ≤ 109).

Print space-separated minimum and maximum number of hay blocks that could have been stolen by the thieves. Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.

NoteLet's consider the first sample test. If initially Sam has a parallelepiped consisting of 32 = 2 × 4 × 4 hay blocks in his barn, then after the theft the barn has 4 = (2 - 1) × (4 - 2) × (4 - 2) hay blocks left. Thus, the thieves could have stolen 32 - 4 = 28 hay blocks. If Sam initially had a parallelepiped consisting of 45 = 5 × 3 × 3 hay blocks in his barn, then after the theft the barn has 4 = (5 - 1) × (3 - 2) × (3 - 2) hay blocks left. Thus, the thieves could have stolen 45 - 4 = 41 hay blocks. No other variants of the blocks' initial arrangement (that leave Sam with exactly 4 blocks after the theft) can permit the thieves to steal less than 28 or more than 41 blocks.

{-
import Test.QuickCheck
import qualified Data.Set as S
import qualified Math.NumberTheory.Primes as P
import Data.List

propDivisors :: Positive Int -> Bool
propDivisors (Positive n') = sort divs == sort (divisors n)
  where
    n = (n' `mod` 10^9)+1
    divs = map fromIntegral $ S.elems $ P.divisors (fromIntegral n)

mainTest = quickCheck propDivisors
-}

import Data.Int

triples n = [ (x,y,z) |
                x <- takeWhile (\x -> x*x*x <= n) [1..],
                n `rem` x == 0,
                let q = n `div` x,
                y <- takeWhile (\x -> x*x <= q) [x..],
                q `rem` y == 0,
                let z = q `div` y ]

stolen n x y z = [ (x'+1)*(y'+2)*(z'+2) - n', (z'+1)*(y'+2)*(x'+2) - n' ]
  where n' = fromIntegral n
        x' = fromIntegral x
        y' = fromIntegral y
        z' = fromIntegral z

solve n = (minimum ds, maximum ds)
  where trips = triples n
        ds = concatMap (\(x,y,z) -> stolen n x y z) (triples n) :: [Int64]

mainSolve = do
  n <- fmap read getLine :: IO Int
  let (a,b) = solve n
  putStrLn $ show a ++ " " ++ show b

main = mainSolve

--142A

import Data.Array
import Data.List (group, genericLength)

isDividor :: Integral a => a -> a -> Bool
isDividor m n  =  m `rem` n == 0

primes :: Integral a => [a]
primes  =  2 : filter isPrime [3, 5 ..]

isPrime :: Integral a => a -> Bool
isPrime n  =  all (not . isDividor n) (takeWhile (\x -> x * x <= n) primes)

factorize :: Integral a => a -> [a]
factorize 0  =  []
factorize n  =  factorize' n primes
  where
    factorize' 1 _  =  []
    factorize' n (p:ps)
      | r == 0  =  p : factorize' q (p:ps)
      | q < p  =  [n]  -- i.e. p * p > n
      | otherwise  =  factorize' n ps
      where
        (q, r)  =  quotRem n p

factorizeP :: Integral a => a -> [(a, a)]
factorizeP  =  map (\x -> (head x, genericLength x)) . group . factorize

dividers :: Integral a => a -> [a]
dividers n  =  dividers' empty
  where
    fs  =  factorizeP n
    k   =  length fs
    empty  =  accumArray undefined 0 (1,k) []
    dividers' array  =  d : case (nextArray 1) of
        Nothing  ->  []
        Just array'  ->  dividers' array'
      where
        d  =  product $ zipWith (^) (map fst fs) (elems array)
        nextArray i
          | i > k  =  Nothing
          | array ! i == (snd $ fs !! (i-1))  =  nextArray (i+1)
          | otherwise  =  Just $ array // ((i, array ! i + 1) : [(j, 0) | j <- [1..i-1]])

solve :: Integer -> (Integer, Integer)
solve n  =  (min - n, max - n)
  where
    min  =  minimum all
    max  =  maximum all
    all  =  [v y z | y <- ds, z <- ds, y <= z, y * z <= n, n `mod` (y * z) == 0]
    ds   =  dividers n
    v y z  =  (x + 1) * (y + 2) * (z + 2)
      where
        x  =  n `div` (y * z)

printP :: Show a => (a, a) -> IO ()
printP (a,b)  =  putStrLn $ show a ++ " " ++ show b

main :: IO ()
main  =  readLn >>= printP . solve

import Control.Applicative

main = do n <- read <$> getLine
          putStrLn $ unwords $ map show $ solve n

solve :: Integer -> [Integer]
solve n = [(minimum ms),(maximum ms)]
   where ms = map (\ [x,y,z] -> (x+1)*(y+2)*(z+2)-n) $ concatMap (\x -> map (\y -> [(div n x),y,(div x y)]) $ f x) $ f n

f :: Integer -> [Integer]
f n = f' $ filter ((0==).mod n) $ takeWhile (\x -> x*x <= n) [1..]
   where f' ns = ns ++ (map (div n) ns)

import Control.Applicative

main = do n <- read <$> getLine
          putStrLn $ unwords $ map show $ solve n

solve :: Integer -> [Integer]
solve n = map (subtract n) [(minimum ms),(maximum ms)]
   where ms = concatMap ((\ [x,y] -> concatMap (g.(y:)) (f x))) $ f n

f :: Integer -> [[Integer]]
f n = map (\x -> [(div n x),x]) $ (1:) $ filter ((0==).mod n) $ takeWhile (\x-> x*x <= n) primes

g [x,y,z] = [(x+1)*(y+2)*(z+2),(y+1)*(z+2)*(x+2),(z+1)*(x+2)*(y+2)]

primes = 2 : filter (\x -> isPrime x primes) [3,5..]
isPrime n (x:xs) = (n < x*x) || ((mod n x /= 0) && (isPrime n xs))

s n=show(minimum l)++" "++show(maximum l) where l=[(x+1)*(y+2)*(z+2)-n|a<-[1..1000],b<-[1..1000],let c=n`div`a`div`b,c*a*b==n,(x,y,z)<-[(a,b,c),(b,a,c),(c,b,a)]]
main=interact$unwords.map show.s.read