import Data.Map (Map, singleton, findWithDefault, insert)
import Data.Int (Int64)

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

parseInt64 :: String -> Int64
parseInt64 x = read x

split      :: Eq a => a -> [a] -> [[a]]
split d [] =  []
split d s  =  x : split d (drop 1 y) where (x,y) = span (/= d) s

addMod :: Int -> Int -> Int
addMod a b = mod (a + b) 1000000007

solve :: [Int64] -> Int
solve xs = go xs (singleton 0 1) 0 1 where
    go :: [Int64] -> Map Int64 Int -> Int64 -> Int -> Int
    go []     s d r = r
    go (x:xs) s d r = go xs s' d' r' where
        k  = addMod r (1000000007 - findWithDefault 0 (-d) s)
        r' = addMod r k
        d' = d + x
        s' = insert (-d) r s

run :: IO ()
run = do
    n <- getLine
    b <- getLine
    print $ solve $ map parseInt64 $ split ' ' b

runK :: Int -> IO ()
runK 1 = run
runK k = run >>= (\x -> runK (k-1))

main = do
    t <- getLine
    runK $ parseInt t

import Control.Monad
import Data.Maybe
import Data.List
import Data.Int
import qualified Data.ByteString.Char8 as C
import qualified Data.Map.Strict as M

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

kMod :: Int64
kMod = 1000000007

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    [n] <- getInts
    bs <- map fromIntegral <$> getInts :: IO [Int64]
    let
      acc (total, totalSuf, sufs, offset) b = (total', totalSuf', sufs', offset')
        where
        totalSuf' = case M.lookup (-offset) sufs of
          Nothing -> (totalSuf * 2) `mod` kMod
          Just c -> (totalSuf * 2 + kMod - c) `mod` kMod
        sufs' = M.insert (-offset) totalSuf sufs
        offset' = offset + b
        total' = (total + totalSuf + kMod - M.findWithDefault 0 (-offset) sufs) `mod` kMod
      (result, _, _, _) = foldl' acc (1, 1, M.singleton 0 1, 0) bs
    C.putStrLn $ C.pack $ show result

{-# LANGUAGE BangPatterns #-}
import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder as B
import System.IO

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.List
import Data.Semigroup

import Data.Int
import qualified Data.Map.Strict as M

type SIO = StateT P.ByteString IO

type Map = M.Map Int64 Int

p :: Int
p = 10 ^ (9 :: Int) + 7

-- Partitions into (nonempty) intervals, of which only the last may have sum 0
solve :: Map -> Int64 -> Int -> [Int] -> Int
solve _ _ prevOptsTot [_] = prevOptsTot -- extend each prevOpt to end
solve !excls !prevSum !prevOptsTot (b : bs) = let
  currExcl = M.findWithDefault 0 currSum excls
  currOpts = prevOptsTot - currExcl
  -- prevOptsTot = currOpts + currExcl
  nextExcls = M.insert currSum prevOptsTot excls
  currSum = prevSum + fromIntegral b
  currOptsTot = mod (prevOptsTot + currOpts) p
  in  solve nextExcls currSum currOptsTot bs
solve _ _ _ [] = 1

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  let  initMap = M.fromAscList [(0, 1)]
  replicateM_ t $ do
    [_n] <- readInts
    b <- readInts
    putInts [solve initMap 0 1 b]

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

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

putInts :: [Int] -> SIO ()
putInts li = let
  outBuilder = foldr (<>) (B.char7 '\n')
    $ intersperse (B.char7 ' ') (map B.intDec li)
  in  lift $ B.hPutBuilder stdout outBuilder

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder as B
import System.IO

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.List
import Data.Semigroup

import Data.Int
import qualified Data.Map.Strict as M

type SIO = StateT P.ByteString IO

type Map = M.Map Int64 Int

p :: Int
p = 10 ^ (9 :: Int) + 7

-- Partitions into (nonempty) intervals, of which only the last may have sum 0
solve :: Map -> Int64 -> Int -> [Int] -> Int
solve _ _ prevOptsTot [_] = prevOptsTot -- extend each prevOpt to end
solve excls prevSum prevOptsTot (b : bs) = let
  currExcl = M.findWithDefault 0 currSum excls
  currOpts = prevOptsTot - currExcl
  -- prevOptsTot = currOpts + currExcl
  nextExcls = M.insert currSum prevOptsTot excls
  currSum = prevSum + fromIntegral b
  currOptsTot = mod (prevOptsTot + currOpts) p
  in  solve nextExcls currSum currOptsTot bs
solve _ _ _ [] = 1

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  let  initMap = M.fromAscList [(0, 1)]
  replicateM_ t $ do
    [_n] <- readInts
    b <- readInts
    putInts [solve initMap 0 1 b]

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

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

putInts :: [Int] -> SIO ()
putInts li = let
  outBuilder = foldr (<>) (B.char7 '\n')
    $ intersperse (B.char7 ' ') (map B.intDec li)
  in  lift $ B.hPutBuilder stdout outBuilder

import Data.Map (Map, singleton, findWithDefault, insert)

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

split      :: Eq a => a -> [a] -> [[a]]
split d [] =  []
split d s  =  x : split d (drop 1 y) where (x,y) = span (/= d) s

addMod :: Int -> Int -> Int
addMod a b = mod (a + b) 1000000007

solve :: [Int] -> Int
solve xs = go xs (singleton 0 1) 0 1 where
    go :: [Int] -> Map Int Int -> Int -> Int -> Int
    go []     s d r = r
    go (x:xs) s d r = go xs s' d' r' where
        k  = addMod r (1000000007 - findWithDefault 0 (-d) s)
        r' = addMod r k
        d' = d + x
        s' = insert (-d) r s

run :: IO ()
run = do
    n <- getLine
    b <- getLine
    print $ solve $ map parseInt $ split ' ' b

runK :: Int -> IO ()
runK 1 = run
runK k = run >>= (\x -> runK (k-1))

main = do
    t <- getLine
    runK $ parseInt t

import Data.Map (Map, singleton, findWithDefault, insertWith)

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

split      :: Eq a => a -> [a] -> [[a]]
split d [] =  []
split d s  =  x : split d (drop 1 y) where (x,y) = span (/= d) s

addMod :: Int -> Int -> Int
addMod a b = mod (a + b) 1000000007

solve :: [Int] -> Int
solve xs = go xs (singleton 0 1) 0 1 where
    go :: [Int] -> Map Int Int -> Int -> Int -> Int
    go []     s d r = r
    go (x:xs) s d r = go xs s' d' r' where
        k  = addMod r (1000000007 - findWithDefault 0 (-d) s)
        r' = addMod r k
        d' = d + x
        s' = insertWith addMod (-d) k s

run :: IO ()
run = do
    n <- getLine
    b <- getLine
    print $ solve $ map parseInt $ split ' ' b

runK :: Int -> IO ()
runK 1 = run
runK k = run >>= (\x -> runK (k-1))

main = do
    t <- getLine
    runK $ parseInt t

import Data.Map (Map, singleton, findWithDefault, insertWith)

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

split      :: Eq a => a -> [a] -> [[a]]
split d [] =  []
split d s  =  x : split d (drop 1 y) where (x,y) = span (/= d) s

addMod :: Int -> Int -> Int
addMod a b = mod (a + b) 1000000007

solve :: [Int] -> Int
solve xs = go xs (singleton 0 1) 0 1 where
    go :: [Int] -> Map Int Int -> Int -> Int -> Int
    go []     s d r = r
    go (x:xs) s d r = go xs s' d' r' where
        k  = r - findWithDefault 0 (-d) s
        r' = addMod r k
        d' = d + x
        s' = insertWith addMod (-d) k s

run :: IO ()
run = do
    n <- getLine
    b <- getLine
    print $ solve $ map parseInt $ split ' ' b

runK :: Int -> IO ()
runK 1 = run
runK k = run >>= (\x -> runK (k-1))

main = do
    t <- getLine
    runK $ parseInt t

import Data.Map (Map, singleton, findWithDefault, insertWith)

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

split      :: Eq a => a -> [a] -> [[a]]
split d [] =  []
split d s  =  x : split d (drop 1 y) where (x,y) = span (/= d) s

addMod :: Int -> Int -> Int
addMod a b = mod (a + b) 1000000007

solve :: [Int] -> Int
solve xs = go xs (singleton 0 1) 0 1 where
    go :: [Int] -> Map Int Int -> Int -> Int -> Int
    go []     s d r = r
    go (x:xs) s d r = go xs s' d' r' where
        k  = r + 1000000007 - findWithDefault 0 (-d) s
        r' = addMod r k
        d' = d + x
        s' = insertWith addMod (-d) k s

run :: IO ()
run = do
    n <- getLine
    b <- getLine
    print $ solve $ map parseInt $ split ' ' b

runK :: Int -> IO ()
runK 1 = run
runK k = run >>= (\x -> runK (k-1))

main = do
    t <- getLine
    runK $ parseInt t

import Data.List

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

split :: Eq a => a -> [a] -> [[a]]
split chr = unfoldr sep where
    sep [] = Nothing
    sep l  = Just . fmap (drop 1) . break (== chr) $ l

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

run :: IO ()
run = do
    n <- getLine
    b <- getLine
    print $ solve $ map parseInt $ split ' ' b

main = do
    t <- getLine
    run
    run
    run
    run

import Control.Monad
import Data.Maybe
import Data.List
import Data.Int
import qualified Data.ByteString.Char8 as C
import qualified Data.IntMap.Strict as IM

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

kMod :: Int64
kMod = 1000000007

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    [n] <- getInts
    bs <- getInts
    let
      acc (total, totalSuf, sufs, offset) b = (total', totalSuf', sufs', offset')
        where
        totalSuf' = case IM.lookup (-offset) sufs of
          Nothing -> (totalSuf * 2) `mod` kMod
          Just c -> (totalSuf * 2 + kMod - c) `mod` kMod
        sufs' = IM.insert (-offset) totalSuf sufs
        offset' = offset + b
        total' = (total + totalSuf + kMod - IM.findWithDefault 0 (-offset) sufs) `mod` kMod
      (result, _, _, _) = foldl' acc (1, 1, IM.singleton 0 1, 0) bs
    C.putStrLn $ C.pack $ show result

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

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

kMod :: Int
kMod = 1000000007

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    [n] <- getInts
    bs <- getInts
    let
      acc (total, totalSuf, sufs, offset) b = (total', totalSuf', sufs', offset')
        where
        totalSuf' = case IM.lookup (-offset) sufs of
          Nothing -> (totalSuf * 2) `mod` kMod
          Just c -> (totalSuf * 2 + kMod - c) `mod` kMod
        sufs' = IM.insert (-offset) totalSuf sufs
        offset' = offset + b
        total' = (total + totalSuf + kMod - IM.findWithDefault 0 (-offset) sufs) `mod` kMod
      (result, _, _, _) = foldl' acc (1, 1, IM.singleton 0 1, 0) bs
    C.putStrLn $ C.pack $ show result


import Data.List (partition)

process :: [Int] -> Int
process xs
    | length es == 1 = snd.head $ es
    | otherwise = snd.head $ os
    where
        (es,os) = partition (even.fst) $ zip xs [1..]

readInt :: String -> Int
readInt = read

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

import System.IO
import Control.Monad
import Data.List
import Data.Maybe

myFunc ::(Integral a,Enum a)=>[a]->([a],[a])
myFunc []=([],[])
myFunc x =partition (\a ->mod a 2 ==0) x

main = do
    number <-getLine
    numberStr <- getLine
    let n=number
    let numberString=numberStr
    let ori=map read (words numberString)
    let k=myFunc ori
    if (==1).length.fst $ k
    then mapM_ print $ [1+ ( head $ maybeToList (elemIndex (head $ fst k) ori))]
    else mapM_ print $ [1+ ( head $ maybeToList (elemIndex (head $ snd k) ori))]

import Data.List (groupBy)

main :: IO ()
main = do
    getLine
    s <- getLine
    let xs = map read . words $ s :: [Int]
    print $ fst . head . filter (if (sum . map (`mod` 2) . take 3) xs < 2 then (\(_, x) -> odd x) else (\(_, x) -> even x)) $ zip [1..] xs

import Control.Monad
import Data.Array
import Data.Char
import Data.Functor
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
-- import qualified Data.Text as T
import qualified Data.ByteString.Char8 as B
getList :: Read a => IO [a]
getList = map (read . B.unpack) . B.words <$> B.getLine
getIntList :: IO [Int]
getIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

maj :: [Bool] -> Bool
maj (True:True:_)   = True
maj (False:False:_) = False
maj (_:_:a:_)       = a
maj _ = error "WTF"

solve :: [Int] -> Int
solve = (+1) . fromJust . (elemIndex =<< not . maj) . map odd

main :: IO ()
main = do
    _ <- getLine
    a <- getIntList
    print $ solve a

differentParity list = if onlyOneEven list
                       then findIndexWithParity 0 list
                       else findIndexWithParity 1 list

onlyOneEven list = length (filter even list) == 1

findIndexWithParity p (x:xs)
    | p == mod x 2 = 1
    | otherwise = 1 + findIndexWithParity p xs

main = do
       dummy <- getLine
       inputLine <- getLine
       let inputWords = words inputLine
       let list = map read inputWords :: [Int]
       putStrLn (show (differentParity list))

par::[Int]->Int
par xs = if x'>y' then 1 else 0
 where
       (x',y') = par' xs 0 0
       par' [] a b = (a,b)
       par' (x:xs) a b
                     | (mod x 2)==0 = par' xs (a+1) b
                     | (mod x 2)==1 = par' xs a (b+1)

foundans::Int->[Int]->Int->Int
foundans _ [] _= 0
foundans p (x:xs) q
               | p==(mod x 2) = q
               | otherwise    = foundans p xs (q+1)

main = do
 n<-getLine
 m<-getContents
 print . (\xs->foundans (par xs) xs 1) . map (read::String->Int) . words $ m

par'::[Int]->(Int,Int)
par' xs = (sum (map (\x->mod x 2) xs), sum (map (\x->mod (x+1) 2) xs) )

par::[Int]->(Int->Bool)
par xs = if x>y then odd else even
 where (x,y)=par' xs

foundans::(a->Bool)->[a]->Int
foundans f xs = 1+(length $ takeWhile f xs)

main = do
 n<-getLine
 m<-getContents
 print . (\xs->foundans (par xs) xs) . map (read::String->Int) . words $ m

import Data.List
choose ([a], _) = a
choose (_, [b]) = b
solve s = fst . choose . partition (odd.snd) $ zip [1..] s
main = getLine >> getLine >>= print . solve . map read . words

import Control.Applicative
import Data.List

check n | le >1 = snd $ head $ filter (\z-> odd (fst z)) $ zip n [1..]
        | otherwise = snd $ head $ filter (\z-> even (fst z)) $ zip n [1..]
  where le = length $ filter even n

main=do
    getLine
    n<- map read <$> words <$> getLine ::IO [Int]
    print $ check n

import Data.List
import Data.Char
import Data.Maybe
import qualified Data.Set as Set
import Control.Monad
import Control.Applicative

main = do
  _ <- getLine
  xs <- fmap (map read . words) getLine :: IO [Int]
  let p = partition (\x -> x `mod` 2 == 0) xs
      number = if length (fst p) == 1 then head (fst p) else head (snd p)
      answer = fromJust $ findIndex (\x -> x == number) xs
      in print (answer + 1)

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

solve :: [Int] -> Int
solve ns = head [ i | (i, n) <- zip [1..] ns, length [ m | m <- ns, even n == even m ] == 1 ]

import Data.List
main = do
  getLine
  (es,os) <- fmap (partition (even . snd) . zip [1..] . map read . words) getLine
  print $ case es of
            [(n,_)] -> n
            _ -> fst (head os)

import Data.List
import Data.Maybe
main = do
    getLine
    s <- getLine
    let task = map read $ words s
    print $ solve task
solve :: [Integer] -> Int
solve task | trueCount == 1 = (fromJust $ elemIndex True bools) + 1
           | otherwise = (fromJust $ elemIndex False bools) + 1
           where bools = map even task
                 trueCount = length . filter (==True) $ bools

import Data.List

main :: IO()
main = do
  _ <- getLine
  line <- getLine
  putStrLn $ show $ gao $ map read $ words line

gao :: [Int] -> Int
gao a = let key = if length x == 1 then head x else head y in (\(Just x) -> x + 1) $ findIndex (==key) a
  where (x, y) = partition even a

-- Vicfred
-- https://codeforces.com/problemset/problem/25/A

import Data.List
import Data.Maybe

solve :: [Int] -> Int
solve a | length (filter odd a) == 1 = 1 + fromJust (findIndex odd a)
        | otherwise                  = 1 + fromJust (findIndex even a)

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

solve :: [Int] -> Int
solve (a:b:rest) | odd a && even b = if odd (head rest) then 2 else 1
                 | even a && odd b = if even (head rest) then 2 else 1
                 | even a     = (+ 3) . length . takeWhile even $ rest
                 | otherwise  = (+ 3) . length . takeWhile odd $ rest
main = interact $ show . solve . map read . tail . words

solve :: [Int] -> Int
solve (a:b:rest) | even a && even b = (+ 3) . length . takeWhile even $ rest
                 | odd a && even b = if odd (head rest) then 2 else 1
                 | even a && odd b = if even (head rest) then 2 else 1
                 | otherwise  = (+ 3) . length . takeWhile odd $ rest
main = interact $ show . solve . map read . tail . words

import Data.List

solve :: [Int] -> Int
solve a = let
            b = [x | x <- a, mod x 2 == 0];
            c = [x | x <- a, odd x];
            in
                let mb = elemIndex (head (f b c)) a in
                    case mb of
                        Nothing -> error "oo"
                        Just a -> a + 1

f :: [Int] -> [Int] -> [Int]
f a b = if (length a == 1) then a else b

main = do {
    z1 <- getLine;
    z2 <- getLine;
    putStrLn $ show $ solve $ map read (words z2)
}

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad
import Data.List
import Data.Ord
import qualified Data.Foldable as F
import qualified Data.Traversable as T
import Text.Printf

main :: IO ()
main = do
  let readData :: IO [Int]
      readData = map read . words <$> getLine
  n : _ <- readData
  (as, bs) <- partition (odd . snd) . zip [1 ..] . take n <$> readData
  case (as, bs) of
    ([(i, _)], _) -> print i
    (_, [(i, _)]) -> print i

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

get num | length (filter odd num) == 1 = odd
        | otherwise = even

find num = fst . head . filter snd . zip [1..] $ map f num
    where f = get num

main = do
    s <- getLine
    print . find =<< getnum

import Control.Applicative
import Data.Char

main= do
	getLine
	n<- map read.words <$> getLine::IO [Int]
	let x = length $ take 3 ( filter even  n)
	print $  snd $ head $ (filter (\z-> (if x>1 then odd else even)  (fst z)) $ (zip n [1..]))

main = do
  getLine
  m <- getLine
  let m2 = map (even.read) $ words m
  print $ diff m2
th :: Int -> [a] -> a
th 1 y = head y
th n (x:xs) = th (n-1) xs
diff :: Eq a => [a] -> Int
diff (x:x2:x3:[]) = if (x == x2) then 3 else (if (x==x3) then 2 else 1)
diff (x:x2:x3:xs) = if (x == x2) then (diff (x2:x3:xs) + 1) else diff (x:x2:x3:[])

deleteN _ []     = []
deleteN i (a:as)
   | i == 0    = as
   | otherwise = a : deleteN (i - 1) as

getIndex :: [Int] -> Int -> Int
getIndex nums i
    | all odd withoutEl || all even withoutEl = i
    | otherwise = getIndex nums (i + 1)
    where withoutEl = deleteN i nums

main = do
    getLine
    nums_ln <- getLine

    let nums = map (read :: String -> Int) (words nums_ln)
    putStrLn . show $ (getIndex nums 0) + 1

import Data.List

answer :: [Integer] ->Int
answer xs =   if length xs == ans && odd (head xs - last xs) then ans +1 else ans
        where ans = snd $ foldl1 (\old@(e,ind) new@(ne, nin)-> if even (e - ne) then old else new ) (zip xs [1..])

someFunc :: IO ()
someFunc = getLine >> getLine >>= print . subtract 1 . answer . fmap read . words

main :: IO ()
main = someFunc

import Data.List
import Data.Maybe

answer :: [Int] -> Int
answer xs = fromJust (findIndex (\x-> x `rem` 2 == parity) xs) + 1
    where oddCount = length . filter odd $ xs
          parity = fromEnum (oddCount == 1)

solve :: String -> String
solve s = show . answer $ xs
    where _:xs = fmap read . words $ s

main :: IO ()
main = interact $ solve

import Data.List
main = do
	dummy <- getLine
	l <- fmap (map read . words) getLine
	putStrLn $ show $ snd $ head $ (\(a,b) -> if length a == 1 then a else b) $ partition (odd . fst) $ zip l [1 ..]

main = do
	n<-getLine
	rest<-getLine
	putStrLn $ show $ solve $ (map read) (words rest)
solve m | length (filter (odd) m)==1 = length (takeWhile (even) m)+1
	    | otherwise = length (takeWhile (odd) m) +1

import Data.List

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

removeMaybe :: Maybe a -> a
removeMaybe (Just a) = a

solve :: [Int] -> Int
solve a | length (filter odd a) == 1 = 1 + removeMaybe (findIndex odd a)
        | otherwise                  = 1 + removeMaybe (findIndex even a)

-- comment functions to understand
-- and verbalize the problem solving
-- process

-- converts list of strings to list of integers
conv lst jj
  | (null lst) = jj
  | otherwise = conv (tail lst) (jj ++ [(read (head lst))::Int])

-- determine if the weird element is even
weird [e,o]
  | (e == 1) = True
  | otherwise = False

-- convert a Bool to an Int
booltoint boo
  | (boo == True) = 1
  | otherwise = 0

-- count the parity of the elements in the list
countParity ss e o
  | (null ss) = [e,o]
  | otherwise = countParity (tail ss)
    (e + (booltoint (even (head ss))))
    (o + (booltoint (odd  (head ss))))

-- search the list for the first instance
-- of the "weird" element which has a unique
-- parity
searchlist lst rr indx
  | (rr == True) = if (even (head lst))
    then indx
    else searchlist (tail lst) rr (indx+1)
  | otherwise = if(odd (head lst))
    then indx
    else searchlist (tail lst) rr (indx+1)

main = do
  ff <- getLine
  oo <- getLine
  let ss = (conv (words oo) [])
      uu = (countParity ss 0 0)

  if (weird uu)
    then putStrLn (show ((searchlist ss (weird uu) 0)+1))
    else putStrLn (show ((searchlist ss (weird uu) 0)+1))

main :: IO()
main = do
    n <- readLn :: IO Int
    a <- fmap ((map read) . words) getLine :: IO [Int]
    let l = take 3 a
        eL = length . filter even $ l
        oL = length . filter odd $ l
        fn = if eL > oL then odd else even
    print $ solve 1 fn a
        where solve _ _ [] = -1
              solve i fn (a:as) = if fn a then i else solve (i+1) fn as

import Data.Maybe
import Data.List

main = do
  getLine
  xs <- fmap (map read . words) getLine
  let (a, b) = partition even xs

  print $ (fromJust $ elemIndex (head $ if length a == 1 then a else b) xs) + 1

main = getContents >>= putStrLn . show . func . map read . words . last . lines

func :: [Int] -> Int
func [] = 0
func xs = findNumber xs $ if length oddX > length evenX then head evenX else head oddX
			where
			oddX = [y | y <- xs , odd y]
			evenX = [y | y <- xs , even y]

findNumber :: (Eq a, Num b) => [a]-> a -> b
findNumber [] m = 0
findNumber (x:xs) m = 1 + if x == m
								then 0
								else findNumber xs m

import Data.List
import Data.Maybe
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve. map read. words.head.tail.lines
solve :: [Int]->String
solve xs = show $ (1+) $ fromJust $ findIndex (slv1) $ zip ( cycle xs)  $ zip (tail $ cycle xs) ( tail $ tail $ cycle xs)
  where slv1 (x,(y,z)) = let x1 = x `mod` 2; y1 = y `mod` 2; z1 = z `mod` 2 in y1==z1 && x1/=y1

main :: IO ()
main = interact func

func :: String -> String
func s = show.func' 1.map (`mod` 2).map read.words.head.tail$lines s

func' :: Int -> [Int] -> Int
func' _ [] = error ""
func' n (0:0:1:_) = n+2
func' n (0:1:0:_) = n+1
func' n (1:0:0:_) = n
func' n (1:1:0:_) = n+2
func' n (1:0:1:_) = n+1
func' n (0:1:1:_) = n
func' n (_:xs) = func' (n+1) xs

main :: IO ()
main = interact func

func :: String -> String
func s = show.func' 1.map (`mod` 2).map read.words.head.tail$lines s

func' :: Int -> [Int] -> Int
func' n (a:b:c:xs)
  | a == b && b /= c = n + 2
  | a == c && b /= c = n+1
  | a /= b && b == c = n
  | otherwise = func' (n+1) (b:c:xs)
func' _ _ = error ""

readInts :: IO [Int]
readInts = do
  line <- getLine
  return (map read (words line))

solve :: Int -> [Bool] -> Int
solve 1 (a:b:c:as)
  | a /= b && b == c  =  1
  | otherwise         =  solve 2 (a:b:c:as)
solve n (a:b:[])      =  n
solve n (a:b:c:as)
  | a /= b && b /= c  =  n
  | otherwise         =  solve (n + 1) (b:c:as)
solve _ _             =  error "Owibka v dannyh."

main = do
  getLine
  as <- readInts
  print (solve 1 (map odd as))

import Data.List

answer :: [Integer] ->Integer
answer xs =  snd $ foldl1 (\old@(e,ind) new@(ne, nin)-> if even (e - ne) then old else new ) (zip xs [1..])

someFunc :: IO ()
someFunc = getLine >> getLine >>= print . subtract 1 . answer . fmap read . words

main :: IO ()
main = someFunc

import Data.List

answer :: [Integer] ->Int
answer xs =  if res /= length xs then res - 1 else res
                    where res = snd $ foldl1 (\old@(e,ind) new@(ne, nin)-> if even (e - ne) then old else new ) (zip xs [1..])

someFunc :: IO ()
someFunc = getLine >> getLine >>= print  . answer . fmap read . words

main :: IO ()
main = someFunc

import Data.List

answer :: [Integer] ->Int
answer xs =  if length xs == ans && even (head xs - last xs) then ans - 1 else ans
        where ans = snd $ foldl1 (\old@(e,ind) new@(ne, nin)-> if even (e - ne) then old else new ) (zip xs [1..])

someFunc :: IO ()
someFunc = getLine >> getLine >>= print . subtract 1 . answer . fmap read . words

main :: IO ()
main = someFunc

import Data.List

answer :: [Integer] ->Int
answer xs =  if length xs == ans && even (head xs - last xs) then ans - 1 else ans
        where ans = snd $ foldl1 (\old@(e,ind) new@(ne, nin)-> if even (e - ne) then old else new ) (zip xs [1..])

someFunc :: IO ()
someFunc = getLine >> getLine >>= print  . answer . fmap read . words

main :: IO ()
main = someFunc

main :: IO()
main = do
    n <- readLn :: IO Int
    a <- fmap ((map read) . words) getLine :: IO [Int]
    let l = take 3 a
        eL = length . filter even $ l
        oL = length . filter odd $ l
        fn = if eL == 1 then even else odd
    print $ solve 1 fn a
        where solve _ _ [] = -1
              solve i fn (a:as) = if fn a then i else solve (i+1) fn as

main :: IO()
main = do
    n <- readLn :: IO Int
    a <- fmap ((map read) . words) getLine :: IO [Int]
    let l = take 3 a
        eL = length . filter even $ l
        oL = length . filter odd $ l
        fn = if eL > oL then even else odd
    print $ solve 1 fn a
        where solve _ _ [] = -1
              solve i fn (a:as) = if fn a then i else solve (i+1) fn as

main = getContents >>= putStrLn . show . func . map read . words . last . lines

func :: [Int] -> Int
func [] = 0
func xs = if length oddX > length evenX then head evenX else head oddX
			where
			oddX = [y | y <- xs , odd y]
			evenX = [y | y <- xs , even y]

par::[Int]->Int
par xs = if x'>y' then 1 else 0
 where
       (x',y') = par' xs 0 0
       par' [] a b = (a,b)
       par' (x:xs) a b
                     | (mod x 2)==0 = par' xs (a+1) b
                     | (mod x 2)==1 = par' xs a (b+1)

foundans::Int->[Int]->Int
foundans _ [] = 0
foundans p (x:xs)
               | p==(mod x 2) = x
               | otherwise    = foundans p xs

main = do
 n<-getLine
 m<-getContents
 print . (\xs->foundans (par xs) xs) . map (read::String->Int) . words $ m

par'::[Int]->(Int,Int)
par' xs = (sum (map (\x->mod x 2) xs), sum (map (\x->mod (x+1) 2) xs) )

par::[Int]->(Int->Bool)
par xs = if x>y then odd else even
 where (x,y)=par' xs

foundans::(a->Bool)->[a]->Int
foundans f xs = length $ takeWhile f xs

main = do
 n<-getLine
 m<-getContents
 print . (\xs->foundans (par xs) xs) . map (read::String->Int) . words $ m

import Data.List
split s = map (map snd) . groupBy  (\(a,_) (b,_) -> div a 3 == div b 3) . zip [0..] $ s
solve s = intercalate "-" . reverse . adjust . reverse . split $ s
    where adjust ([x]:[a,b,c]:xs) = [a,b,'-',c,x]:xs
          adjust xs = xs

main = getLine >> getLine >>= putStrLn . solve

import Control.Applicative
import Data.List

check n | le >1 = head $ filter odd n
        | otherwise = head $ filter even n
  where le = length $ filter even n

main=do
    getLine
    n<- map read <$> words <$> getLine ::IO [Int]
    print $ check n

solve :: [Int] -> Int
solve (a:b:rest) | even a && even b = (+ 3) . length . takeWhile even $ rest
                 | odd a && even b = if odd (head rest) then 2 else 1
                 | otherwise  = (+ 3) . length . takeWhile odd $ rest
main = interact $ show . solve . map read . tail . words

import Data.List

solve :: [Int] -> Int
solve a = let
            b = [x | x <- a, mod x 2 == 0];
            c = [x | x <- a, odd x];
            in
                if (length b) == 1 then head b else head c

main = do {
    z1 <- getLine;
    z2 <- getLine;
    putStrLn $ show $ solve $ map read (words z2)
}

getIndex :: [Int] -> Int -> Int -> Int
getIndex (x:xs) curSum ind
    | newSum `mod` 2 == 1 = ind
    | otherwise = getIndex xs newSum newInd
    where newSum = curSum + x
          newInd = ind + 1

main = do
    getLine
    ln <- getLine
    nums <- return . map (read :: String -> Int) $ words ln
    putStrLn . show $ getIndex (tail nums) (head nums) 2

getIndex :: [Int] -> Int -> Int
getIndex (x:xs) ind
    | null xs = ind
    | x `mod` 2 /= head xs `mod` 2 = ind
    | otherwise = getIndex xs (ind + 1)

main = do
    n_ln <- getLine
    nums_ln <- getLine

    let n = read n_ln :: Int
    let nums = map (read :: String -> Int) (words nums_ln)

    let ia = getIndex nums 1
    let ib = n - getIndex (reverse nums) 0

    putStrLn . show $ (ia + ib) `div` 2


{-# 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 Data.Char

main :: IO ()
main = do
  n <- readInt <$> getLine
  as <- A.listArray (0,n-1) . sort . map toI64 .
    unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine
  m <- readInt <$> getLine
  qs <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine
  let s = sum (A.elems as)
  forM_ qs $ print . query n as s m

query :: Int -> UArray Int Int64 -> Int64 -> Int -> Int -> Int64
query n as sumas m q = sumas - (as A.! (n-q))

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 Control.Monad
import Data.List
import Data.Array

main :: IO ()
main = do
   n <- readLn
   as <- (map read.words) <$> getLine
   _ <- getLine
   let arr = listArray (1,n) (sort as)
   let s = sum arr
   qs <- (map read.words) <$> getLine
   forM_ qs (print.solve arr s n)

solve :: Array Integer Integer -> Integer -> Integer -> Integer -> Integer
solve arr s n q = s - arr!(n-q+1)

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

main = do
    let int =  fst . fromJust . B.readInteger
        ints = map int . B.words
    n <- int <$> B.getLine
    as'' <- ints <$> B.getLine
    let as' = sort as''
        as = array(0,n-1) $ zip [0..n-1] $ as'
        bs = array(0,n-1) $ zip [0..n-1] $ scanr (+) 0 as'
        cs = array(0,n-1) $ zip [0..n-1] $ scanl (+) 0 as'
    B.getLine
    (ints <$> B.getLine) >>=  mapM_ (\i -> print $ bs!(n - i) - as!(n-i) + cs!(n-i))

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

main :: IO ()
main = do
   n <- readLn
   as <- (map read.words) <$> getLine
   _ <- getLine
   let arr = listArray (1,n) (sort as)
   let s = sum arr
   qs <- (map read.words) <$> getLine
   forM_ qs (print.solve arr s n)

solve :: Array Int Int -> Int -> Int -> Int -> Int
solve arr s n q = s - arr!(n-q+1)

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

main = do
    let int =  fst . fromJust . B.readInt
        ints = map int . B.words
    n <- int <$> B.getLine
    as'' <- ints <$> B.getLine
    let as' = sort as''
        as = array(0,n-1) $ zip [0..n-1] $ as'
        bs = array(0,n-1) $ zip [0..n-1] $ scanr (+) 0 as'
        cs = array(0,n-1) $ zip [0..n-1] $ scanl (+) 0 as'
    B.getLine
    (ints <$> B.getLine) >>=  mapM_ (\i -> print $ bs!(n - i) - as!(n-i) + cs!(n-i))

{-# 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 Data.Char

main :: IO ()
main = do
  n <- readInt <$> getLine
  as <- A.listArray (0,n-1) . sort .
    unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine
  m <- readInt <$> getLine
  qs <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine
  let s = sum (A.elems as)
  forM_ qs $ print . query n as s m

query :: Int -> UArray Int Int -> Int -> Int -> Int -> Int
query n as sumas m q = sumas - (as A.! (n-q))

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
main = interact $ unlines . map res . process . tail . lines

res True = "YES"
res False = "NO"

process [] = []
process (x:y:t) = check (group x) (group y) : process t

check [] [] = True
check _ [] = False
check [] _ = False
check (a1:t1) (a2:t2)
  | ((head a1) == (head a2)) && ((length a1) <= (length a2)) = check t1 t2
  | otherwise = False

{-# LANGUAGE ScopedTypeVariables #-}

import Text.Printf
import Data.List
import Data.Functor
import Data.Function
import Control.Monad
import Data.Maybe
import Prelude
import qualified Data.ByteString.Char8 as B8

type CompressedString = [(Char, Int)]

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

readB8Int :: B8.ByteString -> Int
readB8Int = fst . fromJust . B8.readInt

compressFold :: Char -> CompressedString -> CompressedString
compressFold c [] = [(c, 1)]
compressFold c cs@((fc, flen):other)
    | fc == c   = (fc, flen + 1):other
    | otherwise = (c, 1):cs

compress :: B8.ByteString -> CompressedString
compress = B8.foldr' compressFold []

main :: IO ()
main = do
    n <- readB8Int <$> B8.getLine
    replicateM_ n $ do
        stra <- head <$> B8.words <$> B8.getLine
        strb <- head <$> B8.words <$> B8.getLine
        let cstra = compress stra
        let cstrb = compress strb
        let isleneq = ((==) `on` length) cstra cstrb
        let isok = all (\((ca, la), (cb, lb)) -> (ca == cb) && (la <= lb)) $ zip cstra cstrb
        let answer = if isok && isleneq then "YES" else "NO"
        printf "%s\n" $ answer

solve :: String -> String -> Bool
solve a b = solve' a b '\0'

solve' :: String -> String -> Char -> Bool
solve' "" "" _ = True
solve' _  "" _ = False
solve' "" (b:bs) c = b == c && solve' "" bs c
solve' (a:as) (b:bs) c
    | a == b    = solve' as bs a
    | b == c    = solve' (a:as) bs c
    | otherwise = False

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

main :: IO ()
main = do
        n <- read <$> getLine
        let readans = (solve <$> getLine <*> getLine) >>= (putStrLn . boolstr)
        sequence $ replicate n readans
        return ()


import Data.IntMap (IntMap, empty, alter, elems, findWithDefault)

readArr :: IO [Int]
readArr = (map (\s -> read s :: Int)) <$> (words <$> getLine)

fromList :: [Int] -> IntMap Int
fromList [] = empty
fromList (x: xs) = alter (\x -> case x of
  Nothing -> Just 1
  Just a -> Just (a + 1)) x (fromList xs)

calcH :: [Int] -> Int -> Int
calcH a x = if sum (map (\i -> if i < x then (x - i) `div` 2 else (x - i)) a) >= 0
  then x
  else calcH a (x + 1)

calc :: [Int] -> Int
calc a = calcH a 1

for :: Int -> IO ()
for 0 = pure ()
for i = do
  (n: m: _) <- readArr
  a <- readArr
  let x = map (\i -> findWithDefault 0 i (fromList a)) [1..n]
  print $ calc x
  for $ i - 1

main :: IO ()
main = do
  n <- readLn :: IO Int
  for n

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

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

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

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

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

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

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

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

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

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

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

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

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

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

{- END OF GENERAL -}

findLowerBound :: (Int -> Bool) -> (Int, Int) -> Int
findLowerBound f (l, r) | l == r = l
findLowerBound f (l, r) = if f c
        then findLowerBound f (l, c)
        else findLowerBound f (c + 1, r)
    where
        c = (l + r) `div` 2

solve :: Int -> Int -> [Int] -> Int
solve n m as = answer
    where
        answer = findLowerBound canSchedule (1, 2 * m)

        canSchedule :: Int -> Bool
        canSchedule t = ST.runST $ do
            timeLeftA <- MA.newArray (1, n) t :: ST.ST s (STA.STUArray s Int Int)
            tasksLeft <- flip S.execStateT 0 $ do
                forM_ as $ \a -> do
                    workerTimeLeft <- T.lift $ MA.readArray timeLeftA a
                    if workerTimeLeft > 0
                        then T.lift $ modifyArray timeLeftA a pred
                        else S.modify succ
            workersTasksLeft <- MA.getElems timeLeftA <&> sum . map (`div` 2)
            return $ tasksLeft <= workersTasksLeft

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

import Data.IntMap (IntMap, empty, alter, elems, findWithDefault)

readArr :: IO [Int]
readArr = (map (\s -> read s :: Int)) <$> (words <$> getLine)

fromList :: [Int] -> IntMap Int
fromList [] = empty
fromList (x: xs) = alter (\x -> case x of
  Nothing -> Just 1
  Just a -> Just (a + 1)) x (fromList xs)

calcH :: [Int] -> Int -> Int
calcH a x = if sum (map (\i -> if i < x then x - i else 2 * (x - i)) a) >= 0
  then x
  else calcH a (x + 1)

calc :: [Int] -> Int
calc a = calcH a 1

shrinkH :: Int -> [Int]
shrinkH 0 = []
shrinkH i = (0: shrinkH (i - 1))

shrink :: Int -> [Int] -> [Int]
shrink n a = shrinkH (n - length a) ++ a

for :: Int -> IO ()
for 0 = pure ()
for i = do
  (n: m: _) <- readArr
  a <- readArr
  let x = map (\i -> findWithDefault 0 i (fromList a)) [1..n]
  print $ calc x
  for $ i - 1

main :: IO ()
main = do
  n <- readLn :: IO Int
  for n

import Data.IntMap (IntMap, empty, alter, elems)

readArr :: IO [Int]
readArr = (map (\s -> read s :: Int)) <$> (words <$> getLine)

fromList :: [Int] -> IntMap Int
fromList [] = empty
fromList (x: xs) = alter (\x -> case x of
  Nothing -> Just 1
  Just a -> Just (a + 1)) x (fromList xs)

calcH :: [Int] -> Int -> Int
calcH a x = if sum (map (\i -> if i < x then x - i else 2 * (x - i)) a) >= 0
  then x
  else calcH a (x + 1)

calc :: [Int] -> Int
calc a = calcH a 0

shrinkH :: Int -> [Int]
shrinkH 0 = []
shrinkH i = (0: shrinkH (i - 1))

shrink :: Int -> [Int] -> [Int]
shrink n a = shrinkH (n - length a) ++ a

for :: Int -> IO ()
for 0 = pure ()
for i = do
  (n: m: _) <- readArr
  a <- readArr
  let x = shrink n (elems $ fromList a)
  print $ calc x
  for $ i - 1

main :: IO ()
main = do
  n <- readLn :: IO Int
  for n


main = interact $ show.maximum.f.map (map read.words).tail.lines

f = scanl (\s x->s-head x+last x) 0

main = print . solve . pairs . map read . tail . words =<< getContents
pairs (x:y:zs) = (x,y) : pairs zs
pairs _ = []
solve = maximum . scanl stop 0
stop n (a,b) = n - a + b

solve :: Int -> [Int] -> Int
solve a [] = 0
solve a (x:y:xs) = max a $ solve (a-x+y) xs

readInt :: String -> Int
readInt = read

parse :: String -> String
parse x = show $ solve 0 $ tail $ map readInt $ words x

main = interact parse

solve :: [(Integer, Integer)] -> Integer
solve stops = getCapacity stops 0
getCapacity :: [(Integer, Integer)] -> Integer -> Integer
getCapacity [] n = n
getCapacity ((pOut, pIn):xs) n = max newCap $ getCapacity xs newCap
    where newCap = n - pOut + pIn

main = do
    count <- getLine
    stops <- mapM readStops [1..read count]
    print $ solve stops

readStops _ = do
    str <- getLine
    let [a,b] = map read . words $ str
    return (a,b)

import Control.Applicative
import Control.Monad

listToT2 (x:y:_) = (x,y)

main = do
  n <- read <$> getLine :: IO Int
  ts <- replicateM n $ (listToT2.(map read).words) <$> getLine
  print $ snd$solve ts
  return ()

solve :: [(Int,Int)] -> (Int,Int)
solve xs = foldl apply (0,0) xs
  where
    apply :: (Int,Int) -> (Int,Int) -> (Int,Int)
    apply (sum,maxi) (a,b) = (newsum, max maxi newsum)
      where newsum = sum + b - a

import Control.Monad
import Data.Array
import Data.Char
import Data.List
import qualified Data.ByteString.Char8 as B
getList :: Read a => IO [a]
getList = fmap (map (read . B.unpack) . B.words) B.getLine
getIntList :: IO [Int]
getIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine

busstop :: [Int] -> Int
busstop (a:b:[]) = b - a
busstop _        = error "WTF"

solve :: [[Int]] -> Int
solve = maximum . scanl1 (+) . map busstop

main :: IO ()
main = do
        n <- readLn :: IO Int
        a <- replicateM n getIntList
        putStrLn . show $ solve a

module Main where
import Data.List
import Control.Applicative
calcLineDif :: String -> Int
calcLineDif str = let [s1,s2] = words str; (i1,i2) = (read s1, read s2) in i2 - i1

sumPassangers :: (Int,Int) -> Int -> (Int,Int)
sumPassangers (maxi,cur) newPassangers = let newCur = cur + newPassangers in if newCur > maxi then (newCur,newCur) else (maxi,newCur)

main = do
  stops <- (read :: String -> Int) <$> getLine
  print =<< fst <$> foldl sumPassangers (0,0) <$> mapM (\_ ->calcLineDif <$> getLine) [1..stops]

run = foldr (\(a:b:_) rest -> (-a + b) : rest) []
main = interact $ show . maximum . scanl (+) 0 . run . map (map read . words) . tail . lines

main = do
  n <- fmap read getLine :: IO Int
  input <- getContents
  let pairs = map muhParse $ take n $ lines input
  let changes = map (\(x,y) -> y-x) pairs
  let partSums = partSum changes
  let answer = maximum partSums
  putStrLn $ show answer

muhParse :: String -> (Int,Int)
muhParse s = (a,b) where a:b:[] = (map read $ words s :: [Int])

partSum :: [Int] -> [Int]
partSum xs = [sum $ take n xs | n <- [1..length xs + 1]]

import Data.List
import Control.Monad
import Control.Applicative
import Debug.Trace

type Z = Integer

myRead :: IO (Z,Z)
myRead = (\[a,b] -> (a,b)) . map read . words <$> getLine

iDiff :: (Z,Z) -> Z
iDiff (a,b) = b-a

traceS x y = trace (show x) y

solve :: [(Z,Z)] -> Z
solve abs = maximum rs
  where rs = solve' 0 abs

solve' :: Z -> [(Z,Z)] -> [Z]
solve' _ [] = []
solve' x (ab:abs) = x' : solve' x' abs
  where x' = x + iDiff ab

main = do
  n <- read <$> getLine
  abs <- replicateM n myRead
  print $ solve abs

solve [] prev = prev
solve ((a, b):xs) prev = (max y (solve xs y)) where y = prev - a + b

main :: IO()
main = do
    n <- getLine
    contents <- getContents
    let input = map ((\(a:b:_) -> (a, b)) . map (read :: String -> Int) . words) $ lines contents
    print(solve input 0)

solve :: [(Int, Int)] -> Int -> Int
solve [] prev = prev
solve ((a, b):xs) prev = (max (prev - a + b) (solve xs (prev - a + b)))

main :: IO()
main = do
    n <- getLine
    contents <- getContents
    let input = map ((\(a:b:_) -> (a, b)) . map (read :: String -> Int) . words) $ lines contents
    print(solve input 0)

import Control.Monad (foldM)
main = do
    n <- read `fmap` getLine
    (_, m) <- foldM (\(all, m) _ -> do
        [ai, bi] <- (map read . words) `fmap` getLine
        let all' = ((all - ai) `max` 0) + bi
        return (all', max m all')) (0, 0) [1..n]
    print m

main = interact $ show . maximum . scanl (+) 0 . map ((\[x,y] -> y - x) . map read.words) . tail . lines

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Debug.Trace
import Data.List
import Control.Monad
import Data.Array
import Data.Char
class Expression a where scan' :: String -> a; showans :: a -> String
instance Expression Int where scan' = read; showans = show
instance Expression Char where scan' (x:_) = x;showans = (:[])
instance Expression Float where scan' = read;showans = show
instance Expression Double where scan' = read;showans = show
instance Expression Integer where scan' = read;showans = show
instance Expression String where scan' = id;showans = id
instance (Expression a,Expression b) => Expression (a,b) where
    scan' = (\(x:y:_) -> (scan' x,scan' y)).words;showans (x,y) = showans x++' ':showans y
instance (Expression a,Expression b,Expression c) => Expression (a,b,c) where
    scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;showans (x,y,z) = showans x++' ':showans y++' ':showans z
instance (Expression a,Expression b,Expression c,Expression d) => Expression (a,b,c,d) where
    scan' = (\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)).words;showans (w,x,y,z) = showans w++' ':showans x++' ':showans y++' ':showans z
instance (Expression a,Expression b,Expression c,Expression d,Expression e) => Expression (a,b,c,d,e) where
    scan' = (\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)).words;showans (v,w,x,y,z) = showans v++' ':showans w++' ':showans x++' ':showans y++' ':showans z
scan :: (Expression a) => IO a; scan = getLine>>=(return.scan')
scans :: (Expression a) => Int -> IO [a]; scans n = replicateM n scan
scanlist :: (Expression a) => IO [a]; scanlist = getLine>>=return.(map scan').words
scanlists :: (Expression a) => Int -> IO [[a]]; scanlists n = replicateM n scanlist
putAnsLn :: (Expression a) => a -> IO (); putAnsLn = putStrLn.showans
putAnsLns :: (Expression a) => [a] -> IO (); putAnsLns = mapM_ putAnsLn

solve :: [(Int, Int)] -> Int -> Int -> Int
solve [] _ n = n
solve ((out,enter):xs) m n = let m' = m + enter - out in
                             solve xs m' (max n m')

main = do n <- scan :: IO Int
          l <- scans n :: IO [(Int, Int)]
          print (solve l 0 0)

main = interact$show.maximum.scanl1 (+).map (negate.foldl1 (-).map read.words).tail.lines

getList :: [Int] -> [(Int,Int)]
getList [] = []
getList (v1:v2:vs) = [(v1,v2)] ++ getList vs

main = do
  str <- getContents
  let
    n:values = map read $ words str
    res = foldl (\(cur,cap) (down,up) -> ((cur-down+up),(max cap (cur-down+up)))) (0,0) $ getList values
  putStrLn $ show $ snd res

module Main (main) where

peak :: [(Int, Int)] -> Int
peak = maximum . scanl f 0
  where f a (from, to) = a - from + to

main :: IO ()
main = do cont <- getContents
          let a = fmap ((\[a, b] -> (read a, read b)) . words) $ tail $ lines cont
          print $ peak a

main = interact $ show . maxCap (0,0) . map read . tail . words

maxCap (_,m) [] = m
maxCap (s,m) (d:u:ls) = maxCap (new, max m new) ls
    where new = s-d+u

main :: IO ()
main = do
    n <- getLine
    getPassengers 0 0 $ read n

getPassengers :: Int -> Int -> Int -> IO ()
getPassengers capacity 0 0 = print capacity >>= return
getPassengers _        n 0 =
    print "getPassgeners: Passenger on last stop!" >>= return
getPassengers capacity current n = do
    passengers <- getLine
    let [exit,enter] = map read $ words passengers
        current'     = current - exit + enter
    if current' > capacity
      then getPassengers current' current' $ n - 1
      else getPassengers capacity current' $ n - 1

import Control.Monad
split [] r = r
split (x:y) r
    | not (x == ' ') =  split y ((init r) ++ [(last r) ++ [x]])
    | otherwise = split y (r ++ [""])
toInt r = [read x::Int | x <- r]

go :: [[Int]] -> Int -> [Int] ->[Int]
go [] x y = y
go (r1:r2) x y = go r2 (x - (r1!!0) + (r1!!1)) ((x - (r1!!0) + (r1!!1)):y)
solve :: [[Int]] -> [Int]
solve r = go r 0 []

main = do
    nn <- getLine
    let n = read nn :: Int
    ip <- replicateM n getLine
    --print ip
    let ip2 = [toInt (split x [""]) | x <- ip]
    --print ip2
    let r = solve ip2
    print (maximum r)

module Main (main) where

import System.Environment
import Data.Char
import Data.List
import Control.Monad
import Control.Applicative

solve :: [Int] -> Int
solve array = maxValue - minValue
  where
    maxValue = maximum list2
    minValue = minimum list2
    list     = [i*x | (i,x) <- zip (cycle [1,-1]) array]
    list2    = scanl (+) 0 list :: [Int]

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

module Main (main) where

import System.Environment
import Data.Char
import Data.List
import Control.Monad
import Control.Applicative

solve :: [Int] -> Int
solve array = maxValue - minValue
  where
    maxValue = maximum list2
    minValue = minimum list2
    list     = [if i `mod` 2 == 0 then -x else x | (i,x) <- zip [1..] array]
    list2    = scanl (+) 0 list :: [Int]

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

read_int :: String -> Int
read_int = read

get_max :: Int -> Int -> [String] -> Int
get_max curr m [] = m
get_max curr m (s:ss) =
  let nums = map read_int $ words s
      a    = nums !! 0
      b    = nums !! 1
      newCurr = curr-a+b
  in get_max (newCurr) (max newCurr m) ss

solve :: [String] -> Int
solve = get_max 0 0

main = interact $ show . solve . tail . lines

import Control.Applicative
import Data.List
main= do
	getLine
	s<-map (map read ). (map words).lines <$> getContents
	print $ maximum $  scanl (+) 0 $ map (\(a:b:[]) -> b-a) s

{-
A. Tram
=========
time limit per test: 2 seconds
memory limit per test: 256 megabytes
input: standard input
output: standard output

Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.

Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.

Input
-----
The first line contains a single number n (2 ≤ n ≤ 1000) — the number of the tram's stops.

Then n lines follow, each contains two integers ai and bi (0 ≤ ai, bi ≤ 1000) — the number of passengers that exits the tram at the i-th stop, and the number of passengers that enter the tram at the i-th stop. The stops are given from the first to the last stop in the order of tram's movement.

The number of people who exit at a given stop does not exceed the total number of people in the tram immediately before it arrives at the stop. More formally, . This particularly means that a1 = 0.
At the last stop, all the passengers exit the tram and it becomes empty. More formally, .
No passenger will enter the train at the last stop. That is, bn = 0.

Output
-------
Print a single integer denoting the minimum possible capacity of the tram (0 is allowed).

Sample test(s)
--------------
input
```
4
0 3
2 5
4 2
4 0
```
output
```
6
```

Note
-----
For the first example, a capacity of 6 is sufficient:

- At the first stop, the number of passengers inside the tram before arriving is 0. Then, 3 passengers enter the tram, and the number of passengers inside the tram becomes 3.
- At the second stop, 2 passengers exit the tram (1 passenger remains inside). Then, 5 passengers enter the tram. There are 6 passengers inside the tram now.
- At the third stop, 4 passengers exit the tram (2 passengers remain inside). Then, 2 passengers enter the tram. There are 4 passengers inside the tram now.
- Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints.

Since the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer.

-}

tramCapacity :: [[Int]] -> Int
tramCapacity xss = maximum $ scanl (\acc [minus, plus] -> acc + plus - minus) 0 xss

reader :: String -> [[Int]]
reader s = [map read $ words line | line <- xs]
  where _:xs = lines s

main = do
  input <- getContents
  let xss = reader input
  print $ tramCapacity xss

main = do
  m <- readLn
  tp <- sequence $ replicate m getLine
  let tp2 = map (map read . words) tp
  let tp3 = map (\[x,y] -> y -x) tp2
  let tp4 = [sum $ take i tp3 | i <- [1..m]]
  print $ maximum tp4

import           Control.Monad
folder :: (Int, Int) -> (Int, Int) -> (Int, Int)
folder (a, m) (d, u) =
    let a' = a + u - d
    in (a', max m a')

tupler :: [Int] -> (Int, Int)
tupler (a:b:rest) = (a, b)

main :: IO ()
main = do
    n <- (read :: String -> Int) <$> getLine
    (0, ans) <- foldl folder (0, 0) . map (tupler . map (read :: String -> Int) . words) <$> replicateM n getLine
    print ans

main = interact $ show . maximum . scanl (+) 0 . map ((\[x, y] -> y - x) . map read . words) . tail . lines

module Main where

import           Control.Applicative

f :: [Int] -> [Int]
f [] = []
f (x:xs) = (x + sum xs) : f xs

main :: IO ()
main = do
  n <- read <$> getLine :: IO Int
  xs <- map ((\(x:y:_) -> -x + y ) .map read . words) <$> (sequence $ replicate n getLine) :: IO [Int]
  putStrLn . show . maximum . f . reverse $ xs

import Control.Monad
import Data.List

main = getLine >>=
       (flip replicateM $ getLine >>= return.map read.words).read >>=
       putStrLn.show.solve.reverse

solve :: [[Int]] -> Int
solve input = maximum.diffs $ ticks input

ticks :: [[Int]] -> [Int]
ticks input = filter (/=0) $ map (\[a, b] -> b - a) input

diffs :: [Int] -> [Int]
diffs []     = [0]
diffs (a:as) = (sum (a:as)):(diffs as)

import Data.List

process :: [(Int,Int)] -> Int
process = maximum . scanl' (\acc (a,b) -> acc+b-a) 0

readInt :: String -> Int
readInt = read

readPair :: String -> (Int,Int)
readPair line = (a,b)
    where [a,b] = map readInt $ words line

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

import Data.Char
import Data.List

ans a = maximum $ scanl (\x y->x-head y+last y) 0 a

main = do
    n<-getLine
    a<-getContents
    let input = map  (map (\x->read x::Int)) (map words $ lines a)
    print $ ans input

import Control.Applicative

main :: IO ()
main = print =<< solve . map f . tail . lines <$> getContents  where
    f = (\(x:y:_) -> (y - x)) . map read . words

solve :: [Int] -> Int
solve = foldl max 0 . scanl (+) 0

import Control.Applicative

main :: IO ()
main = interact $ show . maximum . scanl (+) 0 . map ((\(x:y:_) -> (y - x)) . map read . words) . tail . lines

import Control.Applicative

main :: IO ()
main = interact $ show . foldl max 0 . scanl (+) 0 . map ((\(x:y:_) -> (y - x)) . map read . words) . tail . lines

import Control.Monad

toInt :: String -> Int
toInt = read

toTuple :: String -> (Int, Int)
toTuple s = ( head x, last x )
			where 	x = ( (map (toInt) ) . words ) s

findMaxCapacity :: [( Int, Int )] -> Int
findMaxCapacity xs 	= snd ( foldl f (0,0) xs )
					where f (a1, a2) (x1, x2) = ( tmp, max a2 tmp)
												where tmp = a1 - x1 + x2
main = do
	strN 		<- getLine
	inoutData 	<- replicateM (toInt strN) getLine
	print $ 	findMaxCapacity ( map toTuple inoutData )

main = interact $ show . f 0 0 . map read . tail . words

f a b [] = b
f a b (x:y:xs) = f (a-x+y) (max b (a-x+y)) xs

solve :: String -> String
solve = show . capacity . fmap (fmap read . words) . tail . lines

capacity :: [[Int]] -> Int
capacity = maximum . scanl (\ acc (x : y: _) -> acc - x + y) 0

main :: IO ()
main = interact solve

main = do
    n <- getLine
    xs <- sequence $ replicate (read n::Int) getLine
    putStrLn $ show $ maximum $ scanl (+) 0 $ map (\[x , y] -> -(read x::Int) + read y::Int) $ map words xs

tram :: [[Int]] -> Int
tram = let func (curr, m) [x, y] = if next > m then (next, next) else (next, m)
 	       where next = curr - x + y
 	   in snd . foldl func (0, 0)

readInt :: String -> Int
readInt = read

parse :: String -> String
parse = show . tram . map (\line -> map readInt $ words line) . lines

main = do
	getLine
	interact parse

module Main where

--71A
--replicateM n x = sequence (replicate n x)

--processWord :: String -> String
--processWord word | length word > 10 = (head word) : (show (length word - 2)) ++ ((last word):[])--(word !! ((length word) - 1))
--                 | otherwise = word

--main = sequence [putStrLn $ show i | i <- [1..5]]
--main = getLine >>= \line -> replicateM (read line) (getLine) >>= \list -> sequence [putStrLn (processWord (list!!i)) | i <- [0..(length list) - 1]]

--118A
--import Data.Char
--isSylable :: Char -> Bool
--isSylable char = elem char "AOYEUIaoyeui"
--
--deleteSylabls::[Char] -> [Char]
--deleteSylabls [] = []
--deleteSylabls (x:xs) | isSylable x = deleteSylabls xs
--                     | otherwise = x:(deleteSylabls xs)
--
--addDots :: [Char] -> [Char]
--addDots [] = []
--addDots (x:xs) = '.' : x : (addDots xs)
--
--processWord :: String -> String
--processWord = addDots . deleteSylabls . (map toLower)
--
--main = getLine >>= putStrLn . processWord

--50A

--split :: Char -> String -> [String]
--split _ [] = [""]
--split c (x:xs) | x == c = "" : rest
--               | otherwise = (x : head rest): tail rest
--                where rest = split c xs
--
--calc :: Int -> Int -> Int
--calc  m n = m*n `div` 2
--
--main = getLine >>= \a -> let inp = (map read (split  ' ' a)) in putStrLn $ show $ calc (inp !! 0) (inp !! 1)

--231A

--split :: Char -> String -> [String]
--split _ [] = [""]
--split c (x:xs) | x == c = "" : rest
--               | otherwise = (x : head rest): tail rest
--                where rest = split c xs
--
--isGood :: [Int] -> Int
--isGood (a:b:c:[]) = if (a+b+c >= 2) then 1 else 0
--
--toIntList :: [[String]] -> [[Int]]
--toIntList strs = map (map read) strs
--
--main = getLine >>= \line -> sequence (replicate (read line) getLine) >>= \list -> putStrLn $ show $ sum $ map isGood (toIntList (map (split ' ') list))

--B158
--split :: Char -> String -> [String]
--split _ [] = [""]
--split c (x:xs) | x == c = "" : rest
--               | otherwise = (x : head rest): tail rest
--                where rest = split c xs
--
--countEntries :: [Int] -> Int -> Int
--countEntries [] _ = 0
--countEntries (x:xs) val | x == val = 1 + rest
--                        | otherwise = rest
--                            where rest = (countEntries xs val)
--
--findSol :: [Int] -> Int
--findSol groups = let
--                    gr = countEntries groups
--                    fours = gr 4
--                    threes = gr 3
--                    twos = gr 2
--                    ones = gr 1
--                    threeToOne = min threes ones
--                    twosToTwos = twos `div` 2
--                    unpairThrees = threes - threeToOne
--                    unpairOnes = ones - threeToOne + ((twos  `mod` 2)*2)
--                in
--                    fours + threeToOne + twosToTwos + ((unpairOnes `div` 4) + (if unpairOnes `mod` 4 /= 0 then 1 else 0)) + unpairThrees
--
--
--
--main = getLine >> getLine >>= \a -> let groups = (map  read  (split ' ' a) :: [Int]) in putStrLn $ show $ findSol groups

--A282
--parse :: String -> Int
--parse "X++" = 1
--parse "++X" = 1
--parse "--X" = -1
--parse "X--" = -1
--
--main = getLine >>=
--    \amount -> sequence (replicate (read amount) getLine) >>=
--    \sentenses -> putStrLn $ show $ sum (map parse sentenses)

--A116

data Stop = Stop {out:: Int, inp::Int} deriving Show

split :: Char -> String -> [String]
split _ [] = [""]
split c (x:xs) | x == c = "" : rest
               | otherwise = (x : head rest): tail rest
                where rest = split c xs

readStop :: String -> Stop
readStop str = let vals = map read (split ' ' str) :: [Int] in Stop (vals!!0) (vals!!1)

main = getLine >>=
    \ stopsAmount -> sequence (replicate (read stopsAmount) getLine) >>=
    \ stopsStr ->
        let
            stops = map readStop stopsStr
            people = \i -> if i == 0 then inp (stops!!i) else (inp (stops!!i)) - (out (stops!!i)) + (people (i-1))
            minCapacity = \i min -> if i >= length stops then min else (if min < people i then minCapacity (i+1) (people i) else minCapacity (i+1) min)
        in
            putStrLn $ show (minCapacity 0 0)

tram [] cur m = m
tram ((a,b):xs) cur m = tram xs c' (max m c')
  where c' = cur-a+b

main = do
  d <- getContents
  let (n:ls) = lines d
  let xs = map (\[a,b] -> (a,b)) $  map (map read . words) ls
  print $ tram xs 0 0

main = interact $ show . maximum . scanl (+) 0 . map ((\[x,y] -> y - x) . map read.words) . tail . lines

import Control.Monad

main = do
    n <- fmap read getLine
    a <- replicateM n $ fmap (foldl1 subtract . map read . words) getLine
    print $ maximum $ scanl1 (+) a

module Main (main)
    where

import Control.Monad (replicateM)

main :: IO ()
main = print . capacity . map readLine =<< flip replicateM getLine =<< readLn
    where capacity = maximum . scanl (\c [a,b] -> c - a + b) 0
          readLine = map read . words

main = do
    getLine
    interact (solve.(map (map read)).(map words).lines)
solve x = show(result 0 0 x)
result max acc ([x,y]:xs)
    |acc>max        = result acc acc ([x,y]:xs)
    |xs/=[]         = result max (acc-x+y) xs
    |otherwise      = max

module Main where

import Control.Monad

main = do
    n <- liftM read getLine
    (_, res) <- foldM (\(curr, need) _ -> do
            [a, b] <- liftM (map read . words) getLine
            let curr' = curr - a + b
                need' = max need curr'
            return (curr', need')
        ) (0, 0) [1..n]

    putStrLn $ show res

module Main where

process :: Int -> Int -> Int -> IO Int
process 0 cap max = return max
process n cap max = do
  s <- getLine
  let [x,y] = words s
  let outT = read x :: Int
  let inT  = read y :: Int
  let cap'  = (cap - outT) + inT
  if (cap' > max)
   then
       process (n - 1) cap' cap'
   else
       process (n - 1) cap' max

main :: IO ()
main = do
  s <- getLine
  let n = read s :: Int
  res <- process n 0 0
  print res

main = do
	dat <- getContents
	let allLines = tail $ lines dat
	putStrLn $ show $ answer $ parse $ (map words allLines)

answer xs = foldl1 (max) $ scanl (\acc x -> acc - (head x) + (last x)) 0 xs

parse :: [[String]] -> [[Integer]]
parse =  map (map ((+ 0) . read))

main = do
	n<-getLine
	reading (read n) []

reading 0 acc = putStrLn $ show $ solve 0 0 $ map (map read) (map words $ acc)
reading n acc = do
	t<-getLine
	reading (n-1) (acc++[t])

solve::Int->Int->[[Int]]->Int
solve m n [] = m
solve m n (k:ks) = solve (max m n1) n1 ks
             where n1=n-head k + last k

--stringToInts :: String -> [Int]
--stringToInts str =
--	map readInt (words str)
--	where readInt = read :: String -> Integer
stringToInts :: String -> IO [Integer]
stringToInts str =
	return $ map readInt (words str)
	where readInt = read :: String -> Integer
	--where readInt = read :: String -> Integer

invoke :: Integer -> Integer -> IO Integer
invoke n cur =
	if n == 0 then return $ cur
	else do
		next_line <- getLine
		lst <- stringToInts next_line
		--let new_cur = cur - (lst !! 0) + (lst !! 1) in
		invoke_result <- invoke (n - 1) (cur - (lst !! 0) + (lst !! 1))
		return $ max cur invoke_result

main = do
	--print $ max 4 5
	--tmp <- stringToInts "123 456"
	--print $ tmp
	n <- getLine
	result <- invoke (read n :: Integer) 0
	print $ result

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

main = do
	let lns = fmap C.lines $ C.hGetContents stdin
	input <- fmap (map (map (fst . fromJust . C.readInt)) . map C.words) $ lns
	let n = (head . head) input
	let ls = (take n . tail) input
	(putStrLn . show . fst . foldl (\(m,c) y -> (max m (c+y), c+y)) (0,0)) $ map (\[x,y] -> y - x) ls

{-# OPTIONS -O2 #-}
import Data.Char

main = do
  s <- getContents
  let
    nums = map read $ words s :: [Int]
    n =  head nums
    (as, bs) = gather $ tail nums
  print $ solve as bs 0 0

solve :: [Int] -> [Int] -> Int -> Int -> Int
solve [] [] _ n = n
solve (a:as) (b:bs) n m = solve as bs (n-a+b) (max m (n-a+b))

gather [] = ([], [])
gather (a:b:l) = (a:x, b:y)
  where
    (x, y) = gather l

import Control.Monad

-- Snippet: readItems
readItems = do
    line <- getLine
    return $ map read $ words line

main = do
    n <- readLn
    a <- replicateM n $ (readItems :: IO [Int])
    putStrLn $ show $ maximum (scanl process 0 a)
    where process people [exit, enter] = people - exit + enter

import Data.List
main = interact $ show . maximum . scanl1 (+) . map (\ [a, b] -> b - a) . map (map read . words) . tail . lines

solve :: Num a => [a] -> a -> [a]
solve (a:b:xs) cur = cur : solve xs (cur - a + b)
solve _ _ = []

main :: IO ()
main = do
	cs <- getContents
	let ints = map read $ tail $ words cs :: [Int]
	print $ maximum $ solve ints 0

import Control.Monad (replicateM)

readNLines :: Int -> IO [String]
readNLines n = replicateM n getLine

parseLine :: String -> (Int, Int)
parseLine line = (read (w!!0) :: Int, read (w!!1) :: Int) where w = words line

solution :: Int -> [(Int, Int)] -> [Int]
solution p [] = [0]
solution p [(a, b)] = [p - a + b]
solution p (x:xs) = k ++ solution (head k) xs where k = solution p [x]

main :: IO ()
main = do
    n <- readLn :: IO Int
    args <- readNLines n
    print $ maximum $ solution 0 $ map parseLine args

main = do
  getLine
  ps <- fmap (map ((\[a, b] -> (a, b)) . map read . words) . lines) getContents

  let
    (as, bs) = unzip ps
    s1 = scanl1 (+) as
    s2 = scanl1 (+) bs
    z = zipWith (-) s2 s1
    m = maximum z

  print m

main = interact $ show.maximum.scanl1 (+).map (negate.foldl1 (-).map read.words).tail.lines

import Data.List
main = interact $ gao.transpose.tail.map (map read.words).lines
gao [x,y] = show.maximum.scanl1 (+).zipWith (-) y $ x

import Control.Monad

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    lines <- fmap (map $ map read . words) (replicateM n getLine) :: IO [[Int]]
    print $ maxCapacity lines 0

maxCapacity :: [[Int]] -> Int -> Int
maxCapacity [] acum = acum
maxCapacity (x:xs) acum = max acum $ maxCapacity xs $ acum - (x !! 0) + (x !! 1)

import Control.Monad
solve :: [[Int]] -> [Int]
solve [] = [0]
solve (x : xs) = (head x) - (last x) + (head $ solve xs)  : solve xs
main = do
    n <- readLn
    l <- replicateM n getLine
    print . maximum $ solve (map (map read . words) $ l)

main = interact $ show . maximum . scanl1 (+) . map ((\[x, y] -> y - x) . map read . words) . tail . lines

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

main = interact process

process contents = let
  ls = contents |> lines |> map words |> map (map read) :: [[Int]]
  in solve (tail ls) |> show

solve station = solve' 0 0 station

solve' maxSoFar current [] = maxSoFar
solve' maxSoFar current (x:xs) = let
  new = current - (x !! 0) + (x !! 1)
  newMax = maxSoFar `max` new
  in solve' newMax new xs

getInput    :: String -> [String]
getInput xs = tail $ lines xs

toInt    :: String -> [Int]
toInt xs = [read x :: Int | x <- words xs]

minCap    :: [String] -> [Int]
minCap [] = []
minCap (x:xs) = (lxs - hxs) : minCap xs
    where pairs = toInt x
          hxs = head pairs
          lxs = last pairs

tram     :: [Int] -> [Int]
tram [x] = [x]
tram []     = []
tram (x:y:xs) = x : tram accumxs
    where accumxs = (x + y) : xs

main :: IO ()
main = do n <- getContents
          putStr $ show $ maximum $ tram $ minCap $ getInput n

solve = maximum . scanl (\acc (a,b) -> acc-a+b) 0

main = do
	v <- getContents
	print . solve . map (\[a,b] -> (a,b)) . map (map read) . map words . tail $ lines v

import Control.Monad
import Control.Applicative

main = do
  n <- readLn
  s <- replicateM n $ map read . words <$> getLine
  print $ maximum (solve s 0)

solve [] _ = []
solve (x:xs) num = num: solve xs (num+(last x)-(head x))

import Data.Char
import Data.List

capacity :: [Int] -> Int -> Int
capacity [] _ = 0
capacity (a:b:xs) c = max c (capacity xs (c + b - a))

solve :: [Int] -> Int
solve lst = capacity lst 0

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

import Control.Monad

main = do
    n <- readLn
    sflow <- replicateM n getLine
    let flow = map (map (read :: String -> Integer) . words) sflow
    let cap = snd $ solve flow
    putStrLn $ show cap

solve flow = foldl (\(cur, cmax) [gout, gin] ->
                     (cur + gin - gout, max cmax (cur + gin - gout))
                   ) (0, 0) flow

solve :: [Int] -> Int
solve x = foldr max 0 $ solve' x 0
    where solve'       [] _ = []
          solve' (x:y:xs) m = let mm = m - x + y
                              in mm : solve' xs mm

main :: IO()
main = do cs <- getContents
          let lst = map read $ words cs :: [Int]
          print $ solve $ tail lst

main = readsolveprint
readsolveprint::IO()
readsolveprint =  getLine >>= \x-> interact $ show . solve. map  (map read. words).  take (read x) . lines
solve :: [[Int]]->Int
solve xs = maximum $ scanl (+) 0 $ [last x - head x| x <- xs]

-- 116A
tram :: [[Int]] -> Int
tram xs = maximum (scanl (+) 0 (map weirdSum xs))
    where weirdSum xs = last xs - head xs

readIn :: IO [[Int]]
readIn = do
    contents <- getContents
    let n:ls = lines contents
        x = read $ head $ words n
        xs = take x $ map ((map read) . words) ls
    return xs

main :: IO()
main = do
    i <- readIn
    putStrLn $ show (tram i)

import Control.Monad
import Data.List

int x = read x ::Int

minCapacity = maximum . scanl (+) 0  . (uncurry $ flip $ zipWith (-)) . unzip

main = do
   n <- liftM int getLine
   vs <- liftM (map ((\[x,y] -> (x,y)) . map int. words)) $ replicateM n getLine
   print $ minCapacity vs

solve :: [(Int, Int)] -> Int
solve = snd.(foldl (\(cur, m) (a,b)-> let c = cur - a + b in (c, max c m)) (0,0))

main = do
    l <- getContents
    print $ solve . map (\(a:b:[]) -> (a,b)) $ map (map (read::String->Int).words). tail $ lines l

myReadLine :: IO (Int, Int)
myReadLine = do
    line <- getLine
    let [a, b] = map read (words line)
    return (a, b)

solve :: ([Int], [Int]) -> Int
solve (a, b) = maximum (scanl (+) 0 (zipWith (-) b a))

main = do
    n <- readLn::(IO Int)
    pair <- sequence (map (\x -> myReadLine) [1..n])
    print (solve (unzip pair))

-- Codeforces 116A

import Control.Monad

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    replicateM n getLine >>= putStrLn . show . solve . map (map read . words) where
        solve = fst . foldl (\(m, acc) n -> ((max m (acc+n)), acc+n)) (0, 0) . map (\x -> x!!1 - x!!0)

main = interact $ show . f 0 0 . map read . tail . words
f a b [] = b
f a b (c:d:e) = f (a-c+d) (max b (a-c+d)) e

module Main where

import Data.Complex
import Data.Char
import Data.List
import Data.Functor
import Control.Monad

type R = Double
type Z = Int
type B = Integer
type Q = Rational
type C = Complex

type A = Char
type S = String

readR = map read <$> words <$> getLine :: IO [R]
readR1 = head <$> readR

readZ = map read <$> words <$> getLine :: IO [Z]
readZ1 = head <$> readZ

readB = map read <$> words <$> getLine :: IO [B]
readB1 = head <$> readB

main :: IO ()
main = do
    n <- readZ1
    xs <- replicateM n readZ
    let ys = scanl f 0 xs
    print $ maximum ys
    where
    f acc (a:b:_) = acc + (b - a)

import Control.Applicative
import Control.Monad
import Data.List (foldl')

main = do
  n <- read <$> getLine
  ls <- map (toTup . map read . words) <$> replicateM n getLine :: IO [(Int,Int)]
  print $ maximum . scanl (+) 0 . map (uncurry $ flip (-)) $ ls

toTup [x,y] = (x,y)

import Data.List
main = interact $ show.snd.foldl' f (0, 0).map (map read.words).tail.lines
  where f (c, mx) [a, b] = let c' = c - a + b
                           in (c', max mx c')

main = do
	n <- getInt
	flux <- sequence $ map (\i -> getIntArray) [2..n]
	let res = snd $ foldl (\acc e -> do
						let curr = fst acc - e !! 0 + e !! 1
						let top = max curr (snd acc)
						(curr, top)) (0, 0) flux
	putStrLn $ show res

getInt::IO Int
getInt = do
	int <- getLine
	return . read $ int

getIntArray::IO [Int]
getIntArray = do
	arr <- getLine
	return $ map readInt $ split arr ' '

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

split::String -> Char -> [String]
split str sep = foldr (\curr acc -> if curr == sep
										then "":acc
										else (curr:(head acc)):(tail acc)) [""] str

main :: IO ()
main =
  interact $ show . maximum . f . (map ((\x -> x !! 1 - x !! 0) . (map read) . words)) . tail . lines

f :: Num a => [a] -> [a]
f [] = []
f (x:xs) = x : (map (+x) $ f xs)

-- Tram
import Data.List.Split

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

getInts :: IO [Int]
getInts = do
  input <- getLine
  return $ map toInt $ splitOn " " input

{-%
 solve :: Int -> [[Int]] -> Int
 solve ans [] = ans
 solve ans ((o:i:[]):xs) = max ans next
   where cur = ans - o + i
         next = max cur $ solve cur xs
-}

main = do
  ints <- getInts
  let [n] = ints
  ints <- sequence $ replicate n getInts
  let sums = map (\a -> foldl1 (-) $ reverse a) ints
  print (maximum $ scanl (+) 0 sums)

main=interact$(show.maximum.(\str -> scanl1 (+) $map (\[a,b] -> read b-read a) $ tail$(\x -> map words$lines x) str ))

solve :: Int -> [Int] -> Int
solve x [] = x
solve cur (a:b:xs) = max cur $ solve (cur - a + b) xs
main = interact $ show . solve 0. map read . tail . words

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

main::IO ()
main=do
    getLine
    a<-getContents
    let a1= map (\[a,b]-> b-a) $ map (map read) $ map words $ lines  a::[Int]
    print $ maximum $ scanl1 (+) a1

main = do
	number <- getLine
	let n = read number
	calc n 0 0

calc :: Int -> Int -> Int -> IO ()
calc 0 _ maks = print maks
calc i sum maks = do
	innn <- getLine
	let exitt = read $ takeWhile (/= ' ') innn
	let inn = read $ reverse $ takeWhile (/= ' ') $ reverse innn
	let nsum = inn + sum - exitt
	calc (i-1) nsum (max nsum maks)

module Main where

import Control.Arrow

import Data.Maybe
import Data.ByteString.Char8 (lines,words,interact,readInt,pack)
import Prelude   hiding      (lines,words,interact)
import Data.List hiding      (lines,words)

main = interact $ lines >>> tail >>>
  map (words >>> map (readInt >>> fromJust >>> fst) >>> foldl1' (-) >>> negate) >>>
  scanl1 (+) >>> maximum >>>
  show >>> pack

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

solve :: [[Int]] -> Int
solve = maximum . scanl (+) 0 . map (\[a, b] -> b - a)

import Prelude hiding (readList)
import Control.Monad

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

readList' :: Read a => a -> IO [a]
readList' _ = readList

showList :: Show a => [a] -> IO ()
showList = putStrLn . unwords . map show

skipLine :: IO ()
skipLine = void $ getLine

count :: (a -> Bool) -> [a] -> Int
count f = length . filter f

divUp :: Integral a => a -> a -> a
divUp x y
  | x `mod` y /= 0 = x `div` y + 1
  | otherwise      = x `div` y

interp :: Int -> [Int] -> Int
interp x [a,b] = x-a+b

main :: IO ()
main = do
  [n] <- readList' (undefined::Int)
  abs <- replicateM n $ readList' (undefined::Int)
  print $ maximum $ scanl interp 0 abs

station :: Int -> [String] -> Int
station n [] = n
station n (x:xs) = max (station (n - a + b) xs) n
  where a = nums !! 0
        b = nums !! 1
        nums = map read . words $ x

main = do
  getLine
  interact $ show . station 0 . lines

getList :: [Int] -> [(Int,Int)]
getList [] = []
getList (v1:v2:vs) = [(v1,v2)] ++ getList vs

main = do
  str <- getContents
  let
    n:values = map read $ words str
    res = foldl (\x (down,up) -> max x (x-down+up)) 0 $ getList values
  putStrLn $ show res
  putStrLn $ show $ getList values

getList :: [Int] -> [(Int,Int)]
getList [] = []
getList (v1:v2:vs) = [(v1,v2)] ++ getList vs

main = do
  str <- getContents
  let
    n:values = map read $ words str
    res = foldl (\x (down,up) -> max x (x-down+up)) 0 $ getList values
  putStrLn $ show res

import Control.Monad
import Data.List

main = getLine >>=
       (flip replicateM $ getLine >>= return.map read.words).read >>=
       putStrLn.show.solve

solve :: [[Int]] -> Int
solve input = maximum.diffs $ ticks input

ticks :: [[Int]] -> [Int]
ticks input = map (\[a, b] -> b - a) input

diffs [] = [0]
diffs (a:[]) = [a]
diffs (a:as:al) = (a + as):diffs (as:al)

import Control.Monad
import Data.List

main = getLine >>=
       (flip replicateM $ getLine >>= return.map read.words).read >>=
       putStrLn.show.solve.reverse

solve :: [[Int]] -> Int
solve input = maximum.diffs $ ticks input

ticks :: [[Int]] -> [Int]
ticks input = map (\[a, b] -> a - b) input

diffs :: [Int] -> [Int]
diffs [a] = [a]
diffs (a:as) = (sum (a:as)):(diffs as)

import Data.Char
import Data.List

ans a = maximum $ scanl (\x y->x-head y+last y) 0 a

main = do
    n<-getLine
    a<-getContents
    let input = map  (map (\x->read x::Int)) (map words $ lines a)
    print input

main = do
	dat <- getContents
	let allLines = tail $ lines dat
	putStrLn $ show $ answer $ parse $ (map words allLines)

answer xs = foldl (\acc x -> max acc (acc - (head x) + (last x))) 0 xs

parse :: [[String]] -> [[Integer]]
parse =  map (map ((+ 0) . read))

main = do
	n<-getLine
	reading (read n) []

reading 0 acc = putStrLn $ show $ solve 0 $ map (map read) (map words $ acc)
reading n acc = do
	t<-getLine
	reading (n-1) (acc++[t])

solve::Int->[[Int]]->Int
solve m [] = m
solve m (k:ks) = solve (max m (m-head k + last k)) ks

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

main = do
	let lns = fmap C.lines $ C.hGetContents stdin
	input <- fmap (map (map (fst . fromJust . C.readInt)) . map C.words) $ lns
	let n = (head . head) input
	let ls = (take n . tail) input
	(putStrLn . show . foldl (\x y -> max x $ (x+y)) 0) $ map (\[x,y] -> y - x) ls

{-# OPTIONS -O2 #-}
import Data.Char

main = do
  s <- getContents
  let
    nums = map read $ words s :: [Int]
    n =  head nums
    (as, bs) = gather $ tail nums
  print $ solve as bs 0

solve [] [] n = n
solve (a:as) (b:bs) n = solve as bs (max n (n-a+b))

gather [] = ([], [])
gather (a:b:l) = (a:x, b:y)
  where
    (x, y) = gather l

{-# OPTIONS -O2 #-}
import Data.Char

main = do
  s <- getContents
  let
    nums = map read $ words s :: [Int]
    n =  head nums
    (as, bs) = gather $ tail nums
  print $ solve as bs 0

solve :: [Int] -> [Int] -> Int -> Int
solve [] [] n = n
solve (a:as) (b:bs) n = solve as bs (max n (n-a+b))

gather [] = ([], [])
gather (a:b:l) = (a:x, b:y)
  where
    (x, y) = gather l

getInput    :: String -> [String]
getInput xs = tail $ lines xs

toInt    :: String -> [Int]
toInt xs = [read x :: Int | x <- words xs]

minCap    :: [String] -> [Int]
minCap [] = []
minCap (x:xs) = (lxs - hxs) : minCap xs
    where pairs = toInt x
          hxs = head pairs
          lxs = last pairs

tram     :: [Int] -> [Int]
tram [x] = [x]
tram []     = []
tram (x:y:xs) = x : tram accumxs
    where accumxs = (x + y) : xs

main :: IO ()
main = do n <- getContents
          putStr $ show $ maximum $ minCap $ getInput n

import Control.Monad

main = do
    n <- readLn
    sflow <- replicateM n getLine
    let flow = map (map (read :: String -> Integer) . words) sflow
    {-putStrLn $ show flow-}

    let res = solve flow

    if (fst res /= 0) then error "wtf??"
                      else putStrLn $ show $ snd res

solve flow = foldl (\(cur, cmax) [gout, gin] ->
                     (cur + gin - gout, max cmax (cmax + gin - gout))
                   ) (0, 0) flow

import Control.Monad

main = do
    n <- readLn
    sflow <- replicateM n getLine
    let flow = map (map (read :: String -> Integer) . words) sflow
    {-putStrLn $ show flow-}

    let cap = snd $ solve flow

    putStrLn $ show cap

solve flow = foldl (\(cur, cmax) [gout, gin] ->
                     (cur + gin - gout, max cmax (cmax + gin - gout))
                   ) (0, 0) flow

-- Codeforces 116A

import Control.Monad

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    replicateM n getLine >>= putStrLn . show . solve . map (map read . words) where
        solve = foldl (\a b -> max a (a+b)) 0 . map (\x -> x!!1 - x!!0)

import Control.Applicative
import Control.Monad
import Data.List (foldl')

main = do
  n <- read <$> getLine
  ls <- map (map read . words) <$> replicateM n getLine :: IO [[Int]]
  print $ foldl' (\cc [o,i] -> let cr = cc-o in max cc (cr+i)) 0 ls

main = do
	n <- getInt
	flux <- sequence $ map (\i -> getIntArray) [2..n]
	let res = foldl (\acc curr -> max (acc - curr !! 0 + curr !! 1) acc) 0 flux
	putStrLn $ show res

getInt::IO Int
getInt = do
	int <- getLine
	return . read $ int

getIntArray::IO [Int]
getIntArray = do
	arr <- getLine
	return $ map readInt $ split arr ' '

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

split::String -> Char -> [String]
split str sep = foldr (\curr acc -> if curr == sep
										then "":acc
										else (curr:(head acc)):(tail acc)) [""] str

main=interact$(show.last.(\str -> scanl1 (\acc x -> if x + acc > acc then x+acc else acc )$map (\[a,b] -> read b-read a)$tail$(\x -> map words$lines x) str))

main = do
	number <- getLine
	let n = read number
	calc n 0 0

calc :: Int -> Int -> Int -> IO ()
calc 0 _ maks = print maks
calc i sum maks = do
	innn <- getLine
	let exitt = read $ takeWhile (/= ' ') innn
	let inn = read $ takeWhile (/= ' ') $ reverse innn
	let nsum = inn + sum - exitt
	calc (i-1) nsum (max nsum maks)

main = do
	number <- getLine
	let n = read number
	calc n 0 0

calc :: Int -> Int -> Int -> IO ()
calc 0 _ maks = print maks
calc i sum maks = do
	innn <- getLine
	let exitt = read $ [head innn]
	let inn = read $ [last innn]
	let nsum = inn + sum - exitt
	calc (i-1) nsum (max nsum maks)


import Control.Monad
import Data.List (sort, groupBy)
import Data.Function (on)
import Data.Int (Int64)

main = do
    t <- read <$> getLine
    replicateM_ t $ do
        n <- read <$> getLine
        a <- map read . words <$> getLine :: IO [Int]
        let b = groupBy ((==) `on` fst) $ sort $ zip a [0..n-1]
        print $ sum $ map (calc 0 n . map snd) b

calc :: Int64 -> Int -> [Int] -> Int64
calc s n [] = 0
calc s n (x:xs) = s * fromIntegral (n - x) + calc (s + fromIntegral x + 1) n xs

import Control.Monad
import Data.Maybe
import Data.Word
import Data.List
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder
import System.IO
import qualified Data.IntMap.Strict as IM

parseInt :: C.ByteString -> Int
parseInt = fst . fromJust . C.readInt

getInts :: IO [Int]
getInts = map parseInt . C.words <$> C.getLine

main :: IO ()
main = do
  [t] <- getInts
  result <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    as <- getInts
    let (result, _) = foldl' acc (0 :: Word64, IM.empty) $ zip [1..] as
        acc (total, mp) (i, a) = (total', mp')
          where total' = total + IM.findWithDefault 0 a mp * (fromIntegral n - i + 1)
                update Nothing = Just i
                update (Just x) = Just (x + i)
                mp' = IM.alter update a mp
    return $ word64Dec result `mappend` charUtf8 '\n'
  hPutBuilder stdout result


import Control.Applicative
import Data.List
import Data.Int

main :: IO()
main = print. solve'.newlist .tail. map read.words =<< getContents

newlist (x:[]) = []
newlist (x:y:xs) = (abs (x-y)):newlist (y:xs)

solve' (x:xs) = max (solve '-' x x xs) (solve '+' 0 0 xs)

solve :: Char -> Int64 -> Int64 -> [Int64] -> Int64
solve _ _ m [] = m
solve '+' t m (x:[]) = max m (t+x)
solve '-' t m (x:[]) = m
solve '-' t m (y:xs) = if (t-y<=0) then solve '+' 0 m xs else solve '+' (t-y) m xs
solve '+' t m (y:xs) = solve '-' (t+y) (m `max` (t+y)) xs

pp = putStrLn

-- params: sequence, max sum, curr sum, iterator
kadane (a : b : cc) mx curr itr left
  | (0 > next) = kadane (b : cc) (maximum [mx,next]) (maximum [next,0]) (succ itr) (succ itr)
  | otherwise = kadane (b : cc) (maximum [mx,next]) (maximum [next,0]) (succ itr) left
  where next = curr + ((abs (a - b)) * ((-1) ^ (itr - left)))
kadane (b : cc) m c i l = m
--  kadane (b : cc) (maximum [mx, next]) (maximum [next, 0]) (succ itr)

-- fold right
conv ( x : xs ) = ((read x) :: Integer) : conv xs
conv mpt = []

main = do
  ff <- getLine
  let n = (read ff) :: Integer

  gg <- getLine
  let ww = conv (words gg)

  let ans = kadane ww 0 0 1 1
--  pp (show ans)
  let ban = kadane (tail ww) 0 0 2 2
--  pp (show ban)

  pp (show (maximum [ans, ban]))

pp = putStrLn

-- params: sequence, max sum, curr sum, iterator
kadane (a : b : cc) mx curr itr left
  | (0 > next) = kadane (b : cc) (maximum [mx,next]) (maximum [next,0]) (succ itr) (succ itr)
  | otherwise = kadane (b : cc) (maximum [mx,next]) (maximum [next,0]) (succ itr) left
  where next = curr + ((abs (a - b)) * ((-1) ^ (itr - left)))
kadane (b : cc) m c i l = m
--  kadane (b : cc) (maximum [mx, next]) (maximum [next, 0]) (succ itr)

-- fold right
conv ( x : xs ) = ((read x) :: Int) : conv xs
conv mpt = []

main = do
  ff <- getLine
  let n = (read ff) :: Int

  gg <- getLine
  let ww = conv (words gg)

  let ans = kadane ww 0 0 1 1
--  pp (show ans)
  let ban = kadane (tail ww) 0 0 2 2
--  pp (show ban)

  pp (show (maximum [ans, ban]))

pp = putStrLn

-- params: sequence, max sum, curr sum, iterator
kadane (a : b : cc) mx curr itr =
  kadane (b : cc) (maximum [mx, next]) (maximum [next, 0]) (succ itr)
  where next = curr + ((abs (a - b)) * ((-1) ^ (itr)))
kadane (b : cc) m c i = m

-- fold right
conv ( x : xs ) = ((read x) :: Int) : conv xs
conv mpt = []

main = do
  ff <- getLine
  let n = (read ff) :: Int

  gg <- getLine
  let ww = conv (words gg)

  let ans = kadane ww 0 0 0
  pp (show ans)

import Control.Applicative
import Data.List
import Data.Int

main :: IO()
main = print. solve'.newlist .tail. map read.words =<< getContents

newlist (x:[]) = []
newlist (x:y:xs) = (abs (x-y)):newlist (y:xs)

solve' (x:xs) = solve '-' x x xs

solve :: Char -> Int64 -> Int64 -> [Int64] -> Int64
solve _ _ m [] = m
solve '+' t m (x:[]) = max m (t+x)
solve '-' t m (x:[]) = m
solve '+' t m (y:xs) = solve '-' (t+y) (m `max` (t+y)) xs
solve '-' t m (y:xs) = if (t-y<=0) then solve '-' y (m `max` y) xs else solve '+' (t-y) m xs


import Data.Graph
import Control.Monad
import Data.Tuple
import System.IO

newtype Query = Query {getQuery :: String}
newtype Answer = Answer {getAnswer :: String}

data Case = TwoPlus | None | OneOnly | One

toTree :: Int ->  [[Int]] -> Tree Int
toTree n ps =head $ dfs gr [1]
  where
    tups = map (\[a,b] -> (a,b)) ps
    gr = buildG (1,n) (tups++map swap tups)

start :: IO (Tree Int)
start = do
  n <- readLn
  xs <- replicateM (n-1) $ (map read.words) <$> getLine
  return $ toTree n xs

process :: Tree Int -> (Either Query Answer,Case)
process (Node a []) = (Right $ Answer $ "! "++show a,None)

process (Node a [Node b []]) = (Left $ Query $ "? " ++ show a ++ " " ++ show b,OneOnly)

process (Node a [Node _ (Node c _:_)]) = (Left $ Query $ "? " ++ show a ++ " " ++ show c,One)

process (Node _ (Node c1 _:Node c2 _:_)) = (Left $ Query $ "? " ++ show c1 ++ " " ++ show c2 ,TwoPlus)

newTree :: Case -> Int -> Tree Int -> Tree Int
newTree None _ _= undefined

newTree OneOnly n _= Node n []

newTree One n (Node a [Node b (Node c cs:bs)])
  | n == a = Node n []
  | n == b = Node b bs
  | n == c = Node c cs
  | otherwise = undefined
newTree TwoPlus n (Node a (Node b bs:Node c cs:as))
  | n == a = Node a as
  | n == b = Node b bs
  | n == c = Node c cs
  | otherwise = undefined

doQuery :: Query -> IO Int
doQuery (Query str) = do
  putStrLn str
  hFlush stdout
  readLn

doAnswer :: Answer -> IO ()
doAnswer (Answer str) = do
  putStrLn str
  hClose stdout

solve :: Tree Int -> IO ()
solve tr =
  case ei of
    Left q ->
      do
        n <- doQuery q
        solve $ newTree c n tr
    Right a ->
      doAnswer a
    where
      (ei,c) = process tr

main :: IO ()
main = do
  tr <- start
  solve tr

{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
import System.IO
import Data.Ord
import Data.Int
import Data.Char
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Text.Read (readEither)

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

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

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

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

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

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

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

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

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

get :: IOInteract a => EIO a
get = ExceptT $ liftM convertEither getToken
put :: IOInteract a => a -> EIO ()
put = lift . (hPutStr stdout) . toShow
putln :: IOInteract a => a -> EIO ()
putln = lift . (hPutStrLn stdout) . toShow
flush :: EIO ()
flush = lift $ hFlush stdout

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

main_ :: EIO ()
-- template --
main_ = do
    n <- get :: EIO Int
    e <- replicateM (n - 1) $ liftM2 (,) get get :: EIO [(Int, Int)]
    f1 (buildTree n e)

buildTree :: Int -> [(Int, Int)] -> Map Int (Set Int)
buildTree n es = let m = foldl (\m i ->
                                Map.insert i Set.empty m ) Map.empty [1..n] in
                 foldl (\m (i, j) ->
                     Map.adjust (Set.insert i) j $ Map.adjust (Set.insert j) i m ) m es

f1 :: Map Int (Set Int) -> EIO ()
f1 d = if Map.size d == 1 then
        case Map.keys d of
            i : _ -> (putln $ "! " ++ show i) >>= (const flush)
            _ -> undefined
       else let (x, y) = getV d in do
           putln $ "? " ++ show x ++ " " ++ show y
           flush
           v <- get
           if v == x || v == y then
               (putln $ "! " ++ show v) >>= (const flush)
            else
                f1 $ removeV y $ removeV x d

getV :: Map Int (Set Int) -> (Int, Int)
getV d = case Map.keys $ Map.filter (\s -> Set.size s == 1) d of
            x : y : _ -> (x, y)
            _ -> undefined

removeV :: Int -> Map Int (Set Int) -> Map Int (Set Int)
removeV i d = case fmap Set.toList $ Map.lookup i d of
                Just (a : _ ) -> Map.adjust (Set.delete i) a $ Map.delete i d
                _ -> undefined