import Data.List
main::IO()
main=do
	n<-getLine
	input<-getLine
	let
		(x:a)=sort $ map read (words input)::[Int]
		is=foldl (\a b -> a && b `mod` x ==0 ) True a
	print $ if is then x else -1

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

main = do
	getLine
	(a:as) <- sort . map read . words <$> getLine
	print $ if all ( ( == 0 ) . ( `mod` a ) ) as then a else -1

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

main = do
	getLine
	(a:as) <- sort . map read . words <$> getLine
	print $ if solve a as then a else -1

solve n [] = True
solve n (a:as)
	| mod a n == 0 = solve n as
	| otherwise = False

main = do
    a <- map (read :: String -> Int ) . words  <$> (getLine >> getLine)
    let b = foldr1 gcd a
    print $ if b `elem` a then b else -1

import Data.List

verify k []     = k
verify k (x:xs) = if x `mod` k == 0 then verify k xs else -1

check (x:xs) = verify x xs

main = interact $ show . check . sort . map read . tail . words

import Data.List

verify k []     = k
verify k (x:xs) = if x `mod` k == 0 then verify k xs else -1

check (x:xs) = verify x xs

unique ::[Int] -> [Int]
unique [] = []
unique [x] = [x]
unique (x:y:xs) = if x /= y then x : (unique $ y: xs) else unique $ y: xs

main = interact $ show . check . unique . sort . map read . tail . words

import Control.Monad (liftM)
import Prelude hiding (reads)

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

solve :: [Int] -> Int
solve as
  | all ((== 0) . flip mod min) as  =  min
  | otherwise  =  -1
  where
    min  =  minimum as

main :: IO ()
main  =  do
    getLine
    as  <-  reads
    print $ solve as

import Data.List (foldl')

main = getLine >> fmap (solve.map read.words) getLine >>= print

solve :: [Integer] -> Integer
solve xs = foldl' f ans xs
   where ans = minimum xs
         f (-1) _ = -1
         f ans next | mod next ans == 0 = ans
                    | otherwise = -1

import Data.List (foldl')

main = getLine >> fmap (solve.map read.words) getLine >>= print

solve :: [Integer] -> Integer
solve xs = if isP then ans else -1
   where (isP, ans) = foldl' f (True, head xs) (tail xs)
         f (isP', ans') next | g == next = (True, g)
                             | g == ans' = (isP', g)
                             | otherwise = (False, g)
            where g = gcd ans' next

main = getLine >> getLine >>= print . foldr1 gcd . map (read :: String -> Int ) . words

main = do
    a <- map (read :: String -> Int ) . words  <$> (getLine >> getLine)
    let b = foldr1 gcd a
    print $ if b /= 1 || (b == 1 && 1 `elem` a) then b else -1

import Data.List

verify k []     = k
verify k (x:xs) = if x `mod` k == 0 then verify k xs else -1

check (x:xs) = verify x xs

unique ::[Int] -> [Int]
unique [] = []
unique [x] = [x]
unique (x:y:xs) = if x /= y then x : (unique $ y: xs) else unique $ y: xs

-- main = interact $ show . check . unique . sort . map read . tail . words
main = interact $ show . unique . sort . map read . tail . words

import Data.List (foldl')

main = getLine >> fmap (solve.map read.words) getLine >>= print

solve :: [Int] -> Int
solve xs = foldl' f (head xs) (tail xs)
   where f (-1) _ = -1
         f current next | mod next current == 0 = current
                        | mod current next == 0 = next
                        | otherwise = -1


import Control.Monad
import Data.Array.Unboxed
import Data.Maybe
import qualified Data.ByteString.Char8 as B

readListLn :: IO [Int]
readListLn = (map (fst . fromJust . B.readInt) . B.words) `liftM` B.getLine

main :: IO ()
main = do
    n <- readLn :: IO Int
    ss <- forM [1..n] (const readListLn)
    let arrHome = accumArray (+) 0 (1, 10^5) $ map (\[x, _] -> (x, 1)) ss :: UArray Int Int
--  let arrForeign = accumArray (+) 0 (1, 10^5) $ map (\[_, y] -> (y, 1)) ss :: UArray Int Int
    forM_ ss $ \[_, y] -> do
        putStrLn $ let native = 2 * (n - 1) - forgn
                       forgn = n - 1 - arrHome ! y
                   in (show native) ++ " " ++ (show forgn)

{-# LANGUAGE OverloadedStrings #-}

import Control.Applicative ((<$>))
import Control.Monad
import Text.Printf
import Data.Maybe (Maybe, fromMaybe)
import Data.List
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as BS

solve :: [(Int, Int)] -> [(Int, Int)]
solve s = map f s
  where (xs, ys) = unzip s
        xCnts = countof $ countup xs
        enemy = (length s) - 1
        f (x, y) = (enemy + dup, enemy - dup)
          where dup = xCnts y

main :: IO ()
main = do
  n <- readInt
  c <- replicateM n $ toTuple <$> readInts
  forM_ (solve c) $ \(a, b) -> do
    printf "%d %d\n" a b

toTuple [a, b] = (a, b)
toNumber = fst . fromMaybe (0, "")
readInt = toNumber . BS.readInt <$> BS.getLine
readInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))

countup = foldl' (\x y -> M.insertWith' (+) y 1 x) M.empty
countof m x = M.findWithDefault 0 x m

{-# LANGUAGE BangPatterns #-}

import Data.Maybe
import Data.List
import qualified Data.IntMap.Strict as IM
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as LBS
import Control.Applicative ((<$>))
import Control.Arrow ((&&&), first, second)
import Control.Monad
import Text.Printf (printf)

main :: IO ()
main = do
  n <- readLn :: IO Int
  teams <- replicateM n $ (map (fst . fromJust . BS.readInt) . BS.words) <$> BS.getLine :: IO [[Int]]
  let !table = IM.fromList . map (head &&& length) . group . sort . map head $ teams
  forM_ (zip [1..] teams) $ \(i, [_, away]) -> do
    let !c = n - 1 + IM.findWithDefault 0 away table
    printf "%d %d\n" c (2 * (n - 1) - c)

{-# LANGUAGE TupleSections #-}

-- For Input
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
--import qualified Data.ByteString.Lex.Double as BSD
import Data.Char (isSpace)
import Data.IORef
import Text.Printf

-- Data Structure Imports
import Data.Maybe
import Data.Function
import Data.List
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map

-- These should be imported by default... :)
import Control.Monad
import Control.Applicative
import Control.Arrow

--------------------------------------------------------------------------------
------------------------------- SOLUTION ---------------------------------------
--------------------------------------------------------------------------------

main :: IO ()
main = do
  all   <- BS.getContents
  input <- newIORef all
  let parse = next input
  n <- parse int
  (hs,as) <- fmap unzip $ parse $ readMany int2 n
  let home = Map.fromList . map (head &&& length) . group $ sort hs
  forM_ as $ \a ->
      let extraHome = Map.findWithDefault 0 a home
      in putStrLn $ show (n + extraHome - 1) ++ " " ++ show (n - extraHome - 1)

--------------------------------------------------------------------------------
-------------------------- IO Function Helpers ---------------------------------
--------------------------------------------------------------------------------

type Parser a = BSC.ByteString -> (a, BSC.ByteString)

int :: Parser Int
int = second (BSC.dropWhile isSpace) . fromJust . BSC.readInt

int2 :: Parser (Int, Int)
int2 = uncurry (first . (,)) . second int . int

int3 :: Parser (Int, Int, Int)
int3 = uncurry (first . (uncurry (,,))) . second int . int2

--double :: Parser Double
--double = second (BSC.dropWhile isSpace) . fromJust . BSD.readDouble

char :: Parser Char
char = BSC.head &&& BSC.tail

letter :: Parser Char
letter = second (BSC.dropWhile isSpace) . char

string :: Parser String
string = (BSC.unpack *** BSC.dropWhile isSpace) . BSC.span (not . isSpace)

readMany :: Parser a -> Int -> Parser [a]
readMany f n bs = first reverse $
                  foldr (\_ (l,bs) -> first (:l) $ f bs) ([],bs) [1..n]

intMany :: Int -> Parser [Int]
intMany = readMany int

next :: IORef BSC.ByteString -> Parser a -> IO a
next input parse = do
  bs <- readIORef input
  let (x, bs') = parse bs
  writeIORef input bs'
  return x

{- CODE JAM input

  cases <- parse int
  forM_ [1..cases] $ \caseNum -> do
         -- Read Data
         -- let solution =
         -- solution <-
         printf "Case #%d: %d\n" caseNum solution
-}


import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Maybe
main=getLine>>map(fst.fromJust.B.readInt).B.words<$>B.getLine>>=print.maximum.map(\l->if head l==0 then 0 else length l).group.take 400000.cycle

longestOnesSequence ans cur [] = ans
longestOnesSequence ans cur (0:xs) = longestOnesSequence ans 0 xs
longestOnesSequence ans cur (1:xs) = longestOnesSequence (max ans $ cur + 1) (cur + 1) xs

main = do
    line' <- getLine
    line <- getLine
    let arr = map read $ words line
    putStrLn . show $ longestOnesSequence 0 0 $ arr ++ arr

foldInt :: (Int, Int) -> Char -> (Int, Int)
foldInt (a,b) '0' = (0,b)
foldInt (a,b) '1' = (a+1, max b (a+1))
foldInt (a,b) _ = (a,b)

calc :: [Char] -> Int
calc c = snd $ foldl foldInt (0,0) c

main = do {
    n <- getLine;
    a <- getLine;
    putStrLn $ show $ calc (a++a);
}

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

process0 [] = 0
process0 (x:xs) = case x of
  0 -> process0 xs
  1 -> process1 1 xs

process1 n [] = n
process1 n (x:xs) = case x of
  1 -> process1 (n + 1) xs
  0 -> max n (process0 xs)

main = do
  throwaway <- getLine
  line <- getLine
  let
    info :: [Integer]
    info = map read $ words line
  print (process0 (info ++ info))

module Main where
-- import qualified Data.ByteString.Char8 as C
import Control.Monad
import Data.List
{- main =  do
    C.getLine
    a <-  C.filter (\x -> x /= ' ')  <$> C.getLine
    let  b = map C.length $ filter (C.elem '1') $ C.group $ C.concat $ [a,a]
    print $ if null b then 0 else maximum b
-}

main =  do
    getLine
    a <-  filter (\x -> x /= ' ')  <$> getLine
    let  b = map length $ filter ('1' `elem`) $ group $ concat $ [a,a]
    print $ if null b then 0 else maximum b

solve [] res cur = max res cur
solve (0:xs) res cur = solve xs (max res cur) 0
solve (1:xs) res cur = solve xs res (cur + 1)

main = do
    n <- (read :: String -> Int) <$> getLine
    lst <- (map read :: [String] -> [Int]) <$> words <$> getLine
    putStrLn (show (min n (solve (lst ++ lst) 0 0)))

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

import qualified Data.ByteString.Char8 as B
readInt = readLn :: IO Int
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

solve :: [Int] -> Int
solve xs
    | all (==0) xs = 0
    | otherwise    = (maximum . map length . filter ((==1) . head) . group) ys
    where ys = xs ++ xs

main :: IO ()
main = do
    _ <- readInt
    xs <- readInts
    print $ solve xs

import Data.List
main = interact $ show . solve . map read . tail . words
solve as = maximum $ (0 :) $ map length $ filter ((> 0) . head) $ group $ as ++ as

-- import Debug.Trace
import Text.Printf
import Control.Monad

glwr :: Read a => IO [a]
glwr = fmap (map read . words) getLine

main :: IO ()
main = do
  _ <- getLine
  ls <- glwr
  print $ maxConRest ls

maxConRest xs = uncurry max $ foldr accMax (length h, 0) ls
  where
    (h, ls) = break (< 1) xs

accMax n (r, m)
  | n < 1 = (0, max r m)
  | 0 < 1 = (r+1, m)

import Data.List

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

solve :: [Int] ->  Int
solve = maximum . map sum . group . duplList

duplList :: [Int] -> [Int]
duplList l = l ++ l

{-# LANGUAGE Safe #-}
{-# Options_GHC -O2 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)
import Data.Char
import Data.List

getSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO 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

solve :: [Int] -> Int
solve (n:a')
  | all (== 0) a = 0
  | otherwise = maximum $map length $ filter ( ( == 1) . head) $ group $ a ++ a
  where
    a = take n a'

main :: IO ()
main = print . solve . map ru . C.words =<< C.getContents

import Data.List

solve :: [Int] -> Int
solve xs = ts where
  ts = if all (\x -> x == 0) xs then 0
       else maximum . map length .
            filter (all (\x -> x == 1)) . group $ (xs ++ xs)

rInt :: String -> Int
rInt = read

main :: IO ()
main = interact $ show. solve . head . (map . map) rInt .  map words . tail . lines

{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

--import Debug.Trace

import System.IO
import GHC.Generics
import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Monoid
import Data.Maybe
import Data.Either
import Data.Ord
import Data.Ratio
import qualified Data.Foldable as Foldable
import Data.Char
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.List
import Data.Array.IArray
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA
import qualified Data.Array.ST.Safe as SA
import qualified Data.Array.IO.Safe as IA
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.Bits

getWords  = words <$> getLine :: IO [String]
getInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]
getDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]
getInt    = read <$> getLine :: IO Int
getDouble  = read <$> getLine :: IO Double
printLines :: Show a => [a] -> IO ()
printLines = mapM_ print
printStrs = mapM_ putStrLn :: [String] -> IO ()
printList = putStrLn . intercalate " " . map show :: [Int] -> IO ()

---- Answer Code Section ----

process :: [Int] -> Int
process hours = maximum . map (\l -> if head l == 0 then 0 else length l) . group . take (length hours * 2) . cycle $ hours

main = do
    n <- getInt
    hours <- getInts
    print $ process hours

import Data.List
f ("0":_)=0
f l=length l
main=getLine>>getLine>>=print.maximum.map f.group.take 400000.cycle.words

import Data.List
main=getLine>>map read.words<$>getLine>>=print.maximum.map(\l->if head l==0 then 0 else length l).group.take 400000.cycle

{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

--import Debug.Trace

import System.IO
import GHC.Generics
import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Monoid
import Data.Maybe
import Data.Either
import Data.Ord
import Data.Ratio
import qualified Data.Foldable as Foldable
import Data.Char
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.List
import Data.Array.IArray
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA
import qualified Data.Array.ST.Safe as SA
import qualified Data.Array.IO.Safe as IA
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.Bits

getWords  = words <$> getLine :: IO [String]
getInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]
getDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]
getInt    = read <$> getLine :: IO Int
getDouble  = read <$> getLine :: IO Double
printLines :: Show a => [a] -> IO ()
printLines = mapM_ print
printStrs = mapM_ putStrLn :: [String] -> IO ()
printList = putStrLn . intercalate " " . map show :: [Int] -> IO ()

---- Answer Code Section ----

main = getInt >> getInts >>= print . maximum . map (\l -> if head l == 0 then 0 else length l) . group . take 400000 . cycle

readBool a = if (read a) == 0 then True else False

solve sch = (pre + head l) : (tail l)
  where
    findPre (True : _) = 0
    findPre (False : l) = 1 + findPre l
    pre = findPre sch
    calcL [] acc res = acc : res
    calcL (True : l) acc res = calcL l 0 (acc : res)
    calcL (False : l) acc res = calcL l (acc + 1) res
    l = calcL sch 0 []

main = do
  a <- getLine
  sch <- fmap ((map readBool) . words) getLine
  putStrLn . show . maximum $ solve sch

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

main =  do
    C.getLine
    a <-  C.filter (\x -> x /= ' ')  <$> C.getLine
    let  b = map C.length $ filter (C.elem '1') $ C.group $ C.concat $ [a,a]
    print $ if null b then 0 else maximum b

import Data.List
main=getLine>>getLine>>=print.maximum.groupBy(\a b->a==b&&b=="1").take 400000.cycle.words


import Data.List
import Data.Either
import Control.Monad

isgood :: [String] -> Bool
isgood s@[a,b,c] = "abc" == (map head s) && (length c `elem` map length [a, b])
isgood _ = False

main = do
  s <- fmap group getLine
  putStrLn $ if isgood s then "YES" else "NO"

import Data.List

main = do
  s <- getLine
  let ta = length . elemIndices 'a' $ s
  let tb = length . elemIndices 'b' $ s
  let tc = length . elemIndices 'c' $ s
  let p1 = ta > 0 && tb > 0 && (tc == ta || tc == tb)
  let p2 = s == sort s
  putStrLn $ if p1 && p2 then "YES" else "NO"

main = interact $ f.g.head.lines

g :: String -> Bool
g s = length a > 0 && length b > 0 && length d == 0 && (length a == length c || length b == length c)
      where (a, bcd) = span (== 'a') s
            (b, cd)  = span (== 'b') bcd
            (c, d)   = span (== 'c') cd

f :: Bool -> String
f True = "YES\n"
f False = "NO\n"

main = interact $ f.g.head.lines

g :: String -> Bool
g s = length d == 0 && (length a == length c || length b == length c)
      where (a, bcd) = span (== 'a') s
            (b, cd)  = span (== 'b') bcd
            (c, d)   = span (== 'c') cd

f :: Bool -> String
f True = "YES\n"
f False = "NO\n"

main = interact $ f.g

g :: String -> Bool
g s = length d == 0 && (length a == length c || length b == length c)
      where (a, bcd) = span (== 'a') s
            (b, cd)  = span (== 'b') bcd
            (c, d)   = span (== 'c') cd

f :: Bool -> String
f True = "YES\n"
f False = "NO\n"


import Data.Char
import Data.List

main=interact$solve.filter(not.null).map(dropWhile(' '==)).tail.lines

solve :: [String] -> String
solve (x:xs)
  | isPrefixOf "try" x = solve xs
  | isPrefixOf "catch" x = solve xs
  | otherwise = throw etype xs
   where
     etype = filter isAlpha.dropWhile('('/=)$x

throw etype [] = "Unhandled Exception"
throw etype (x:xs)
  | isPrefixOf "try" x = throw etype $ go 1 xs
  | etype == ctype = cmsg
  | otherwise = throw etype xs
   where
     (y,('\"':z)) = break('\"'==).dropWhile('('/=)$x
     ctype = filter isAlpha y
     cmsg = takeWhile ('\"' /=)z

go 0 xs = xs
go try (x:xs)
 | isPrefixOf "try" x = go (try+1) xs
 | otherwise = go (try-1) xs

{-# LANGUAGE BangPatterns #-}

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

import Data.Char
import Data.List

newtype Parser a = Parser { runParser :: String -> (a,String) }

instance Functor Parser where
    fmap f (Parser a) = Parser (a >>> first f)

instance Monad Parser where
    Parser p >>= f =  Parser (\s ->
        let (a,s') = p s in runParser (f a) s')
    return a = Parser (\s -> (a,s))

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

data Op = Try | Throw String | Catch String String | Nop deriving(Show)

parseLine :: Parser Op
parseLine = do
    spaces
    tk <- token
    case tk of
        "try" -> return Try
        "throw" -> do
            s <- paren token
            return (Throw s)
        "catch" -> paren $ do
            ex <- token
            comma
            ms <- dquoted letters
            return $ Catch ex ms
        _ -> return Nop

peek :: Parser Char
peek = Parser $ \(c:cs) -> (c,c:cs)

consume :: Parser ()
consume = Parser $ \(c:cs) -> ((),cs)

spaces = do
    ch <- peek
    if ch == ' ' then consume >> spaces else return ()

token = do
    c <- peek
    if isAlphaNum c then do
        consume
        cs <- token
        return (c:cs)
    else spaces >> return ""

paren p = do
    consume
    spaces
    a <- p
    consume
    spaces
    return a

comma = consume >> spaces
dquoted p = do
    consume
    l <- p
    consume
    return l

letters = do
    c <- peek
    if c == '"' then return "" else do
        consume
        cs <- letters
        return (c:cs)

main = do
    n':ss <- lines <$> getContents
    let n = read n'
    let p = flip map (take n ss) (\s -> fst $ runParser parseLine (s++"\n"))
    let !ps = fst $ parsePrograms p
    let !res = execProgram ps
    case res of
        Message s -> putStrLn s
        Exception ex -> putStrLn "Unhandled Exception"

data Program = PTryCatch String String [Program]
             | PThrow String
             | PNop deriving(Show)

parsePrograms :: [Op] -> ([Program],[Op])
parsePrograms [] =  ([],[])
parsePrograms ops@(Catch _ _:_) = ([],ops)
parsePrograms ops = (p:ps,ops'')
    where
    (p,ops') = parseProgram ops
    (ps,ops'') = parsePrograms ops'

parseProgram :: [Op] -> (Program,[Op])
parseProgram (Throw ex:ops) = (PThrow ex,ops)
parseProgram (Nop:ops) = (PNop,ops)
parseProgram (Try:ops) = (PTryCatch ex ms ps,ops')
    where
    (ps,Catch ex ms:ops') = parsePrograms ops

data RVal = Unit | Exception String | Message String
    deriving(Show)

execProgram :: [Program] -> RVal
execProgram ps = go ps
    where
    go [] = Unit
    go (PNop:ps) = go ps
    go (PThrow ex:ps) = Exception ex
    go (PTryCatch ex ms p:ps) = case execProgram p of
        Exception ex' | ex == ex' -> Message ms
        Unit -> go ps
        v -> v

import Maybe (fromMaybe)
import Monad (liftM)

{-
import HUnit

testParseLine :: Test
testParseLine  =  TestList "TestParseLine"
  [
    Test "#1" $ assertEq EmptyLine $ parseLine "",
    Test "#2" $ assertEq EmptyLine $ parseLine "    ",
    Test "#3" $ assertEq Try $ parseLine "try",
    Test "#4" $ assertEq Try $ parseLine "  try    ",
    Test "#5" $ assertEq (Throw "abc") $ parseLine "throw(abc)",
    Test "#6" $ assertEq (Throw "abc") $ parseLine "throw (   abc   )   ",
    Test "#7" $ assertEq (Throw "abc") $ parseLine "    throw (abc)",
    Test "#8" $ assertEq (Catch "abc" "is abc") $ parseLine "catch(abc,\"is abc\")",
    Test "#9" $ assertEq (Catch "abc" "is abc") $ parseLine "  catch   ( abc  ,  \"is abc\"  )  ",
    Test "#10" $ assertEq (Catch "abc" "is abc") $ parseLine "  catch   (abc,\"is abc\")",
    Test "#11" $ assertEq (Catch "abc" "fdfd") $ parseLine "  catch   (abc,\"fdfd\")"

  ]

testInput :: Test
testInput  =  Test "TestInput" $ assertEq (Just "is something") $ solve
  [
    "try                        ",
    "    try                    ",
    "        throw(A)           ",
    "    catch(B,\"is B\")      ",
    "    try                    ",
    "                           ",
    "    catch(A,\"is A\")      ",
    "catch(A,\"is something\")  "
  ]

test :: IO ()
test  =  mapM_ run
  [
    testParseLine,
    testInput
  ]
-}

type Type  =  String
type Message  =  String

data Line  =  EmptyLine | Try | Throw Type | Catch Type Message
  deriving
    (Eq, Show)

(?) :: Bool -> a -> a -> a
(?) True   =  const
(?) False  =  flip const

replace :: Eq a => [a] -> a -> [a] -> [a]
replace cs c s  =  map (\x -> (elem x cs) ? c $ x) s

parseLine :: String -> Line
parseLine line  =  case words (replace "()," ' ' line) of
    []  ->  EmptyLine
    ["try"]  ->  Try
    ["throw", s]  ->  Throw s
    ("catch" : s1 : _)  ->  Catch s1 (getMessage line)
  where
    getMessage  =  takeWhile (/= '\"') . tail . dropWhile (/= '\"')

solve :: [String] -> Maybe String
solve lines  =  solve' Nothing 0 (map parseLine lines)
  where
    solve' _ _ []  =  Nothing
    solve' Nothing n (line : lines)  =  case line of
        EmptyLine  ->  solve' Nothing        n    lines
        Try        ->  solve' Nothing       (n+1) lines
        Throw t    ->  solve' (Just (t, n))  n    lines
        Catch _ _  ->  solve' Nothing       (n-1) lines
    solve' f@(Just (t', n')) n (Catch t m : lines)
      | n' /= n  =  solve' f (n-1) lines
      | t' /= t  =  solve' (Just (t', n'-1)) (n-1) lines
      | otherwise  =  Just m
    solve' f@(Just (t', n')) n (line : lines)  =  case line of
        EmptyLine  ->  solve' f n lines
        Try        ->  solve' f (n+1) lines
        Throw t    ->  error $ concat ["find two throw in lines: ", show n', ", ", show n]

main :: IO ()
main  =  do
    n  <-  readLn
    lines'  <-  liftM (take n . lines) getContents
    putStrLn $ fromMaybe "Unhandled Exception" $ solve lines'

{-# LANGUAGE OverloadedStrings #-}

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

main :: IO ()
main = do
  _ <- getLine
  ans <- solve <$> B.getContents
  case ans of
    Catched msg -> B.putStrLn msg
    _ -> putStrLn "Unhandled Exception"

solve :: B.ByteString -> Val
solve bs = evalExpr $ evalParser expr bs

type Exception = B.ByteString
type Message = B.ByteString

data Expr = Throw Exception | TryCatch [Expr] Exception Message
data Val = Bottom | Catched Message | UnCatched Exception

evalParser :: Parser [Expr] -> State -> [Expr]
evalParser expr st = case runParser expr st of
                       Just (result,_) -> result
                       Nothing -> error "parse error"

evalExpr :: [Expr] -> Val
evalExpr (Throw excp : _) = UnCatched excp
evalExpr (TryCatch es excp0 msg : rest) =
  case evalExpr es of
    Bottom -> evalExpr rest
    Catched msg -> Catched msg
    UnCatched excp1
      | excp0 == excp1 -> Catched msg
      | otherwise -> UnCatched excp1
evalExpr [] = Bottom

expr :: Parser [Expr]
expr = many (trycatch <|> throw)

throw = do
  spaces
  string "throw"
  spaces
  char '('
  spaces
  excp <- letters
  spaces
  char ')'
  spaces
  return $ Throw excp

trycatch = do
  spaces
  string "try"
  spaces
  exprs <- expr
  spaces
  string "catch"
  spaces
  char '('
  spaces
  excp <- letters
  spaces
  char ','
  spaces
  msg <- between '\"' '\"'
  spaces
  char ')'
  spaces
  return $ TryCatch exprs excp msg

type State = B.ByteString
data Parser t = Parser {runParser :: State -> Maybe (t, State)}

instance Monad Parser where
  return t = Parser $ \st -> Just (t,st)
  m >>= f = Parser $ \st -> do
    (t,rest) <- runParser m st
    runParser (f t) rest

instance MonadPlus Parser where
  mzero = Parser $ const Nothing
  mplus p q = Parser $ \st ->
    runParser p st `mplus` runParser q st

instance Functor Parser where
  fmap f m = Parser $ \st ->
    fmap (\(t,rest) -> (f t,rest)) $ runParser m st

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

instance Alternative Parser where
  empty = mzero
  (<|>) = mplus

getState :: Parser State
getState = Parser $ \st -> Just (st,st)

putState :: State -> Parser ()
putState st = Parser $ const $ Just ((),st)

modifyState :: (State -> State) -> Parser ()
modifyState f = Parser $ \st -> Just ((),f st)

char :: Char -> Parser ()
char c = do
  bs <- getState
  guard (not (B.null bs) && B.index bs 0 == c)
  modifyState B.tail

string :: B.ByteString -> Parser ()
string bs = do
  cs <- getState
  guard $ bs `B.isPrefixOf` cs
  modifyState . B.drop $ B.length bs

spaces :: Parser ()
spaces = do
  bs <- getState
  putState $ B.dropWhile isSpace bs

letters :: Parser B.ByteString
letters = do
  (xs,ys) <- B.span isLetter <$> getState
  putState ys
  return xs

between :: Char -> Char -> Parser B.ByteString
between c d = do
  char c
  (xs,ys) <- B.break (d==) <$> getState
  putState ys
  char d
  return xs

eof :: Parser ()
eof = do
  spaces
  rest <- getState
  guard $ B.null rest

data Statement = Try | Throw String | Catch String String deriving Show

data Program = Trycatch String String Program | ThrowProg String | EmptyProg | SeqProg Program Program deriving Show

trim = reverse . dropWhile (==' ') . reverse . dropWhile (==' ')

unbrace l = case trim l of
  '(':l' -> case reverse l' of
    ')':l'' -> reverse l''

unquote l = case trim l of
  '"':l' -> case reverse l' of
    '"':l'' -> reverse l''

parse :: [String] -> [Statement]
parse s = s >>= \l -> case (dropWhile (==' ') l) of
  ('t':'r':'y':_) -> [Try]
  ('t':'h':'r':'o':'w':l) -> [Throw $ trim $ unbrace l]
  ('c':'a':'t':'c':'h':l) -> case span (/=',') $ unbrace l of
    (l, ',':r) -> [Catch (trim l) (unquote r)]
  [] -> []

go :: [Statement] -> Maybe (String, Int) -> String
go (Try : t) Nothing = go t Nothing
go (Catch ex msg : t) (Just (err, 0)) | err == ex = msg
  | otherwise = go t (Just (err, 0))
go (Catch _ _ : t) Nothing = go t Nothing
go (Catch _ _ : t) (Just (err, i)) = go t (Just (err, i-1))
go (Throw err : t) Nothing = go t (Just (err, 0))
go (Try : t) (Just (err, i)) = go t (Just (err, i+1))
go [] (Just (err, 0)) = "Unhandled Exception"

main = interact $ (`go` Nothing) . parse . tail . lines

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

data Result
  = Ex C.ByteString
  | Msg C.ByteString
  | Nil
  | End
  deriving (Eq, Show)

type Parser = State C.ByteString

next :: (Char -> Bool) -> Parser C.ByteString
next f = do
  modify $ C.dropWhile $ not . f
  (x, y) <- gets $ C.span f
  put y
  return x

parseMany :: Parser Result
parseMany = do
  first <- parse
  if first == End
    then return Nil
    else do
      rest <- parseMany
      return $ if first /= Nil then first else rest

parse :: Parser Result
parse = do
  modify $ C.dropWhile $ not . isLetter
  h <- gets C.head
  if h /= 't'
    then return End
    else do
      key <- next $ isLetter
      if key == C.pack "throw"
        then do
          ex <- next $ isLetter
          return $ Ex ex
        else do
          result <- parseMany
          _ <- next $ isLetter    -- "catch"
          ex <- next $ isLetter
          _ <- next $ (=='"')
          msg <- next $ (/='"')
          if result == Ex ex
            then return $ Msg msg
            else return result

main :: IO ()
main = do
  _ <- C.getLine
  s <- C.getContents
  let ans = case fst $ runState parseMany $ C.append s $ C.pack " return" of
              Ex _ -> "Unhandled Exception"
              Msg msg -> C.unpack msg
              _ -> "Error"
  putStrLn ans

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

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

get :: State s s
get = State $ \s -> (s, s)

put :: s -> State s ()
put s = State $ \_ -> ((), s)

modify :: (s -> s) -> State s ()
modify f = State $ \s -> ((), f s)

gets :: (s -> a) -> State s a
gets f = State $ \s -> (f s, s)

{-# LANGUAGE BangPatterns #-}

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

import Data.Char
import Data.List

newtype Parser a = Parser { runParser :: String -> (a,String) }

instance Functor Parser where
    fmap f (Parser a) = Parser (a >>> first f)

instance Monad Parser where
    Parser p >>= f =  Parser (\s ->
        let (a,s') = p s in runParser (f a) s')
    return a = Parser (\s -> (a,s))

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

data Op = Try | Throw String | Catch String String | Nop deriving(Show)

parseLine :: Parser Op
parseLine = do
    spaces
    tk <- token
    case tk of
        "try" -> return Try
        "throw" -> do
            s <- paren token
            return (Throw s)
        "catch" -> paren $ do
            ex <- token
            comma
            ms <- dquoted letters
            return $ Catch ex ms
        _ -> return Nop

peek :: Parser Char
peek = Parser $ \cs -> (if null cs then '\0' else head cs,cs)

consume :: Parser ()
consume = Parser $ \cs -> ((),if null cs then cs else tail cs)

spaces = do
    ch <- peek
    if ch == ' ' then consume >> spaces else return ()

token = do
    c <- peek
    if isAlphaNum c then do
        consume
        cs <- token
        return (c:cs)
    else spaces >> return ""

paren p = do
    consume
    spaces
    a <- p
    consume
    spaces
    return a

comma = consume >> spaces
dquoted p = do
    consume
    l <- p
    consume
    return l

letters = do
    c <- peek
    if c == '"' then return "" else do
        consume
        cs <- letters
        return (c:cs)

main = do
    n':ss <- lines <$> getContents
    let n = read n'
    let p = map (fst . runParser parseLine) (take n ss)
    let !ps = fst $ parsePrograms p
    let !res = execProgram ps
    case res of
        Message s -> putStrLn s
        Exception ex -> putStrLn "Unhandled Exception"

data Program = PTryCatch String String [Program]
             | PThrow String
             | PNop deriving(Show)

parsePrograms :: [Op] -> ([Program],[Op])
parsePrograms [] =  ([],[])
parsePrograms ops@(Catch _ _:_) = ([],ops)
parsePrograms ops = (p:ps,ops'')
    where
    (p,ops') = parseProgram ops
    (ps,ops'') = parsePrograms ops'

parseProgram :: [Op] -> (Program,[Op])
parseProgram (Throw ex:ops) = (PThrow ex,ops)
parseProgram (Nop:ops) = (PNop,ops)
parseProgram (Try:ops) = (PTryCatch ex ms ps,ops')
    where
    (ps,Catch ex ms:ops') = parsePrograms ops

data RVal = Unit | Exception String | Message String
    deriving(Show)

execProgram :: [Program] -> RVal
execProgram ps = go ps
    where
    go [] = Unit
    go (PNop:ps) = go ps
    go (PThrow ex:ps) = Exception ex
    go (PTryCatch ex ms p:ps) = case execProgram p of
        Exception ex' | ex == ex' -> Message ms
        Unit -> go ps
        v -> v

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

data Result
  = Ex C.ByteString
  | Msg C.ByteString
  | Nil
  | End
  deriving (Eq, Show)

type Parser = State C.ByteString

next :: (Char -> Bool) -> Parser C.ByteString
next f = do
  modify $ C.dropWhile $ not . f
  (x, y) <- gets $ C.span f
  put y
  return x

parseMany :: Parser Result
parseMany = do
  first <- parse
  if first == End
    then return Nil
    else do
      rest <- parseMany
      return $ if first /= Nil then first else rest

parse :: Parser Result
parse = do
  modify $ C.dropWhile $ not . isLetter
  h <- gets C.head
  if h /= 't'
    then return End
    else do
      key <- next $ isLetter
      if key == C.pack "throw"
        then do
          ex <- next $ isLetter
          return $ Ex ex
        else do
          result <- parseMany
          _ <- next $ isLetter    -- "catch"
          ex <- next $ isLetter
          _ <- next $ (=='"')
          msg <- next $ (/='"')
          if result == Ex ex
            then return $ Msg msg
            else return result

main :: IO ()
main = do
  _ <- C.getLine
  s <- C.getContents
  let ans = case fst $ runState parse $ C.append s $ C.pack " return" of
              Ex _ -> "Unhandled Exception"
              Msg msg -> C.unpack msg
              _ -> "Error"
  putStrLn ans

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

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

get :: State s s
get = State $ \s -> (s, s)

put :: s -> State s ()
put s = State $ \_ -> ((), s)

modify :: (s -> s) -> State s ()
modify f = State $ \s -> ((), f s)

gets :: (s -> a) -> State s a
gets f = State $ \s -> (f s, s)

data Statement = Try | Throw String | Catch String String deriving Show

data Program = Trycatch String String Program | ThrowProg String | EmptyProg | SeqProg Program Program deriving Show

trim = reverse . dropWhile (==' ') . reverse . dropWhile (==' ')

unbrace l = case trim l of
  '(':l' -> case reverse l' of
    ')':l'' -> reverse l''

unquote l = case trim l of
  '"':l' -> case reverse l' of
    '"':l'' -> reverse l''

parse :: [String] -> [Statement]
parse s = s >>= \l -> case (dropWhile (==' ') l) of
  ('t':'r':'y':_) -> [Try]
  ('t':'h':'r':'o':'w':l) -> [Throw $ trim $ unbrace l]
  ('c':'a':'t':'c':'h':l) -> case span (/=',') $ unbrace l of
    (l, ',':r) -> [Catch (trim l) (unquote r)]
  [] -> []

go :: [Statement] -> Maybe (String, Int) -> String
go (Try : t) Nothing = go t Nothing
go (Catch ex msg : t) (Just (err, 0)) | err == ex = msg
  | otherwise = go t (Just (err, 0))
go (Catch _ _ : t) Nothing = go t Nothing
go (Catch _ _ : t) (Just (err, i)) = go t (Just (err, i-1))
go (Throw err : t) Nothing = go t (Just (err, 0))
go (Try : t) (Just (err, i)) = go t (Just (err, i+1))
go [] (Just (err, 0)) = "Unhandled exception"

run :: [Statement] -> String
run (Throw ex : t) = go ex t where
  go ex (Catch ex' msg : _) | ex == ex' = msg
  go ex (_ : t) = go ex t
  go _ [] = "Unhandled exception"
run (_ : t) = run t

main = interact $ show . (`go` Nothing) . parse . tail . lines

data Statement = Try | Throw String | Catch String String deriving Show

data Program = Trycatch String String Program | ThrowProg String | EmptyProg | SeqProg Program Program deriving Show

trim = reverse . dropWhile (==' ') . reverse . dropWhile (==' ')

unbrace l = case trim l of
  '(':l' -> case reverse l' of
    ')':l'' -> reverse l''

unquote l = case trim l of
  '"':l' -> case reverse l' of
    '"':l'' -> reverse l''

parse :: [String] -> [Statement]
parse s = s >>= \l -> case (dropWhile (==' ') l) of
  ('t':'r':'y':_) -> [Try]
  ('t':'h':'r':'o':'w':l) -> [Throw $ trim $ unbrace l]
  ('c':'a':'t':'c':'h':l) -> case span (/=',') $ unbrace l of
    (l, ',':r) -> [Catch (trim l) (unquote r)]
  [] -> []

go :: [Statement] -> Maybe (String, Int) -> String
go (Try : t) Nothing = go t Nothing
go (Catch ex msg : t) (Just (err, 0)) | err == ex = msg
  | otherwise = go t (Just (err, 0))
go (Catch _ _ : t) Nothing = go t Nothing
go (Catch _ _ : t) (Just (err, i)) = go t (Just (err, i-1))
go (Throw err : t) Nothing = go t (Just (err, 0))
go (Try : t) (Just (err, i)) = go t (Just (err, i+1))
go [] (Just (err, 0)) = "Unhandled exception"

run :: [Statement] -> String
run (Throw ex : t) = go ex t where
  go ex (Catch ex' msg : _) | ex == ex' = msg
  go ex (_ : t) = go ex t
  go _ [] = "Unhandled exception"
run (_ : t) = run t

main = interact $ (`go` Nothing) . parse . tail . lines


import Control.Monad
import Data.Bool
import Data.List

main = getLine >>= flip replicateM_ test . read

test = do
    n <- read <$> getLine
    as <- map read . words <$> getLine
    putStrLn $ bool "NO" "YES" $ [0 .. n - 1] == sort ((`mod` n) <$> zipWith (+) [0 .. n - 1] as)

import qualified Data.List as L
import qualified Data.IntSet as IS
import Data.IntSet (IntSet)

pmod :: Integer -> Integer -> Integer
pmod n p
    | md < 0    = md + p
    | otherwise = md
    where
        md = n `mod` p

allUnique :: [Integer] -> Bool
--allUnique lst = length lst == length (map head $ L.group $ L.sort lst)
allUnique = go IS.empty . map fromIntegral
    where
        go set [] = True
        go set (i:is)
            | IS.member i set   = False
            | otherwise         = go (IS.insert i set) is

valid :: [Integer] -> Bool
valid as = allUnique $ map (`pmod` fromIntegral (length as)) $ zipWith (+) [0..] as

solve :: [Integer] -> String
solve as
    | valid as = "YES"
    | otherwise= "NO"

testCases :: Integer -> IO ()
testCases 0 = return ()
testCases t = do
    _ <- getLine
    as <- readNums
    putStrLn $ solve as
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- parseNums <$> getLine
    testCases t

parseNums :: (Read a) => String -> [a]
parseNums = map read . words

readNums :: (Read a) => IO [a]
readNums = parseNums <$> getLine

import Control.Monad
import qualified Data.Set as S

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

routine :: IO ()
routine = do
    n <- readLn
    as <- (map read.words) <$> getLine
    putStrLn $ if solve n as
      then "No"
      else "Yes"

solve :: Int -> [Int] -> Bool
solve n as = hasDupesWith S.empty xs
  where
    xs = map (`mod` n) $ zipWith (-) as [0,(-1)..]

hasDupesWith :: S.Set Int ->  [Int] -> Bool
hasDupesWith _ [] = False
hasDupesWith seen (x:xs) = x `S.member` seen || hasDupesWith (S.insert x seen) xs

import qualified Data.List as L

pmod :: Integer -> Integer -> Integer
pmod n p
    | n < 0     = (n `mod` p) + p
    | otherwise = n `mod` p

allUnique :: [Integer] -> Bool
allUnique lst = length lst == length (map head $ L.group $ L.sort lst)

valid :: [Integer] -> Bool
valid as = allUnique $ map (`pmod` fromIntegral (length as)) $ zipWith (+) [0..] as

solve :: [Integer] -> String
solve as
    | valid as = "YES"
    | otherwise= "NO"

testCases :: Integer -> IO ()
testCases 0 = return ()
testCases t = do
    _ <- getLine
    as <- readNums
    putStrLn $ solve as
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- parseNums <$> getLine
    testCases t

parseNums :: (Read a) => String -> [a]
parseNums = map read . words

readNums :: (Read a) => IO [a]
readNums = parseNums <$> getLine

import qualified Data.List as L

pmod :: Int -> Int -> Int
pmod n p
    | n < 0     = (n `mod` p) + p
    | otherwise = n `mod` p

allUnique :: [Int] -> Bool
allUnique lst = length lst == length (map head $ L.group $ L.sort lst)

valid :: [Int] -> Bool
valid as = allUnique $ map (`pmod` length as) $ zipWith (+) [0..] as

solve :: [Int] -> String
solve as
    | valid as = "YES"
    | otherwise= "NO"

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    _ <- getLine
    as <- readNums
    putStrLn $ solve as
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- parseNums <$> getLine
    testCases t

parseNums :: (Read a) => String -> [a]
parseNums = map read . words

readNums :: (Read a) => IO [a]
readNums = parseNums <$> getLine


import Array
import Maybe
import Prelude hiding (print)

parse :: String -> (Int, Int)
parse line  =  case words line of
    [s1, s2]  ->  (read s1, read s2)

solve :: Int -> [(Int, Int)] -> Maybe (Int, Int)
solve n xs  =  listToMaybe $ filter ((/= 1) . snd) $ assocs array
  where
    array :: Array Int Int
    array  =  accumArray (+) 0 (1, n) $ concatMap (\(a,b) -> [(i,1) | i <- [a..b]]) xs

print :: Maybe (Int, Int) -> IO ()
print Nothing  =  putStrLn "OK"
print (Just (a, b))  =  putStrLn $ show a ++ " " ++ show b

main :: IO ()
main  =  do
    (n, m)  <-  fmap parse getLine
    xs  <-  fmap (map parse . lines) getContents
    print $ solve n xs

import Control.Monad
import Data.Array
import Data.List

getA = fmap (map read . words) getLine

main = do
	[n, m] <- getA
	a <- replicateM m getA
	putStrLn $ toS $ find ((/=1) . snd) $ assocs $ accumArray (+) 0 (1, n) $ concat $ map (\[i, j] -> zip [i .. j] $ repeat 1) a where
		toS Nothing = "OK"
		toS (Just (i, j)) = show i ++ " " ++ show j

main = interact solve
solve input = output where
  [n,m]:s = map (map (read::String->Int)) $ map words $ lines input
  output = ans s
  ans ([x,y]:xs) = if x==1 then ans0 y xs else "1 0"
  ans0 x [] = if x==n then "OK" else f (x+1) 0
  ans0 x ([y,z]:xs)
    | x + 1== y = ans0 z xs
    | x + 1 < y = f (x+1) 0
    | y < z     = f x 2
    | otherwise = f x (ans1 y xs)
  ans1 _ [] = 2
  ans1 x ([y,z]:xs) = if x<y then 2 else ans1 x xs + 1
  f x y = unwords $ map show [x,y]

main = do interact (show . gao . map (map read . words) . tail . lines)
gao (p:q) = minimum [p # i + p # j + i # j | i <- q, j <- q, i /= j] / 2
(#) a = sqrt . sum . zipWith (\i j -> (i - j) ^ 2) a


{-# LANGUAGE BangPatterns , BlockArguments ,FlexibleContexts ,FlexibleInstances ,OverloadedStrings ,TypeApplications ,MultiParamTypeClasses ,TupleSections #-}
import Control.Monad (replicateM,forM_,when,(<=<))

main :: IO ()
main = do
  n <- readLn @Int
  query <- replicateM n $ do
    b <- readLn @Int
    a <- map (read @Int) . words <$> getLine
    return (b,a)
  solve n query
solve :: Int -> [(Int,[Int])] -> IO ()
solve n query = do
  forM_ query \(n,x) -> do
    let oddIndex = map snd$filter(\(index,val)->odd index) $zip[1..]x
        evenIndex = map snd$filter(\(index,val)->even index) $zip[1..]x
    let ho = head oddIndex
        he = head evenIndex
    putStrLn$
      if(even ho && even he)then do
        if(all even oddIndex && all even evenIndex)then "YES"else "NO"
      else if(even ho && odd he) then do
        if(all even oddIndex && all odd evenIndex)then "YES"else "NO"
      else if(odd ho && even he) then do
        if(all odd oddIndex && all even evenIndex)then "YES"else "NO"
      else if(odd ho && odd he) then do
        if(all odd oddIndex && all odd evenIndex)then "YES"else "NO"
      else "NO"

import Data.List

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

readInt :: IO Int
readInt = parseInt <$> getLine

readIntArr :: IO [Int]
readIntArr = do
  arr <- words <$> getLine
  pure $ map parseInt arr

check :: Int -> Int
check x = if x `mod` 2 == 0
  then 1
  else -1

calc :: [Int] -> (Int, Int) -> Bool -> String
calc [] _ _ = "YES"
calc (x: xs) (c1, c2) p = if p
  then if (abs c1) > (abs $ c1 + check x)
    then "NO"
    else calc xs (c1 + check x, c2) False
  else if (abs c2) > (abs $ c2 + check x)
    then "NO"
    else calc xs (c1, c2 + check x) True

solve :: IO ()
solve = do
  n <- readInt
  arr <- readIntArr
  putStrLn $ calc arr (0, 0) True

for :: Int -> IO () -> IO ()
for 0 _ = pure ()
for i f = do
  f
  for (i - 1) f

main :: IO ()
main = do
  n <- readInt
  for n solve


import Data.List
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
eleven = intercalate "O" $ map (flip replicate 'o' . pred) fibs
main = interact $ flip take eleven . read

main = putStr . flip (foldr (\i g fs@(f:_) -> if i == f then 'O':g (dropWhile (== i) fs) else 'o':g fs) (const [])) fibs . enumFromTo 1 . read =<< getLine
fibs = 1:1:zipWith (+) fibs (tail fibs)

main = getLine >>= putStrLn . solve . read

solve n = foldr (\x acc -> (genName 'o' x):acc) [] [1 .. n]

genName 'o' num
    | elem num fib = 'O'
    | otherwise = 'o'

fib = f [2,1] 2
    where f (a:b:x) num
              | num < 15 = f ((a+b):a:b:x) (num+1)
              | otherwise = a:b:x

import Data.List

g::Bool->Char
g True='O'
g False='o'

f :: Int->Int->[Int]
f a b
   |a>1000=[]
   |otherwise=a:(f b (a+b))

h::Int->Int->[Int]->[Bool]
h p n xs
  |p>n=[]
  |otherwise=(elem p xs):h (p+1) n xs

main=do
     e1<-getLine
     let n=read e1::Int
         xs=f 1 1
     putStrLn $ map g $ h 1 n xs

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

fibs = 1:1: (zipWith (+) fibs (tail fibs))

process x n = map (\z-> if elem z x then 'O' else 'o') [1..n]

main = do
		n<- read <$> getLine:: IO Int
		let x = takeWhile (<=n) fibs
		putStrLn $ process x n

process :: Int -> [Char]
process n = take n $ f 1 1 0
    where
        f a b i
            | i == 0 = 'O':f b (a+b) (a-1)
            | otherwise = 'o':f a b (i-1)

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    putStrLn $ process n


{-# 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.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.STRef
import Data.IORef
import Data.Function
import System.IO
import System.Exit
import qualified System.Random as SR

main :: IO ()
main = do
  n <- readInt <$> getLine
  (rest,maxval) <- binMax (n-2) (10^9) 60
  rands <- SR.randomRs (1,n) <$> SR.newStdGen
  let noDupRands =
        take rest $ map fst
        $ filter (uncurry IS.notMember)
        $ scanl (\(prev,set0) now -> (now, IS.insert prev set0))
            (-1,IS.singleton (-1))
        $ rands
      is | n < shiftL rest 1 = [1..rest `min` n]
         | otherwise         = noDupRands
  as <- fmap sort $ forM is $ \i -> do
    putStrLn $ '?':' ': show i
    hFlush stdout
    ai <- readInt <$> getLine
    if ai < 0 then exitFailure else return ai
  let diffs = zipWith (-) (tail as) as
      d = foldl1' gcd diffs
  putStrLn $ ('!':) $ (' ':) $ shows (maxval - (n-1)*d) $ ' ' : show d

binMax :: Int -> Int -> Int -> IO (Int,Int)
binMax !lt !ge !rest
  | ge - lt <= 1 = return (rest,ge)
  | otherwise    = do
      let mid = lt + shiftR (ge - lt) 1
      putStrLn $ '>':' ': show mid
      hFlush stdout
      i <- readInt <$> getLine
      case i of
        1 -> binMax mid ge (rest-1)
        0 -> binMax lt mid (rest-1)
        _ -> exitFailure

rInt :: StateT BSL.ByteString Maybe Int
rInt = StateT $ BSL.readInt . BSL.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

#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

{-# 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.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.STRef
import Data.IORef
import Data.Function
import System.IO
import System.Exit
import qualified System.Random as SR

main :: IO ()
main = do
  n <- readInt <$> getLine
  (rest,maxval) <- binMax (n-2) (10^9) 60
  rands <- SR.randomRs (1,n) <$> SR.newStdGen
  let noDupRands =
        take rest $ map fst
        $ filter (uncurry IS.notMember)
        $ scanl (\(prev,set0) now -> (now, IS.insert prev set0))
            (-1,IS.singleton (-1))
        $ rands
      is | n < shiftL rest 1 = [1..rest `min` n]
         | otherwise         = noDupRands
  as <- fmap (sort . (maxval:)) $ forM is $ \i -> do
    putStrLn $ '?':' ': show i
    hFlush stdout
    ai <- readInt <$> getLine
    if ai < 0 then exitFailure else return ai
  let diffs = zipWith (-) (tail as) as
      d = foldl1' gcd diffs
  putStrLn $ ('!':) $ (' ':) $ shows (maxval - (n-1)*d) $ ' ' : show d

binMax :: Int -> Int -> Int -> IO (Int,Int)
binMax !lt !ge !rest
  | ge - lt <= 1 = return (rest,ge)
  | otherwise    = do
      let mid = lt + shiftR (ge - lt + 1) 1
      putStrLn $ '>':' ': show mid
      hFlush stdout
      i <- readInt <$> getLine
      case i of
        1 -> binMax mid ge (rest-1)
        0 -> binMax lt mid (rest-1)
        _ -> exitFailure

rInt :: StateT BSL.ByteString Maybe Int
rInt = StateT $ BSL.readInt . BSL.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

#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

{-# 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.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.STRef
import Data.IORef
import Data.Function
import System.IO
import System.Exit
import qualified System.Random as SR

ulimit = 10^9 :: Int
over = ulimit + 10

main :: IO ()
main = do
  n <- readInt <$> getLine
  (!rest,!amax) <- binMax (n-2) ulimit 60
  rands <- SR.randomRs (1,n) <$> SR.newStdGen
  let noDupRands
        = take rest $ map fst $ filter (uncurry IS.notMember)
          $ scanl (flip (,) . uncurry IS.insert) (over,IS.singleton over) rands
      is | n < shiftL rest 1 = [1..rest `min` n]
         | otherwise         = noDupRands
  as <- fmap (sort . (amax:)) $ forM is $ \i -> do
    putStrLn $ '?':' ': show i
    hFlush stdout
    ai <- readInt <$> getLine
    if ai < 0 then exitFailure else return ai
  let diffs = zipWith (-) (tail as) as
      d = foldl1' gcd diffs
  putStrLn $ ('!':) $ (' ':) $ shows (amax - (n-1)*d) $ ' ' : show d

binMax :: Int -> Int -> Int -> IO (Int,Int)
binMax !lt !ge !rest
  | ge - lt <= 1 = return (rest,ge)
  | otherwise    = do
      let mid = lt + shiftR (ge - lt + 1) 1
      putStrLn $ '>':' ': show mid
      hFlush stdout
      i <- readInt <$> getLine
      case i of
        1 -> binMax mid ge (rest-1)
        0 -> binMax lt mid (rest-1)
        _ -> exitFailure

rInt :: StateT BSL.ByteString Maybe Int
rInt = StateT $ BSL.readInt . BSL.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

#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


import Data.List
import Data.Maybe
import Control.Monad
{-solve :: [String] -> ([String],Int)
solve l = (result,howoften)
	where
		zipped=zip l [0..]
		firstelem = map (\(x,y)-> (fromJust $ elemIndex x l)==y) zipped
		--newpins=filter (\x -> not (x `elem` l)) (map show [1000..])
		--result=zipWith (\x (y,z) -> if x then y else newpins!!z) firstelem zipped
		--howoften= foldr (\x c-> if x then c else c+1) 0 firstelem
-}
{-
routine :: IO ()
routine = do
	n <- readLn
	l <- replicateM n getLine
	let (list,c)=solve l
	print c

-}
helper :: [String] -> [String] -> String -> ([String],Int)
helper total li str = if str `elem` li then (newStr:li,1) else (str:li,0)
	where
		unused = head $ filter (\x -> not (x `elem` (map head li))) $ filter (\x -> not (x `elem` (map head total))) (map (head.show) [0..9])
		newStr = (unused):(tail str)

solve :: [String] -> ([String],Int)
solve li = foldr (\str (list,count) -> let (x,y)=helper li list str in (x,y+count)) ([],0) li

routine :: IO ()
routine = do
	n <- readLn
	l <- replicateM n getLine
	let (list,c)=solve l
	print c
	forM_ list putStrLn

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

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

main = getLine >>= test.read
test 0 = return ()
test i = do
  n <- read <$> getLine
  ps <- getPins n
  print $ sum $ subtract 1.length <$> group (sort ps)
  putStr $ unlines $ change ps
  test (i - 1)

change ps = snd <$> sortOn fst changed where
  sorted = sortOn snd $ zip [1..] ps
  grouped = groupBy (\(_, a) (_, b) -> a == b) sorted
  changed = grouped >>= (\(a:as) -> a : alter '0' as)
  alter _ [] = []
  alter c ((i, [p, q, r, s]):as) = let c' = if c == '9' then '0' else succ c in
    if elem [c, q, r, s] ps
      then if elem [p, c, r, s] ps
        then if elem [p, q, c, s] ps
          then if elem [p, q, r, c] ps
            then alter c' ((i, [p, q, r, s]):as)
            else (i, [p, q, r, c]) : alter c' as
          else (i, [p, q, c, s]) : alter c' as
        else (i, [p, c, r, s]) : alter c' as
      else (i, [c, q, r, s]) : alter c' as

getPins 0 = return []
getPins i = do
  p <- getLine
  (p:) <$> getPins (i - 1)

import Data.List
import Data.Maybe
import Control.Monad
{-solve :: [String] -> ([String],Int)
solve l = (result,howoften)
	where
		zipped=zip l [0..]
		firstelem = map (\(x,y)-> (fromJust $ elemIndex x l)==y) zipped
		--newpins=filter (\x -> not (x `elem` l)) (map show [1000..])
		--result=zipWith (\x (y,z) -> if x then y else newpins!!z) firstelem zipped
		--howoften= foldr (\x c-> if x then c else c+1) 0 firstelem
-}
{-
routine :: IO ()
routine = do
	n <- readLn
	l <- replicateM n getLine
	let (list,c)=solve l
	print c

-}
helper :: [String] -> String -> ([String],Int)
helper li str = if str `elem` li then (newStr:li,1) else (str:li,0)
	where
		unused = head $ filter (\x -> not (x `elem` (map head li))) (map (head.show) [0..9])
		newStr = (unused):(tail str)

solve :: [String] -> ([String],Int)
solve li = foldr (\str (list,count) -> let (x,y)=helper list str in (x,y+count)) ([],0) li

routine :: IO ()
routine = do
	n <- readLn
	l <- replicateM n getLine
	let (list,c)=solve l
	print c
	forM_ list putStrLn

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

import Data.List
import Data.Maybe
import Control.Monad
{-solve :: [String] -> ([String],Int)
solve l = (result,howoften)
	where
		zipped=zip l [0..]
		firstelem = map (\(x,y)-> (fromJust $ elemIndex x l)==y) zipped
		--newpins=filter (\x -> not (x `elem` l)) (map show [1000..])
		--result=zipWith (\x (y,z) -> if x then y else newpins!!z) firstelem zipped
		--howoften= foldr (\x c-> if x then c else c+1) 0 firstelem
-}
{-
routine :: IO ()
routine = do
	n <- readLn
	l <- replicateM n getLine
	let (list,c)=solve l
	print c

-}
helper :: [String] -> [String] -> String -> ([String],Int)
helper total li str = if str `elem` li then (newStr:li,1) else (str:li,0)
	where
		unused = head $ filter (\x -> not (x `elem` (map head total))) (map (head.show) [0..9])
		newStr = (unused):(tail str)

solve :: [String] -> ([String],Int)
solve li = foldr (\str (list,count) -> let (x,y)=helper li list str in (x,y+count)) ([],0) li

routine :: IO ()
routine = do
	n <- readLn
	l <- replicateM n getLine
	let (list,c)=solve l
	print c
	forM_ list putStrLn

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


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

process n [] = []
process n (a:b) | a>=0 = (n+a): (process (n+a) b)
                | otherwise = (n+a) : (process n b)

main::IO ()
main=do
  getLine
  a<-  map read <$> words <$> getLine::IO [Integer]
  putStrLn $ intercalate " " $ map show $process  0 a

import Data.List (mapAccumL)

process :: [Int] -> [Int]
process = snd . mapAccumL (\x b -> let b' = b+x in (max x b', b')) 0

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    bs <- fmap (map readInt.words) getLine
    putStrLn.unwords.map show $ process bs

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

main = do
  getLine
  bs <- map read.words <$> getLine
  let vs = solve 0 bs
  let m = minimum vs
  putStrLn $ unwords.map show $ (+ (head bs - head vs)) <$> vs

solve _ [] = []
solve a (b:bs)
  | b > 0 = (a + b) : solve (a + b) bs
  | otherwise = (a + b) : solve a bs

module Main where
import Data.List

getA :: [Int] -> [Int]
getA b = f b 0
  where f (bi:br) m = bi+m : f br (max m (bi+m))

solve :: String -> String
solve s = let ((n:_):b:_) = map (map read . words) $ lines s
              in (unwords $ map show $ take n $ getA (b ++ repeat 0)) ++ "\n"

main = interact solve

import Control.Monad
import Data.List
import Data.Ord

main = do
    getLine
    inp <- getLine
    let nums = map read $ words inp
    putStrLn $ intercalate " " $ map show $ ans 0 nums

ans :: Int -> [Int] -> [Int]
ans m [] = []
ans m (b:bs) =
  let a = b + m in
  a : ans (if b > 0 then a else m) bs


import Control.Monad

import Data.Char
import Data.List

solve :: (Integer, Integer) -> Integer
solve (n, k) = k * (n `div` k) + min (k `div` 2) (n `rem` k)

main :: IO ()
main = do
    input <- getContents
    putStrLn $ unlines . map (show . solve) $ zip (a input) (b input)
    where a            = map snd . filter (odd . fst) . zip [1..] . map (read :: String -> Integer) . tail . words
          b            = map snd . filter (even . fst) . zip [1..] . map (read :: String -> Integer) . tail . words

import Control.Monad

solve :: [Int] -> Int
solve (n:k:_) = n - (max 0 $ (n `mod` k) - (k `div` 2))

main :: IO ()
main = ids >>= mapM_ (fn >=> print)
  where ids   = enumFromTo 1 . read <$> getLine
        fn tc = solve . map read . words <$> getLine

import Control.Monad

solve :: Int -> Int -> Int
solve n k = a + (min b (k `div` 2))
    where
        a = (n `div` k) * k
        b = n `mod` k

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

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

import Control.Monad

solve :: Int -> Int -> Int
solve n k = (q * k) + min rem (k `quot` 2)
  where
    (q, rem) = n `quotRem` k

main = do
  numCases <- read <$> getLine

  replicateM_ numCases $ do
    [n, k] <- fmap read <$> words <$> getLine
    print $ solve n k

sol :: [Int] -> Int
sol [n, k] = min n $ k * a + k `div` 2
  where a = n `div` k

main = interact (unlines . map show . map (sol . map read) . map words .  tail . lines)

import Control.Applicative
import Control.Monad

solve n k = (d * k) + (min (k `div` 2) r)
    where
        d = n `div` k
        r = n `rem` k

readInt :: String -> Integer
readInt = read

main = do
    n <- read <$> getLine
    replicateM_ n $ do
        [h, m] <- map readInt . words <$> getLine
        print $ solve h m

main :: IO ()

main = interact solve

solve :: String -> String
solve = buildup . map solver . breakdown
solver :: (Int, Int) -> Int
solver (x,y) = min (x `div` y * y + (y `div` 2)) x

breakdown :: String -> [(Int, Int)]
breakdown = map (f . words) . tail . lines
    where   f :: [String] -> (Int,Int)
            f (x:y:[]) = (read x, read y)

buildup :: [Int] -> String
buildup = unlines . map show

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

main :: IO ()

main = interact solve

solve :: String -> String
solve = buildup . map solver . breakdown
solver :: (Int, Int) -> Int
solver (x,y) = max (x `div` y * y + (y `div` 2)) x

breakdown :: String -> [(Int, Int)]
breakdown = map (f . words) . tail . lines
    where   f :: [String] -> (Int,Int)
            f (x:y:[]) = (read x, read y)

buildup :: [Int] -> String
buildup = unlines . map show

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

main :: IO ()

main = interact solve

solve :: String -> String
solve = buildup . map solver . breakdown
solver :: (Int, Int) -> Int
solver (x,y) = x `div` y * y + (y `div` 2)

breakdown :: String -> [(Int, Int)]
breakdown = map (f . words) . tail . lines
    where   f :: [String] -> (Int,Int)
            f (x:y:[]) = (read x, read y)

buildup :: [Int] -> String
buildup = unlines . map show

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

main :: IO ()

main = interact solve

solve :: String -> String
solve = buildup . map solver . breakdown
solver :: (Int, Int) -> Int
solver (x,y) = x - (( x `mod` y) `div` 2)

breakdown :: String -> [(Int, Int)]
breakdown = map (f . words) . tail . lines
    where   f :: [String] -> (Int,Int)
            f (x:y:[]) = (read x, read y)

buildup :: [Int] -> String
buildup = unlines . map show

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


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

main = interact solve

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

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

import Control.Monad

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

module Main (main)
    where

import Control.Monad (replicateM)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import Control.Monad

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import Control.Applicative

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

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

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

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

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

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

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

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

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

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

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

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

--ghc 7.10

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

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

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

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

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

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

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

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

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


import Data.Int (Int64)

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

readInt :: String -> Int64
readInt = read

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

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

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

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

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

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

  let
    h = head xs
    l = last xs

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

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

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

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

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

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

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

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

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

import System.IO

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

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

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

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

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

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

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

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

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

module Main where

import Control.Applicative

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

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

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

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

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

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

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

import Data.List
import Data.Int

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

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

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

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

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

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

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

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

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

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

import Data.Int (Int64)

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

readInt :: String -> Int64
readInt = read

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

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

readInt :: String -> Int
readInt = read

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

import Data.List

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

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

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

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

import Data.List
import Data.Int

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

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

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

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


{-# LANGUAGE BangPatterns #-}

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

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

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

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

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

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

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

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

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

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

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

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

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


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

main = getLine >>= flip replicateM_ test . read

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

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

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

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

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

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

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

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

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

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

import Data.List

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

split = _split [] ""

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

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

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

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

type Point = (Integer, Integer)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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