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.

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

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

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 = interact $ show.maximum.f.map (map read.words).tail.lines

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

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)


The weight of a sequence is defined as the number of unordered pairs of indexes $$$(i,j)$$$ (here $$$i \lt j$$$) with same value ($$$a_{i} = a_{j}$$$). For example, the weight of sequence $$$a = [1, 1, 2, 2, 1]$$$ is $$$4$$$. The set of unordered pairs of indexes with same value are $$$(1, 2)$$$, $$$(1, 5)$$$, $$$(2, 5)$$$, and $$$(3, 4)$$$.You are given a sequence $$$a$$$ of $$$n$$$ integers. Print the sum of the weight of all subsegments of $$$a$$$. A sequence $$$b$$$ is a subsegment of a sequence $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a single integer — the sum of the weight of all subsegments of $$$a$$$.

Note  In test case $$$1$$$, all possible subsegments of sequence $$$[1, 2, 1, 1]$$$ having size more than $$$1$$$ are:   $$$[1, 2]$$$ having $$$0$$$ valid unordered pairs;  $$$[2, 1]$$$ having $$$0$$$ valid unordered pairs;  $$$[1, 1]$$$ having $$$1$$$ valid unordered pair;  $$$[1, 2, 1]$$$ having $$$1$$$ valid unordered pairs;  $$$[2, 1, 1]$$$ having $$$1$$$ valid unordered pair;  $$$[1, 2, 1, 1]$$$ having $$$3$$$ valid unordered pairs.  Answer is $$$6$$$. In test case $$$2$$$, all elements of the sequence are distinct. So, there is no valid unordered pair with the same value for any subarray. Answer is $$$0$$$.

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


Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.

The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements.

Print the only integer — the maximum value of f.

NoteIn the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].In the second case maximal value of f is reachable only on the whole array.

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

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


One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first.  There are $$$n$$$ books standing in a row on the shelf, the $$$i$$$-th book has color $$$a_i$$$.You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.What is the minimum number of operations you need to make the shelf beautiful?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of books. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the book colors.

Output the minimum number of operations to make the shelf beautiful.

NoteIn the first example, we have the bookshelf $$$[1, 2, 2, 1, 3]$$$ and can, for example:   take a book on position $$$4$$$ and move to the right end: we'll get $$$[1, 2, 2, 3, 1]$$$;  take a book on position $$$1$$$ and move to the right end: we'll get $$$[2, 2, 3, 1, 1]$$$. In the second example, we can move the first book to the end of the bookshelf and get $$$[2,2,1,1,1]$$$.

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

import qualified Data.ByteString.Lazy.Char8 as P

import Data.Array.Unboxed

type SIO = StateT P.ByteString IO

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

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

solve :: Int -> [Int] -> Int
solve n a = let
  aArr :: UArray Int Int
  aArr = listArray (1, n) a
  leftMost :: UArray Int Int
  leftMost = accumArray min maxBound (1, n) $ zip a [1..]
  rightMost :: UArray Int Int
  rightMost = accumArray max minBound (1, n) $ zip a [1..]
  count :: UArray Int Int
  count = accumArray (+) 0 (1, n) $ zip a (repeat 1)

  -- Every value except for at most one can either be fully left in
  -- place or fully moved to the end.  This dp counts how many can be
  -- left in place up to a given index.
  fun :: Int -> Int
  fun 0 = 0
  fun i = let
    opt1 = memo ! (i - 1)
    ai = aArr ! i
    opt2 = if  i == rightMost ! ai
      then  count ! ai + memo ! (leftMost ! ai - 1)
      else  0
    in  max opt1 opt2
  memo :: Array Int Int
  memo = listArray (0, n) $ map fun [0..n]

  -- The remaining value is more interesting. It need not start at the
  -- end!  Consider a test case like [8,6,5,3,3,1,8,8,6].  The best
  -- strategy is to make 8 the last value, then move the two 6s.  This
  -- takes 3 operations. This code considers every possible value  i
  -- for the first unmoved index holding the partially moved value.
  locations :: Array Int [Int]
  locations = accumArray (flip (:)) [] (1, n) $ zip a [1..]
  options = do
    currValLocs <- elems locations
    (startPos, later) <- zip currValLocs [1..]
    pure $ memo ! (startPos - 1) + later
  in  n - maximum options

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [n] <- readInts
  a <- readInts
  lift . print $ solve n a

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

import qualified Data.ByteString.Lazy.Char8 as P

import Data.List
import Data.Array.Unboxed

type SIO = StateT P.ByteString IO

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

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

solve :: Int -> [Int] -> Int
solve n a = let
  aArr :: UArray Int Int
  aArr = listArray (1, n) a
  leftMost :: UArray Int Int
  leftMost = accumArray min maxBound (1, n) $ zip a [1..]
  rightMost :: UArray Int Int
  rightMost = accumArray max minBound (1, n) $ zip a [1..]
  count :: UArray Int Int
  count = accumArray (+) 0 (1, n) $ zip a (repeat 1)
  fun :: Int -> Int
  fun 0 = 0
  fun i = let
    opt1 = memo ! (i - 1)
    ai = aArr ! i
    opt2 = if  i == rightMost ! ai
      then  count ! ai + memo ! (leftMost ! ai - 1)
      else  0
    in  max opt1 opt2
  memo :: Array Int Int
  memo = listArray (0, n) $ map fun [0..n]
  lastVal = aArr ! n
  preLen = length $ dropWhileEnd (== lastVal) a
  in  preLen - memo ! preLen

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [n] <- readInts
  a <- readInts
  lift . print $ solve n a


This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?

NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:

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


Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string.More formally, you are given two strings s1, s2 of length n and number t. Let's denote as f(a, b) the number of characters in which strings a and b are different. Then your task will be to find any string s3 of length n, such that f(s1, s3) = f(s2, s3) = t. If there is no such string, print  - 1.

The first line contains two integers n and t (1 ≤ n ≤ 105, 0 ≤ t ≤ n). The second line contains string s1 of length n, consisting of lowercase English letters. The third line contain string s2 of length n, consisting of lowercase English letters.

Print a string of length n, differing from string s1 and from s2 in exactly t characters. Your string should consist only from lowercase English letters. If such string doesn't exist, print -1.

import Data.Maybe (fromMaybe)

solve [n, t, s1, s2] = solve' (read n) (read t) (zip s1 s2)

solve' :: Int -> Int -> [(Char, Char)] -> Maybe String
solve' _ t s12
  | d > 2*t = Nothing
  | d > t = Just $ go (d-t, d-t, 2*t-d, 0) s12
  | otherwise = Just $ go (0, 0, d, t-d) s12
  where d = length . filter (uncurry (/=)) $ s12
        go _ [] = []
        go (a, b, c, d) ((x, y) : zs)
          | a > 0 && x /= y = x : go (a-1, b, c, d) zs
          | b > 0 && x /= y = y : go (a, b-1, c, d) zs
          | c > 0 && x /= y = other x y : go (a, b, c-1, d) zs
          | d > 0 && x == y = next x : go (a, b, c, d-1) zs
          | otherwise = x : go (a, b, c, d) zs

other x y = head . filter (\c -> c /= x && c /= y) $ ['a' .. ]

next 'z' = 'a'
next c = succ c

main = interact $ fromMaybe "-1" . solve . words

import Control.Monad
import System.IO
import Data.Int
import Data.Char
import Data.Maybe
import Data.Ix
import Data.List
import GHC.Exts
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Data.Vector as Vector

readInt = read :: String -> Int
infixl 5 |>
a |> f = f a

infixl 5 ||>
m ||> f = liftM f m

readLines :: Int -> IO [String]
readLines 0 = return []
readLines n = do
	l1 <- getLine
	lns <- readLines (n - 1)
	return $ l1 : lns

toLong :: Int -> Int64
toLong = fromIntegral

other c1 c2 = find (\c -> c /= c1 && c /= c2) ['a' .. 'c'] |> fromMaybe undefined

get_ans [] _ _ _ _ = ""
get_ans (c1 : t1) (c2 : t2) mb ms1 ms2
	| c1 == c2 && mb > 0		= c1 : get_ans t1 t2 (mb - 1) ms1 ms2
	| c1 == c2					= (other c1 c2) : get_ans t1 t2 mb ms1 ms2
	| ms1 > 0 					= c1 : get_ans t1 t2 mb (ms1 - 1) ms2
	| ms2 > 0					= c2 : get_ans t1 t2 mb ms1 (ms2 - 1)
	| otherwise					= other c1 c2 : get_ans t1 t2 mb ms1 ms2

main = do
	n : should_differ : [] <- getLine ||> words ||> map readInt
	s1 <- getLine
	s2 <- getLine

	should_match <- return $ n - should_differ

	matching <- return $ zip s1 s2 |> filter (uncurry (==)) |> length

	should_match_in_both <- return $ find (\m -> m <= should_match && 2 * (should_match - m) <= (n - matching)) [0 .. matching]

	case should_match_in_both of
		Nothing -> putStrLn "-1"
		Just x  -> do
					res <- return $ get_ans s1 s2 x (should_match - x) (should_match - x)
					putStr $ res

--l1は対応するで同じにするもの l2はs2で違うのにする
answer l1 l2 [] [] = []
answer l1 l2 (a1:n1) (a2:n2) | a1 == a2 = if l2 == 0 then a1:(answer l1 l2 n1 n2) else (getDif a1 a2):(answer l1 (l2-1) n1 n2)
                             | otherwise = if l1 == 0 then (getDif a1 a2):(answer l1 l2 n1 n2) else if l1 `rem` 2 == 0 then a1:(answer (l1-1) l2 n1 n2) else a2:(answer (l1-1) l2 n1 n2)
getDif a b | b < a = getDif b a
           | a == b = if a == 'a' then 'b' else pred a
           | succ a == b = if a == 'a' then succ b else pred a
           | otherwise = succ a
main = do
  w0 <- getLine
  let [n,t] = [read n::Int|n<-(words w0)]
  s1 <- getLine
  s2 <- getLine
  let n0=length $ filter (\x ->(fst x)/=(snd x)) $ zip s1 s2
  let n1=n-n0
  let minN = if n0 `rem` 2 == 0 then n0 `div` 2 else (n0 + 1) `div` 2
  if t < minN
  then putStrLn "-1"
  else if t <= n0 then putStrLn $ answer (2*(n0-t)) 0 s1 s2 else putStrLn $ answer 0 (t-n0) s1 s2

import Control.Applicative
import Control.Monad
import Control.Applicative
import Control.Monad
import Control.Monad
import Data.List
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.IO
import Data.IORef

solve :: Int -> Int -> UArray Int Char -> UArray Int Char -> IO String
solve n need s1 s2 = do
    str <- newArray (0,n-1) 'a' :: IO (IOUArray Int Char)
    rest1 <- newIORef need
    rest2 <- newIORef need
    forM [0..n-1] $ \i -> do
        r <- readIORef rest1
        when (s1 ! i == s2 ! i) $ do
            if r > 0
                then do
                    writeArray str i (s1 ! i)
                    writeIORef rest1 (r-1)
                    writeIORef rest2 (r-1)
                else writeArray str i $ fromMaybe 'a' $ find (\x -> x /= s1 ! i && x /= s2 ! i) "abc"
    forM [0..n-1] $ \i -> do
        r1 <- readIORef rest1
        r2 <- readIORef rest2
        let x = s1 ! i
        let y = s2 ! i
        when (x /= y) $ do
            if r2 == 0
                then writeArray str i (fromMaybe 'a' $ find (\z -> z /= x && z /= y) "abc")
                else if r1 < r2
                    then do
                        writeArray str i y
                        writeIORef rest2 (r2-1)
                    else do
                        writeArray str i x
                        writeIORef rest1 (r1-1)
    readIORef rest2 >>= \x ->
        if x > 0
            then return "-1"
            else getElems str

main :: IO ()
main = do
    [n,t] <- map read . words <$> getLine
    s1 <- listArray (0,n-1) <$> getLine
    s2 <- listArray (0,n-1) <$> getLine
    putStrLn =<< solve n (n-t) s1 s2

import Data.Maybe (fromMaybe)

solve [n, t, s1, s2] = solve' (read n) (read t) (zip s1 s2)

solve' :: Int -> Int -> [(Char, Char)] -> Maybe String
solve' n t s12
  | d >= 2*t = Nothing
  | d > t = Just $ go (d-t, d-t, 2*t-d, 0) s12
  | otherwise = Just $ go (0, 0, d, t-d) s12
  where d = length . filter (uncurry (/=)) $ s12
        go _ [] = []
        go (a, b, c, d) ((x, y) : zs)
          | a > 0 && x /= y = x : go (a-1, b, c, d) zs
          | b > 0 && x /= y = y : go (a, b-1, c, d) zs
          | c > 0 && x /= y = other x y : go (a, b, c-1, d) zs
          | d > 0 && x == y = next x : go (a, b, c, d-1) zs
          | otherwise = x : go (a, b, c, d) zs

other x y = head . filter (\c -> c /= x && c /= y) $ ['a' .. ]

next 'z' = 'a'
next c = succ c

main = interact $ fromMaybe "-1" . solve . words

import Control.Applicative
import Control.Monad
import Control.Applicative
import Control.Monad
import Control.Monad
import Data.List
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.IO
import Data.IORef

solve :: Int -> Int -> UArray Int Char -> UArray Int Char -> IO String
solve n need s1 s2 = do
    str <- newArray (0,n-1) 'a' :: IO (IOUArray Int Char)
    rest1 <- newIORef need
    rest2 <- newIORef need
    forM [0..n-1] $ \i -> do
        r <- readIORef rest1
        when (s1 ! i == s2 ! i && r > 0) $ do
            writeArray str i (s1 ! i)
            writeIORef rest1 (r-1)
            writeIORef rest2 (r-1)
    forM [0..n-1] $ \i -> do
        r1 <- readIORef rest1
        r2 <- readIORef rest2
        let x = s1 ! i
        let y = s2 ! i
        when (x /= y) $ do
            if r2 == 0
                then writeArray str i (fromMaybe 'a' $ find (\z -> z /= x && z /= y) "abc")
                else if r1 < r2
                    then do
                        writeArray str i y
                        writeIORef rest2 (r2-1)
                    else do
                        writeArray str i x
                        writeIORef rest1 (r1-1)
    readIORef rest2 >>= \x ->
        if x > 0
            then return "-1"
            else getElems str

main :: IO ()
main = do
    [n,t] <- map read . words <$> getLine
    s1 <- listArray (0,n-1) <$> getLine
    s2 <- listArray (0,n-1) <$> getLine
    putStrLn =<< solve n (n-t) s1 s2

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

solve :: Int -> Int -> String -> String -> Int -> Maybe String
solve c1 c2 [] [] need
    | c1 == need && c2 == need = Just []
    | otherwise = Nothing
solve c1 c2 (x:xs) (y:ys) need
    | c1 == need && c2 == need = fmap ((fromMaybe 'a' $ find (\z -> z /= x && z /= y) ['a'..'z']) :) $ solve c1 c2 xs ys need
    | x == y = fmap (x :) $ solve (c1+1) (c2+1) xs ys need
    | c1 == c2 = fmap (x :) $ solve (c1+1) c2 xs ys need
    | c1 > c2 = fmap (y :) $ solve c1 (c2+1) xs ys need

main :: IO ()
main = do
    [n,t] <- map read . words <$> getLine
    s1 <- getLine
    s2 <- getLine
    case solve 0 0 s1 s2 (n-t) of
        Just xs -> putStrLn xs
        Nothing -> print (-1)

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

solve :: Int -> Int -> String -> String -> Int -> Maybe String
solve c1 c2 [] [] need
    | c1 == need && c2 == need = Just []
    | otherwise = Nothing
solve c1 c2 (x:xs) (y:ys) need
    | c2 == need || c1 == need && x == y = fmap ((fromMaybe 'a' $ find (\z -> z /= x && z /= y) ['a'..'z']) :) $ solve c1 c2 xs ys need
    | x == y = fmap (x :) $ solve (c1+1) (c2+1) xs ys need
    | c1 == c2 = fmap (x :) $ solve (c1+1) c2 xs ys need
    | c1 > c2 = fmap (y :) $ solve c1 (c2+1) xs ys need

main :: IO ()
main = do
    [n,t] <- map read . words <$> getLine
    s1 <- getLine
    s2 <- getLine
    case solve 0 0 s1 s2 (n-t) of
        Just xs -> putStrLn xs
        Nothing -> print (-1)


The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters:   R, G, B — denoting red, green and blue doors, respectively;  r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once.

For each testcase, print YES if the knight can open all doors. Otherwise, print NO.

NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door.

{-# LANGUAGE TypeApplications #-}

module Main where

import           Data.List
import           Data.Char
import           Data.Functor
import           Control.Monad
import           Data.Function
import           Control.Monad.State

data Answer = YES | NO deriving Show

pickUp :: String -> State [Char] Answer
pickUp [      ] = return YES
pickUp (c : cs) = do
  keys <- get
  if        isLower c
  then      put (c : keys) >> pickUp cs
  else if   toLower c `elem` keys
  then      put (delete c keys) >> pickUp cs
  else      return NO

main :: IO ()
main =
  getLine <&> read @Int
  >>=
  flip replicateM getLine
  >>=
  mapM_ (\s -> print $ evalState (pickUp s) [])

import Control.Monad.State (State, evalState, replicateM, state)
import Data.Bifunctor (first)
import Data.Char (isDigit)
import Data.List (elemIndex)

ok :: [Char] -> [Char]
ok s =
  if and [elemIndex p s <= elemIndex q s | (p, q) <- [('r', 'R'), ('g', 'G'), ('b', 'B')]]
    then "YES\n"
    else "No\n"

getInt :: State [Char] Int
getInt = state func
  where
    func s = first (\x -> read x :: Int) $ span isDigit s

getNext :: State [Char] [Char]
getNext = state func
  where
    func s = first ok $ span (/= '\n') (tail s)

mainFunc :: State [Char] [[Char]]
mainFunc = do
  n <- getInt
  replicateM n getNext

-- replicateM n f = loop n
--   where loop c
--     | c <=0 = pure []
--     | otherwise = (:) <$> f <*> (loop (c-1))

main :: IO ()
main = do
  inp <- getContents
  putStr $ concat $ evalState mainFunc inp

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
--import Data.List
--import Data.Array.Unboxed

type SP = State P.ByteString
type S = StateT P.ByteString

cmp a b = if a < b then 1 else 0

solve :: SP Builder
solve = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    s <- getNext
    let ok a b = P.elemIndex a s <= P.elemIndex b s
    let good = ok 'r' 'R' && ok 'g' 'G' && ok 'b' 'B'
    pure $ string7 $ if good then "YES\n" else "NO\n"

dropSpace :: P.ByteString -> P.ByteString
dropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough

getNext :: Monad m => S m P.ByteString
getNext = state $ P.span (> ' ') . dropSpace

getInt :: Monad m => S m Int
getInt = state $ fromJust . P.readInt . dropSpace

putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let outp = evalState solve inp
  P.putStr $ toLazyByteString outp

import Control.Monad (forM_)
import Data.Map (fromList, (!))

solve :: [Char] -> Bool
solve arr = m ! 'r' < m ! 'R' && m ! 'g' < m ! 'G' && m ! 'b' < m ! 'B'
  where
    m = fromList $ zip arr [1 ..]

main :: IO ()
main = do
    t <- readLn :: IO Int
    forM_ [1 .. t] $ \i -> do
        l <- getLine
        putStrLn $ if solve l then "YES" else "NO"

import Data.Char (toUpper)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf i xs = take i xs : chunksOf i (drop i xs)

toArr :: Read a => String -> [a]
toArr = map read . words

type InType  = String
type OutType = Bool

isKey :: Char -> Bool
isKey c = c `elem` "rgb"

solve :: InType -> OutType
solve = go (const False)
  where go :: (Char -> Bool) -> InType -> Bool
        go f [] = True
        go f (c : cs) = if isKey c then go (\z -> f z || z == toUpper c) cs
                        else f c && go f cs

receive :: [String] -> InType
receive [s] = s
receive _   = error "invalid input"

main :: IO ()
main = interact $ unlines . map (showb . solve . receive) . chunksOf 1 . tail . lines
  where showb True  = "YES"
        showb False = "NO"

import Control.Monad
import Data.Function
import Data.List
import Data.Maybe

solve :: IO ()
solve = do
    s <- getLine
    putStrLn $ if and (zipWith ((<) `on` fromJust . flip elemIndex s) "rgb" "RGB")
        then "YES" else "NO"

main :: IO ()
main = flip replicateM_ solve =<< readLn

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
--import Data.List
--import Data.Array.Unboxed

mainFun :: SP Builder
mainFun = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    s <- getNext
    let  ok p q = P.elemIndex p s <= P.elemIndex q s
    pure $ if  ok 'r' 'R' && ok 'g' 'G' && ok 'b' 'B'
      then  string7 "YES\n"
      else  string7 "NO\n"

type SP = State P.ByteString
type S = StateT P.ByteString

dropSpace :: P.ByteString -> P.ByteString
dropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough

getNext :: Monad m => S m P.ByteString
getNext = state $ P.span (> ' ') . dropSpace

getInt :: Monad m => S m Int
getInt = state $ fromJust . P.readInt . dropSpace

putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun inp
  P.putStr $ toLazyByteString outp