-- Codeforces 282A

import Control.Monad

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    replicateM n getLine >>= putStrLn . show . sum . map solve where
        solve :: [Char] -> Int
        solve [_, '+', _] = 1
        solve [_, '-', _] = -1

main = interact $ show . sum . map (\s -> if '+' `elem` s then 1 else -1) . tail . lines

solve :: String -> Int
solve all =
    foldl (\acc x-> if elem '+' x then acc + 1 else acc - 1) 0 $ tail$lines all
main = do
    all <- getContents
    print $ solve all

import Control.Monad (liftM)

solve :: [String] -> Int
solve []  =  0
solve (l:s)
  | '-' `elem` l  =  solve s - 1
  | '+' `elem` l  =  solve s + 1
  | otherwise  =  solve s

main :: IO ()
main  =  liftM (tail . lines) getContents >>= print . solve

import Data.List

main = do
	n <- getInt
	operations <- sequence $ map (\i -> getLine) [1..n]
	let res = foldr (\curr acc -> if (curr !! 1 == '+') then acc + 1 else acc - 1) 0 operations
	putStrLn $ show res

getInt::IO Int
getInt = do
	res <- getLine
	return $ readInt res

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

import Data.List

main = do
	n <- getInt
	operations <- sequence $ map (\i -> getLine) [1..n]
	let res = foldr (\curr acc -> if (isInfixOf "+" curr) then acc + 1 else acc - 1) 0 operations
	putStrLn $ show res

getInt::IO Int
getInt = do
	res <- getLine
	return $ readInt res

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

import Control.Monad
import Data.List

f :: [String] -> Int
f (a:rst)
  | "++" `isInfixOf` a = 1 + f rst
  | "--" `isInfixOf` a = (-1) + f rst
f [] = 0

main :: IO ()
main = do
  numLines <- getLine
  inputs <- replicateM (read numLines) getLine
  putStrLn $ show $ f inputs

import Control.Monad

count :: Char -> [String] -> Int
count c ss = length $ filter (\s -> elem c s) ss

main = do
    input <- getLine
    commands <- replicateM (read input) getLine
    print $ (count '+' commands) - (count '-' commands)

import Control.Monad

main = interact $ show.sum.map(\x -> if( x!!1 == '-') then -1 else  1).tail.lines

solve xs = sum [if x !! 1 == '+' then 1 else -1 | x <- xs]
main = interact $ show . solve . tail . lines

module Main where

solve line =
    plus - minus
    where
        plus = length $ filter (\x -> elem '+' x) line
        minus = length $ filter (\x -> elem '-' x) line

main = do
    _ <- getLine
    rules <- getContents
    print $ solve $ lines rules

import Control.Applicative

process a = a2-a1
  where a1= length $ filter (\z->z=="--X"||z=="X--") a
        a2= length $ filter (\z->z=="++X"||z=="X++") a

main::IO ()
main=do
    getLine
    a<-lines <$> getContents
    print $ process a

main = do
	numberString <- getLine
	let number = read numberString :: Int
	summa number 0

summa :: Int -> Int -> IO ()
summa 0 suma = print suma
summa i suma = do
	stat <- getLine
	if elem '+' stat
		then summa (i-1) (suma+1)
		else summa (i-1) (suma-1)

solve' :: String -> Int
solve' str = case str of
				"X++" -> 1
				"X--" -> -1
				"++X" -> 1
				"--X" -> -1
				otherwise -> 0

solve :: IO String -> IO Int
solve x = fmap (sum.map solve'.words) x

main :: IO()
main = solve getContents >>= print

import Data.List (foldl')

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

solve :: [String] -> Int
solve = foldl' f 0
  where f n "++X" = n + 1
        f n "X++" = n + 1
        f n "--X" = n - 1
        f n "X--" = n - 1
        f n _ = n

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

interpLine :: Int -> String -> Int
interpLine x s
  | '+' `elem` s = x+1
  | otherwise    = x-1

main :: IO ()
main = do
  [n] <- readList' (undefined::Int)
  lines <- replicateM n getLine
  print $ foldl interpLine 0 lines

exec :: Int -> [String] -> Int
exec x [] = x
exec x (n:ns)
  | n !! 1 == '+' = exec (x + 1) ns
  | otherwise = exec (x - 1) ns

main = do
  n <- getLine
  interact $ show . exec 0 . lines

import Data.List
main=interact$show.solve.parse
parse=map(\(_:l:_)->l).tail.lines
solve x=length p-length m where (p,m) = partition (== '+') x

-- import Debug.Trace
-- import System.IO.Unsafe
-- import Text.Printf
import System.IO
import Control.Monad
import Data.List

glwr = fmap (map read . words) getLine

main = do
  hSetBuffering stdout NoBuffering
  solve

solve :: IO ()
solve = do
  n:_ <- glwr
  strs <- forM [1..n] $ const getLine
  print $ bit n strs

bit :: Int -> [String] -> Int
bit n = foldr ko 0

ko s acc = case s!!1 of
  '+' -> acc+1
  _   -> acc-1

solve :: [String] -> Int
solve [] = 0
solve (x:xs)
    | x !! 1 == '+' = 1 + solve xs
    | otherwise = solve xs - 1

parse :: String -> String
parse = show . solve . tail . words

main = interact parse

import Control.Monad
import Control.Applicative

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

solve :: [String] -> Int
solve ss = (length (filter ((1==).op) ss)) - (length (filter ((-1==).op) ss))

op xs
  | xs == "++X" = 1
  | xs == "--X" = -1
  | xs == "X++" = 1
  | xs == "X--" = -1

module Main where

import Control.Monad (replicateM)

main :: IO ()
main = do
  n <- fmap read getLine :: IO Int
  inp <- replicateM n getLine
  let pluses = length . filter (elem '+') $ inp
      minuses = n - pluses
  print (pluses - minuses)

main = interact $ show . f . tail . lines

f [] = 0
f (a:b) = (if elem '+' a then 1 else -1) + f b

module Main where
import Control.Applicative
main = do
  commandCount <- read <$> getLine
  mapM (\_ -> getLine)[1..commandCount] >>= \commands -> print $ foldl interpreter 0 commands
    where interpreter x c | (c == "X++"|| c == "++X") = x + 1 | otherwise = x -1

main = interact $ show . sum . map (\x -> if elem '-' x then -1 else 1) . tail . lines

while i n = do
    if i == 0 then
        print n
    else do
        s <- getLine
        if s!!1 == '-' then
            while (i - 1) (n - 1)
        else
            while (i - 1) (n + 1)
main = do
    input <- getLine
    let n = read input :: (Int)
    while n 0

import Control.Monad
main = (getLine >>= (\l -> replicateM (read l) getLine)) >>= (print . foldr (\l -> if elem '-' l then pred else succ) 0)

main=interact$show.sum.map(\x->if x!!1=='+' then 1 else -1).tail.lines

main = interact$show.sum.map (\x->if x == '+' then 1 else -1).map head.map tail.tail.lines

main = interact f

f = show . sum . map g . tail . lines

g (_:c:_) | c == '+' = 1
          | otherwise = -1

main :: IO ()
main = do
    n <- getLine >>= return . read
    s <- sequence $ replicate n getLine
    putStrLn $ show $ sum $ map
                            (\x -> if x == "X++" || x == "++X" then 1 else -1)
                            s

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

interpBit :: Int -> Int -> IO ()
interpBit m 0 = print m >>= return
interpBit m n = do
    [_,o,_] <- getLine
    if o == '+'
      then interpBit (m + 1) (n - 1)
      else interpBit (m - 1) (n - 1)

module Main where

solve :: [String] -> Int
solve = solve' 0
        where
          solve' x [] = x
          solve' x (s:ss)
            | s!!1 == '+' = solve' (x+1) ss
            | s!!1 == '-' = solve' (x-1) ss
            | otherwise = solve' x ss

main = getLine >> getContents >>= (print . solve . lines)

import Control.Applicative
main= do
	n<-read <$> getLine::IO Int
	s<- length .filter (  elem '+'). lines <$> getContents
	let t = s+s -n
	print t

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

The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.

The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:

Operation ++ increases the value of variable x by 1.
Operation -- decreases the value of variable x by 1.

A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable x. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains.

A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.

You're given a programme in language Bit++. The initial value of x is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).

Input
------
The first line contains a single integer n (1 ≤ n ≤ 150) — the number of statements in the programme.

Next n lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable x (denoted as letter «X»). Thus, there are no empty statements. The operation and the variable can be written in any order.

Output
-------
Print a single integer — the final value of x.

Sample test(s)
--------------
input
```
1
++X
```
output
```
1
```

input
```
2
X++
--X
```
output
```
0
```
-}

bitCompute :: [String] -> Int
bitCompute xs = sum $ map (\s -> if '+' `elem` s then 1 else -1) xs

main = do
  input <- getContents
  let xs = tail $ lines input
  print $ bitCompute xs

main = do
  n <- readLn
  arr <- sequence $ replicate n getLine
  let m = length (filter (`elem` ["X++", "++X"]) arr) - length (filter (`elem` ["X--", "--X"]) arr)
  print m

import           Control.Monad                  ( replicateM )
folder :: Int -> String  -> Int
folder a s = if '+' `elem` s then (a + 1) else (a - 1)

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

import Control.Monad

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

operate (o:os)
        | o == '+' =  1
        | o == '-' = -1

solve (op:[])  =  operate $ tail op
solve (op:ops) = (operate $ tail op) + (solve ops)

import Data.Char

ans str = foldl check 0 str
check a xs
    | elem '+' xs = a+1
    | otherwise = a-1

main = do
    n<-getLine
    m<-getContents
    print.ans $ lines m

main :: IO ()
main = getLine >> getContents >>= print . foldl solve 0 . lines

solve :: Int -> String -> Int
solve a "X++" = a+1
solve a "++X" = a+1
solve a "X--" = a-1
solve a "--X" = a-1

main :: IO ()
main = getContents >>= print . f . tail . lines

f :: [String] -> Int
f [] = 0
f (x:xs)
  | '+' `elem` x = f xs + 1
  | '-' `elem` x = f xs - 1

import Data.List
solve :: [String] -> Int
solve = sum . map (\x -> if "++" `isInfixOf` x then 1 else -1)

work :: String -> String
work = show . solve . tail .lines

main :: IO ()
main = interact work

main = print . sum . map (\l -> if elem '+' l then 1 else -1) . tail . lines =<< getContents

main = print . sum . map (\x -> if x then 1 else -1) . map (elem '+') . tail . lines =<< getContents

import Control.Monad

solve :: [[Char]] -> [Char]
solve = unwords

count :: [Char] -> Int
count xs = foldl (\acc elem -> if elem == '+' then acc+1 else acc) 0 xs

main = do
    input1 <- getLine
    let num = (read input1 :: Int)
    lines <- replicateM num getLine
    let s = (count (unwords lines)) - num
    print s

import Data.Typeable

parse x = read x :: Int

solverec :: Int -> IO Int
solverec 0 = return 0
solverec x = do
    raw <- getLine
    acc <- return (if raw!!1=='+' then 1 else -1)
    sub <- solverec $ x-1
    return (acc+sub)

main = do
    raw <- getLine
    let n = parse raw
    res <- solverec n
    print res

import Control.Monad

parse s = case s of
  "++X" -> 1
  "X++" -> 1
  "--X" -> -1
  "X--" -> -1
  _ -> 0

main = do
  d <- getContents
  let (n:ls) = lines d
  let ops = map parse ls
  print $ sum ops

import Data.List (foldl')

main :: IO ()
main = interact $ show . foldl' (+) 0 . map solve . tail . words

solve :: String -> Int
solve (_:'+':_) = 1
solve (_:'-':_) = -1

module Main (main)
    where

import Data.List (sort, group)
import Control.Monad (replicateM)

main :: IO ()
main = print . exec . map (head . tail) =<< flip replicateM getLine =<< readLn
    where exec = count . map (pred . length) . group . sort . ("+-"++)
          count [p,m] = p - m

import Control.Monad
import Data.List

convert :: String -> Int
convert x = if x!!1 == '+' then 1 else -1

main :: IO ()
main = do
    str <- getLine
    inputs <- replicateM (read str) getLine
    print $ sum $ map convert inputs

import Data.Char(digitToInt)

toInt::[Char]->Int
toInt x =
 let
     toInt'::[Char]->Int->Int
     toInt' y z =
      if null y
         then z
         else toInt' (tail y) (z*10+(digitToInt (head y)-digitToInt '0'))
 in toInt' x 0

add::[Char]->Bool
add x =
 if null x
 then False
 else if (head x) == '+'
 then True
 else add (tail x)

getAddCnt::[[Char]]->Int
getAddCnt x =
 if null x
 then 0
 else if add $ head x
 then 1 + (getAddCnt $ tail x)
 else getAddCnt $ tail x

main::IO()
main =
 do
 input <- getContents
 let
  line = lines input
  n = toInt $ head line
  addCnt = getAddCnt $ tail line
  subCnt = n-addCnt
 print $ addCnt-subCnt

import qualified Data.Map as Map
import Control.Monad

g [] = 0
g (x : xs) = do
  case Map.lookup x (Map.fromList [("++X", 1), ("X++", 1), ("--X", -1), ("X--", -1)]) of
    Just y -> y + (g $ xs)
    Nothing -> g $ xs

main = do
  b <- readLn
  inputs <- replicateM b getLine
  putStrLn $ show $ g inputs

import Control.Monad
main = do
  n<-getLine
  arr<-replicateM (read n) getLine
  print ( (length (filter f arr)) -  (length (filter f' arr)) )
        where
                f x = (x=="X++") || (x=="++X")
                f' x = not (f x)

import Data.List
import Data.Char

main = do
	input <- getContents
	putStrLn $ show $ answer $ tail $ lines input

answer x = (length $ filter (isInfixOf "++") x) - (length $ filter (isInfixOf "--") x)

s x=show$length [i | i<-tail$lines x,elem '+' i] - 	length [i | i<-tail$lines x,elem '-' i]
main=interact$s

f s= if s!!1=='+' then 1 else -1
main=interact$show.sum.map f.tail.lines

parseOp :: String -> Int
parseOp "X++" = 1
parseOp "++X" = 1
parseOp "X--" = -1
parseOp "--X" = -1
parseOp _ = 0

main :: IO ()
main = do
	cs <- getContents
	print $ sum $ map parseOp $ words cs

import Control.Monad

data Operation = Inc | Dec deriving (Show, Eq, Ord)

parseLine :: String -> Operation
parseLine x
    | x `elem` ["++X", "X++"] = Inc
    | x `elem` ["--X", "X--"] = Dec
    | otherwise = error "Unparseble entity"

eval :: Int -> [Operation] -> Int
eval y [] = y
eval y (x:xs)
    | x == Inc = eval (y + 1) xs
    | x == Dec = eval (y - 1) xs

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

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

main :: IO ()
main = interact $ show . solve . tail . lines

solve :: [String] -> Int
solve  = foldl run 0

run :: Int -> String -> Int
run x (_ : '+' : _) = x + 1
run x (_ : '-' : _) = x - 1

import Control.Monad

main = getLine
    >>= return . (read :: String -> Int)
    >>= \x -> forM [1..x] (\i -> getLine >>= return . conversion)
    >>= print . sum

conversion :: String -> Int
conversion "++X" = 1
conversion "--X" = -1
conversion "X++" = 1
conversion "X--" = -1

main = do
    getLine
    ls <- fmap lines getContents

    let
        c1 = length $ filter (elem '+') ls
        c2 = length $ filter (elem '-') ls
    print $ c1 - c2

import Data.List

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    lines <- getNLines n
    print $ execute lines

getNLines :: Int -> IO [String]
getNLines 0 = return []
getNLines n = getLine >>= \newLine ->
    fmap ([newLine] ++) $ getNLines (n - 1)

execute :: [String] -> Int
execute [] = 0
execute (ins:rest) | isInfixOf "++" ins = execute rest + 1
    | isInfixOf "--" ins = execute rest - 1

f s | elem '+' s = 1
	| otherwise  = -1
main = interact $ show . sum . map f . tail . lines

import Data.List
import Data.List.Split
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Char as C

(|>) = flip ($)

main = interact process

process contents = let
  ls = contents |> lines |> tail
  in solve ls |> show

solve ls = let
  plus = ls |> filter ('+' `elem`) |> length
  minus = ls |> filter ('-' `elem`) |> length
  in plus - minus

isPlus    :: String -> Bool
isPlus xs
 | (hxs == '+') || (lxs == '+') = True
 | otherwise                    = False
 where hxs = head xs
       lxs = last xs

isSub :: String -> Bool
isSub xs
 | (hxs == '-') || (lxs == '-') = True
 | otherwise                    = False
 where hxs = head xs
       lxs = last xs

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

operate    :: [String] -> Int
operate [] = 0
operate (x:xs)
 | isPlus x = 1 + operate xs
 | isSub x  = (operate xs) - 1

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

recognize (x:y:z:_)
	|(x:[y])=="++" || (y:[z])=="++" = "++"
	|otherwise = "--"
solve []=0
solve (x:xs)
	|x=="++" =1+solve xs
	|otherwise=0-1+solve xs
main=getLine>>=(\x->interact$show.solve.map recognize.take (read x::Int).lines)

main = readsolveprint
readsolveprint::IO()
readsolveprint =  getLine >>= \x-> interact $ show.solve. take (read x) . lines
  where
    solve=foldr f 0
      where f x y | x== "++X" || x== "X++"= 1+y
              | otherwise= y-1

import Control.Applicative

process a = a2-a1
  where a1= length $ filter (\z->z=="--X"||z=="X--") a
        a2= length $ filter (\z->z=="--X"||z=="X--") a

main::IO ()
main=do
    getLine
    a<-lines <$> getContents
    print $ process a

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

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

solve :: [String] -> Int
solve xs = a - (length xs - a)
    where a = length $ filter (=="X++") xs

main :: IO ()
main = do
    n <- readInt
    xs <- replicateM n $ getLine
    print $ solve xs

main = do
    getLine
    l <- getContents
    putStrLn $ show . sum . map convert . tail . lines $ l
        where
            convert "++X" = 1
            convert "X--" = -1

--main = interact $ show . sum . map convert . tail . lines
--    where
--        convert "++X" = 1
--        convert "X--" = -1

main = do
    l <- getContents
    putStrLn $ show . sum . map (\x -> if x == "++X" then 1 else -1) . tail . lines $ l

import Control.Monad

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

operate (o:os)
        | o == 'X' =  0
        | o == '+' =  1
        | o == '-' = -1

solve (op:[])  = operate op
solve (op:ops) = (operate $ tail op) + (solve ops)

import Data.Char

main = interact $ unlines . map (\s -> if foldl(\acc c -> if isUpper c then acc else False) True $ tail s then map (\c -> if isUpper c then toLower c else toUpper c) s else s) . lines

main = interact $ show . sum . map (\s -> if head s == '+' then length s else length s * (-1)) . map (filter (/='X')) . tail . lines

apply :: Int -> String -> Int
apply y (x:s:xs)
  | s == '+' = y + 1
  | s == '-' = y - 1

run :: Int -> Int -> IO Int
run m n
  | m == 0 = return n
  | otherwise = getLine >>= run (m-1) . apply n

main = getLine >>= go 0 . read where go = flip run

import Data.Char

main :: IO ()
main = interact solve

solve :: String -> String
solve (x : xs) = toUpper x : xs

main = interact $ show . f . tail . lines
f [] = 0
f (a:b) = if elem '+' a then 1 else -1


import qualified Data.ByteString.Char8 as B

sum_lists x y = map (\(a, b) -> a+b) $ zip x y

max_val = 1000001

positive = \x -> if x < 0 then 0 else 1
negative = \x -> if x > 0 then 0 else 1

left x = scanl (+) 0 (map positive x)
right x = scanr (+) 0 (map negative x)

solve :: [Int] -> Int
solve x = foldl min max_val (init . tail $ sum_lists p1 p2)
   where
      p1 = left x
      p2 = right x

readInt bs = case B.readInt bs of Just (n,_) -> n

main=B.readFile"input.txt">>=writeFile"output.txt".show.solve.tail.map(signum.readInt).B.words

--main = do
--   handleIn <- openFile "input.txt" ReadMode
--   n' <- hGetLine handleIn
--   let n = read n' :: Int
--   t' <- hGetLine handleIn
--   let t = (map read (words t')) :: [Int]
--   handleOut <- openFile "output.txt" WriteMode
--   hPrint handleOut $ solve t
--   hFlush handleOut

import qualified Data.ByteString.Char8 as B

main=B.readFile"input.txt">>=writeFile"output.txt".show.solve.tail.map(signum.readInt).B.words

readInt bs = case B.readInt bs of Just (n,_) -> n

solve :: [Int] -> Int
solve (x:xs) = case nonzero of
             [] -> zeronum
             _ -> (zeronum+).minimum $ zipWith (+) (scanl positive (sum[1|x>0]) nonzero) (init $ scanr negative 0 nonzero)
   where
     nonzero = filter (0/=) xs
     zeronum = sum[1|0<-x:xs]

positive x y = if y>0 then x+1 else x
negative x y = if x<0 then y+1 else y

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}
{-# OPTIONS_GHC -O3 #-}

import Control.Applicative
import Control.Monad hiding ((<$!>))
import Control.Monad.ST.Safe
import Control.Monad.State hiding ((<$!>))
-- import Data.Array
import Data.Array.IArray
import Data.Array.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Builder as BB
import Data.Char
import qualified Data.Foldable as F
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
-- import Data.Tree
import Data.Tuple
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
-- import Debug.Trace
import System.IO

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

main = do
  input <- openFile "input.txt" ReadMode
  hGetLine input
  xs <- unfoldr (B.readInt . B.dropWhile isSpace) <$> (B.hGetLine input)

  let
    a = scanl1 (+) $ map (fromEnum . (>= 0)) xs
    b = scanr1 (+) $ map (fromEnum . (<= 0)) xs

  output <- openFile "output.txt" WriteMode
  hPrint output $ minimum $ zipWith (+) a $ tail b
  hClose output

import Array (Array, (!), array, listArray)
import Char (isDigit, ord)
import Data.List (foldl1')
import IO
import Monad (liftM)
import Prelude hiding (read)

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

minimum' :: Ord a => [a] -> a
minimum'  =  foldl1' (\a b -> a < b ? a $ b)

solve :: Int -> Array Int Int -> Int
solve n a  =  minimum' [(l ! i) + (r ! i) | i <- [1..n-1]]
  where
    l  =  array (0, n) ((0,0) : [(i, l ! (i-1) + (a ! i >= 0 ? 1 $ 0)) | i <- [1..n]])
    r  =  array (0, n) ((n,0) : [(i, r ! (i+1) + (a ! (i+1) <= 0 ? 1 $ 0)) | i <- [0..n-1]])

read :: String -> Int
read (c:s)
  | c == '-'  =  (-1) * (read' 0 s)
  | otherwise  =  read' 0 (c:s)
  where
    read' a []  =  a
    read' a (c:s)  =  read' (10 * a + ord c - ord '0') s

main :: IO ()
main  =  do
    hInput  <-  openFile "input.txt" ReadMode
    hOutput  <-  openFile "output.txt" WriteMode

    n   <-  liftM read (hGetLine hInput)
    as  <-  liftM (listArray (1,n) . map read . words) (hGetLine hInput)
    hPrint hOutput $ solve n as

    hClose hInput
    hClose hOutput

import Array (Array, (!), array, listArray)
import Char (isDigit, ord)
import Data.List (foldl1')
import IO
import Monad (liftM)
import Prelude hiding (read)

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

minimum' :: Ord a => [a] -> a
minimum'  =  foldl1' (\a b -> a < b ? a $ b)

solve :: Int -> Array Int Int -> Int
solve n a  =  minimum' [(l ! i) + (r ! i) | i <- [1..n-1]]
  where
    l  =  array (0, n) ((0,0) : [(i, l ! (i-1) + (a ! i >= 0 ? 1 $ 0)) | i <- [1..n]])
    r  =  array (0, n) ((n,0) : [(i-1, r ! i + (a ! i <= 0 ? 1 $ 0)) | i <- [1..n]])

read :: String -> Int
read s  =  read' 0 (dropWhile (not . isDigit) s)
  where
    read' a []  =  a
    read' a (c:s)
      | isDigit c  =  read' (10 * a + ord c - ord '0') s
      | otherwise  =  error ""

main :: IO ()
main  =  do
    hInput  <-  openFile "input.txt" ReadMode
    hOutput  <-  openFile "output.txt" WriteMode

    n   <-  liftM read (hGetLine hInput)
    as  <-  liftM (listArray (1,n) . map read . words) (hGetContents hInput)
    hPrint hOutput $ solve n as

    hClose hInput
    hClose hOutput

import qualified Data.ByteString.Char8 as B

main=B.readFile"input.txt">>=writeFile"output.txt".parseOutput.solve.parseInput

readInt bs = case B.readInt bs of Just (n,_) -> n

parseInput = tail.map (signum.readInt).B.words
parseOutput = show

solve :: [Int] -> Int
solve xs = case nonzero of
             [] -> zeronum
             _ -> (zeronum+).pred.minimum $ zipWith (+) (tail$scanl positive 0 nonzero) (init$scanr negative 0 nonzero)
   where
     nonzero = filter (0/=) xs
     zeronum = sum[1|0<-xs]

positive x y = if y>0 then x+1 else x
negative x y = if x<0 then y+1 else y

import qualified Data.ByteString.Char8 as B

main=B.readFile"input.txt">>=writeFile"output.txt".parseOutput.solve.parseInput

readInt bs = case B.readInt bs of Just (n,_) -> n

parseInput = map (signum.readInt).B.words
parseOutput = show

solve :: [Int] -> Int
solve xs = minimum $ zipWith (+) (scanl positive 0 xs) (scanr negative 0 xs)

positive x y = if y>=0 then x+1 else x
negative x y = if y<=0 then y+1 else x+1

import System.IO

left :: [Integer] -> [Integer] -> (Integer -> Bool) -> [Integer]
left acc [] f = acc
left (a:acc) (x:xs) f
   | not (f x) = left ( (a+1):a:acc ) xs f
   | otherwise  = left ( a:a:acc ) xs f

sum_lists :: [Integer] -> [Integer] -> [Integer]
sum_lists [] [] = []
sum_lists (x:xs) (y:ys) = (x+y):(sum_lists xs ys)

max_val = 1000001

solve :: [Integer] -> Integer
solve x = foldl min max_val (sum_lists p1 p2)
   where
      p1 = reverse (left [0] x (<0) )
      p2 = left [0] (reverse x) (>0)

main = do
   handleIn <- openFile "input.txt" ReadMode
   n' <- hGetLine handleIn
   let n = read n' :: Integer
   t' <- hGetLine handleIn
   let t = (map read (words t')) :: [Integer]
   handleOut <- openFile "output.txt" WriteMode
   hPutStrLn handleOut ( show ( solve t ) )
   hFlush handleOut


--
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}

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

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

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

intersectM :: (Int, Int) -> (Int, Int) -> Maybe (Int, Int)
intersectM (l1, r1) (l2, r2) = if rr < ll then Nothing else Just (ll, rr)
    where
        ll = max l1 l2
        rr = min r1 r2

solve :: (Int, Int) -> (Int, Int) -> Int
solve (l1, r1) (l2, r2) =
        case mm of
            Nothing -> l1 + l2
            Just (ll, rr) -> ll
    where
        mm = intersectM (l1, r1) (l2, r2)

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

module Main (main)
where

import Data.List (intercalate, words)

main :: IO ()
main = intercalate "\n" <$> map show <$> map minElem <$> map readNums <$> (read <$> getLine >>= readNLines) >>= putStrLn

minElem :: (Int, Int, Int, Int) -> Int
minElem (a, b, c, d)
  | c `between` (a, b) = c
  | a `between` (c, d) = a
  | otherwise = a + c
  where x `between` (y, z) = x >= y && x <= z

readNLines :: Int -> IO [String]
readNLines n = sequence $ replicate n getLine

readNums :: String -> (Int, Int, Int, Int)
readNums str = toQuadruple $ map read $ words str
  where toQuadruple [a, b, c, d] = (a, b, c, d)
        toQuadruple _ = undefined

import Control.Monad
main = do
  t <- read <$> getLine :: IO Int
  replicateM_ t $ do
    [l1,r1,l2,r2] <- fmap (fmap read)
                   . fmap words
		   $ getLine :: IO [Int]
    print $ solve l1 r1 l2 r2

solve a1 b1 a2 b2
  | b1 < a2 || b2 < a1 = a1 + a2
  | otherwise = max a1 a2

module Main (main)
where

import Data.List (intercalate, words)

main :: IO ()
main = intercalate "\n" <$> map show <$> map minElem <$> map readNums <$> (read <$> getLine >>= readNLines) >>= putStrLn

minElem :: (Int, Int, Int, Int) -> Int
minElem (a, b, c, d)
  | c `between` (a, b) = c
  | a `between` (c, d) = a
  | otherwise = b + c
  where x `between` (y, z) = x >= y && x <= z

readNLines :: Int -> IO [String]
readNLines n = sequence $ replicate n getLine

readNums :: String -> (Int, Int, Int, Int)
readNums str = toQuadruple $ map read $ words str
  where toQuadruple [a, b, c, d] = (a, b, c, d)
        toQuadruple _ = undefined


-- import Debug.Trace

import Data.Bits

type InType  = (Int, Int)
type OutType = Bool

inpLines :: Int
inpLines = 1

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf x l  = take x l : chunksOf x (drop x l)

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

solve :: InType -> OutType
solve (u, v)
    | u > v     = False
    | otherwise = go 0 0 0
    where go :: Int -> Int -> Int -> Bool
          go 31 _ _ = True
          go b o1 o2
            | o1 < o2 = False
            | otherwise = go (b + 1) (o1 + f b u) (o2 + f b v)
          f x b = if testBit b x then 1 else 0

receive :: [String] -> InType
receive [s] = (u, v)
    where [u, v] = toArr s

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

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

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [q] <- readInts
  replicateM_ q $ do
    [u, v] <- readInts
    let
      fun i x = popCount $ x .&. (2 * bit i - 1)
      ok = v >= u && and [fun i v <= fun i u | i <- [0..29]]
    lift $ P.putStrLn $ if  ok
      then  P.pack "YES"
      else  P.pack "NO"

type SIO = StateT P.ByteString IO

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


f [] cnt ans
  | cnt /= 0 = -1
  | otherwise = ans
f (')':xs) cnt ans = f xs (cnt-1) ans2
  where ans2 = if cnt > 0 then ans else ans+2
f (_:xs) cnt ans = f xs (cnt+1) ans
main = do
  getLine
  s <- getLine
  print $ f s 0 0

f [] cnt ans
  | cnt /= 0 = -1
  | otherwise = ans
f (')':xs) cnt ans
  | cnt <= 0 = f xs (cnt-1) (ans+2)
  | otherwise = f xs (cnt-1) ans
f (_:xs) cnt ans = f xs (cnt+1) ans
main = do
  getLine
  s <- getLine
  print $ f s 0 0

f [] cnt ans = if cnt /= 0 then -1 else ans
f (')':xs) cnt ans = f xs (cnt-1) ans2
  where ans2 = if cnt > 0 then ans else ans+2
f (_:xs) cnt ans = f xs (cnt+1) ans
main = do
  getLine
  s <- getLine
  print $ f s 0 0

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

main = do
  getLine
  str <- getLine
  if length (filter (== '(') str) /= length (filter (== ')') str)
    then print $ -1
    else print $ f 0 str

f _ [] = 0
f x ('(':cs) = f (x + 1) cs
f x (')':cs) = let x' = x - 1 in
  if x' < 0 then 1 + g x' cs
  else f x' cs

g _ [] = 0
g x ('(':cs) = let x' = x + 1 in
  if x' >= 0 then 1 + f x' cs
  else 1 + g x' cs
g x (')':cs) = 1 + g (x - 1) cs


import Data.Set
import Data.Array
q '+'=(1,0)
q '-'=(0,1)
z=fmap
c(a,b)(c,d)=(a+c,b+d)
s(h:l)=z e r where [n,m]=z read$words h;r=z(\(c:n)->(read n+0,q c))l;t=assocs$accumArray c(0,0)(1,n)r;s=fromList$z fst$Prelude.filter((==sum(z(fst.snd)t)-n+m).uncurry(-).snd)t;e(j,(k,n))|m&&size s>1="Not defined"|m==(k>n)="Truth"|1>0="Lie"where m=member j s
main=interact$unlines.s.lines

import qualified Data.Set as Set
import qualified Data.Array as Arr

s(h:t) = result ++ [] where
  [n,m] = map read $ words h
  rawTells = map tl t where
    tl ('+':n) = (read n :: Int, (1, 0))
    tl ('-':n) = (read n :: Int, (0, 1))
  cmb (a,b) (c,d) = (a+c, b+d)
  tells = Arr.assocs $ Arr.accumArray cmb (0,0) (1, n) $ rawTells
  liesByDefault = sum $ map (fst . snd) $ tells
  changeNeeded = liesByDefault-(n-m)
  suspects = map fst $ filter ((== changeNeeded).uncurry (-).snd) $ tells
  ss = Set.fromList suspects
  result = map eval rawTells where
    eval (j, _) | Set.member j ss && length suspects > 1 = "Not defined"
    eval (j, (k, nk)) | Set.member j ss == (k>nk) = "Truth"
     | otherwise = "Lie"

main=interact$unlines.s.lines

import qualified Data.Map as Map
import qualified Data.Set as Set
import Control.Arrow

s(h:t) = result ++ [] where
  [n,m] = map read $ words h
  rawTells = map tl t where
    tl ('+':n) = (read n :: Int, (1, 0))
    tl ('-':n) = (read n :: Int, (0, 1))
  cmb (a,b) (c,d) = (a+c, b+d)
  tells = Map.toList $ Map.fromListWith cmb $ rawTells
  liesByDefault = sum $ map (fst . snd) $ tells
  changeNeeded = liesByDefault-(n-m)
  suspects = map fst $ filter ((== changeNeeded).uncurry (-).snd) $ tells
  ss = Set.fromList suspects
  result = map eval rawTells where
    eval (j, _) | Set.member j ss && length suspects > 1 = "Not defined"
    eval (j, (k, nk)) | Set.member j ss == (k>nk) = "Truth"
     | otherwise = "Lie"

main=interact$unlines.s.lines


solve xs = map (\x -> if (x `mod` 2 == 0) then 1 else 0) xs

main = do text <- readFile "input.txt"
          writeFile "output.txt" (unlines $ map show $ solve $ map read $ tail $ lines text)

main = readFile "input.txt" >>= writeFile "output.txt" . concat . map ((++"\n") . show . (`mod`2) . (+1) . read) . tail . lines

s x=show(mod(1+x)2)++"\n"
main=do{c<-readFile"input.txt";writeFile"output.txt"$foldl(++)""$map(s.read)$tail$words c}

s x=show(mod(1+x)2)++"\n"
main=do
 c<-readFile"input.txt"
 writeFile"output.txt"$foldl(++)""$map(s.read)$tail$words c


import Data.List

get_min :: Maybe Integer -> Integer -> [(Char, Integer)] -> Integer
get_min _                 acum []              = acum
get_min _                 acum (('R', n):rest) = get_min (Just n) acum rest
get_min Nothing           acum (('L', n):rest) = get_min Nothing acum rest
get_min (Just last_right) acum (('L', n):rest) = get_min (Just last_right) (min acum (div (n - last_right) 2)) rest

myShow :: Integer -> String
myShow n
  | n >= 10^10 = "-1"
  | otherwise  = show n

process :: String -> String
process str =
  let [_, dirs, nums] = lines str
      parts  = zip dirs (map read $ words nums)
  in myShow $ get_min Nothing (10^10) parts

main :: IO ()
main = interact process

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

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

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

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

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

  -- converting list to Set
  -- let mySet = S.fromList myList
  --
  generatedMemo :: S.Set Int -> S.Set Int -> Int -> [Char] -> [Char]
  generatedMemo _ _ 20 accumulator = accumulator
  generatedMemo locLeft locRight n accumulator
    | n `elemSet` locLeft   = generatedMemo locLeft locRight (n + 1) $ 'L':accumulator
    | n `elemSet` locRight  = generatedMemo locLeft locRight (n + 1) $ 'R':accumulator
    | otherwise             = generatedMemo locLeft locRight (n + 1) $ ' ':accumulator

  mayMeetF :: ((Char, Int), (Char, Int)) -> Bool
  mayMeetF (('R', _), ('L', _)) = True
  mayMeetF _ = False

  diffF :: ((Char, Int), (Char, Int)) -> Int
  diffF (('R', x), ('L', y)) = (y - x) `div` 2

  normalized :: [Int] -> [Int]
  normalized (x:xs) = (x:xs)
  normalized [] = [-1]

  main :: IO()
  main = do
    n <- getLine >>= return . readInt
    directions <- getLine
    locations <- getLine >>= return . sort .  (map readInt) . words
    let dirLoc = directions `zip` locations
        dirLoc2 = 1 `drop` dirLoc
        mayMeet = (mayMeetF `filter`) $ dirLoc `zip` dirLoc2
        diffs =  diffF  `map` mayMeet
        normaldiff = normalized diffs
    putStrLn $ show $ minimum normaldiff

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}

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

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

main :: IO ()
main = do
    _ <- getLine
    lrs <- getLine
    xs <- map readInt.B.words <$> B.getLine
    print . maybe (-1) id $ solve lrs xs

solve :: String -> [Int] -> Maybe Int
solve lrs xs = go0 lrs xs
  where
    go0 ('R':'L':lrs) (x:y:xys) = go (div (y-x) 2) lrs xys
    go0 (_:r:lrs) (_:y:xys) = go0 (r:lrs) (y:xys)
    go0 _ _ = Nothing
    go !res ('R':'L':lrs) (x:y:xys) = go (min res $ div (y-x) 2) lrs xys
    go res (_:r:lrs) (_:y:xys)  = go res (r:lrs) (y:xys)
    go res _ _ = Just res

import Data.List( minimum)
main = do
    n <- getLine
    lrs <- getLine
    xs <- return . map (read::String->Integer) . words =<< getLine
    let distxs = zip lrs xs
	filt [] = []
	filt [p] = []
	filt ((dir1,x1):tl@((dir2,x2):ps)) =
	    if dir1=='R' && dir2=='L'
		then ((x2-x1)`div`2):filt ps
		else filt tl
	candidate = filt distxs
    if candidate == [] then print $ negate 1
			else print . minimum $ filt distxs

import Control.Arrow
import Control.Applicative
import Data.Int

solve :: [Char] -> [Int64] -> Int64
solve dirs coords = case impacttimes of
                      [] -> -1
                      x -> minimum x
  where
    impacttimes = solve' dirs coords []
    solve' :: [Char] -> [Int64] -> [Int64] -> [Int64]
    solve' ('R':ds@('L':_)) (n1:cs@(n2:_)) acc = solve' ds cs (((n2 - n1) `div` 2):acc)
    solve' (_:ds) (_:cs) acc = solve' ds cs acc
    solve' _ _ acc = acc

main :: IO()
main = do
  _ <- getLine
  dirs <- getLine
  coords <- (map read . words) <$> getLine
  print $ solve dirs coords

import Data.List

maybe_min :: Maybe Integer -> Integer -> Maybe Integer
maybe_min Nothing n   = Just n
maybe_min (Just n') n = Just $ min n' n

get_min :: Maybe Integer -> Maybe Integer -> [(Char, Integer)] -> Maybe Integer
get_min _                 acum []              = acum
get_min _                 acum (('R', n):rest) = get_min (Just n) acum rest
get_min Nothing           acum (('L', n):rest) = get_min Nothing acum rest
get_min (Just last_right) acum (('L', n):rest) = get_min (Just last_right) (maybe_min acum (div (n - last_right) 2)) rest

myShow :: Maybe Integer -> String
myShow n = case n of
  Nothing   -> "-1"
  (Just n') -> show n'

process :: String -> String
process str =
  let [_, dirs, nums] = lines str
      parts  = zip dirs (map read $ words nums)
  in myShow $ get_min Nothing Nothing parts

main :: IO ()
main = interact process

import Data.Maybe
import Data.Char
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

main = do
    n <- read `fmap` getLine :: IO Int
    dirs <- BS.getLine
    ps <- BS.getLine
    let ns = (map (fst . fromJust . BS8.readInt) . BS8.words) ps :: [Int]
    print (collide ns dirs)

collide :: [Int] -> BS8.ByteString -> Int
collide ns ds = f ns ds (-1) where
    f (n:n2:ns) ds t
        | d == ord 'R' && d2 == ord 'L' = f (n2:ns) ds' (if t == -1 then t' else min t' t)
        | otherwise = f (n2:ns) ds' t
        where
            d = fromIntegral $ BS.head ds
            d2 = fromIntegral $ BS.head (BS.tail ds)
            ds' = BS.tail ds
            t' = (n2 - n) `div` 2
    f _ _ t = t

module Main where

import Control.Applicative

main = do
    getLine
    s <- getLine
    i <- map (read :: String -> Int) . words <$> getLine
    let m = snd $ foldr (\(x,y) (a,acc) -> case (x,a) of
                            ('R', Just ('L',c)) -> (Nothing, ((c-y)`div`2):acc)
                            ('L', Just ('L',c)) -> (Just('L',y), acc)
                            ('L', Nothing) -> (Just('L',y), acc)
                            _        -> (Nothing, acc)) (Nothing,[])  $ zip s i
    print $ if null m then (-1)  else minimum m

import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric
import Data.Maybe(isNothing, fromJust)
-- import Debug.Trace(trace)

trace x y = y

fastRead :: String -> Int64
fastRead ('-':s) = case readDec s of [(n, "")] -> (-n)
fastRead s = case readDec s of [(n, "")] -> n

main = interact solve

solve input = if isNothing answer then "-1" else show $ fromJust answer
    where
    n_s:pattern:worded' = words input
    n::Int
    n = read n_s
    points::[Int]
    points = map read worded'

    zipped::[(Char, Int)]
    zipped = zip pattern points

    bytwo::[x] -> [(x,x)]
    bytwo [] = []
    bytwo (x:[]) = []
    bytwo (x:y:xs) = (x,y):(bytwo (y:xs))

    answer::Maybe Int
    answer = foldl' foldop Nothing $ bytwo zipped

    foldop current (('L',x), ('R',y)) = current
    foldop current (('L',x), ('L',y)) = current
    foldop current (('R',x), ('R',y)) = current
    foldop current ((xdir, x), (ydir, y))
           | trace (show xdir ++ show x ++ show ydir ++ show y) False = Nothing
           | isNothing current = Just ((y-x) `div` 2)
           | otherwise = Just $ min cur ((y-x) `div` 2)
           where
                Just cur = current
                distance = (y-x) `div` 2

import Control.Applicative
import Control.Monad

solve :: String -> [Int] -> (Maybe Int, Maybe Int)
solve [] [] = (Nothing, Nothing)
solve (c:cs) (x:xs) | c == 'L' = (Just x, b)
                    | c == 'R' = (a, d)
                    where (a, b) = solve cs xs
                          td = do
                                var <- a
                                let timeImpact = (var - x) `div` 2
                                return timeImpact
                          d = (liftM2 min td b) `mplus` td

getInt :: Maybe Int -> Int
getInt Nothing = -1
getInt (Just x) = x

main :: IO ()
main = do
        getLine
        dir <- getLine
        pos <- map read . words <$> getLine
        let soln = solve dir pos
        -- putStrLn . show $ soln
        putStrLn . show . getInt . snd $ solve dir pos

import Data.Maybe
import Data.Char
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

main = do
    n <- read `fmap` getLine :: IO Int
    dirs <- BS.getLine
    ps <- BS.getLine
    let ns = (map (fst . fromJust . BS8.readInt) . BS8.words) ps :: [Int]
    print (collide ns dirs)

collide :: [Int] -> BS8.ByteString -> Int
collide ns ds = f ns ds (-1) where
    f (n:n2:ns) ds t
        | d == ord 'R' && d2 == ord 'L' = f (n2:ns) ds' (if t == -1 then t' else min t' t)
        | otherwise = f ns ds' t
        where
            d = fromIntegral $ BS.head ds
            d2 = fromIntegral $ BS.head (BS.tail ds)
            ds' = BS.tail ds
            t' = (n2 - n) `div` 2
    f _ _ t = t

import Data.List

get_min :: [Integer] -> [Integer] -> Integer
get_min _  [] = -1
get_min xs (y:ys) =
  let xs' = dropWhile (< y) xs
  in if null xs' then -1 else div (head xs' - y) 2

process :: String -> String
process str =
  let [_, dirs, nums] = lines str
      parts  = zip dirs (map read $ words nums)
      lefts  = sort . map snd . filter (\(n,_) -> n == 'L') $ parts
      rights = sort . map snd . filter (\(n,_) -> n == 'R') $ parts
  in show $ get_min lefts rights

main :: IO ()
main = interact process


{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeFamilies  #-}

import           Data.Bits
--import           Data.Functor.Foldable
import           Data.List
import           Data.Word

main = do
  _ <- getLine
  ns <- fmap read . words <$> getLine :: IO [Word32]
  let bs = w2bs <$> ns
  -- print $ ixRecurse 32 ns
  -- print . bs2w $ structuralRecurse bs
  print . bs2w $ hyloRecurse bs

ixRecurse :: Int -> [Word32] -> Word32
ixRecurse 0 _ = 0
ixRecurse i [] = 0
ixRecurse i ns = go (i-1) zs os
  where
    go i [] [] = 0
    go i [] on = ixRecurse i ns
    go i zs [] = ixRecurse i zs
    go i zs os = min (ixRecurse i zs) (ixRecurse i os) + 2^i
    (zs,os) = partition (\x -> ((bit (i-1)) .&. x) /= 0) ns

data Bit = O | I
  deriving (Show, Eq, Ord)

structuralRecurse :: [[Bit]] -> [Bit]
structuralRecurse ns = go (zs,os)
  where
    (zs, os) = partition (\x -> head x == O) . filter (not . null) $ ns
    go :: ([[Bit]], [[Bit]]) -> [Bit]
    go ([],[]) = []
    go ([],os) = O:structuralRecurse (tail <$> os)
    go (zs,[]) = O:structuralRecurse (tail <$> zs)
    go (zs,os) = I:min (structuralRecurse . fmap tail $ zs) (structuralRecurse . fmap tail $ os)

data BTree = Node (BTree) (BTree) | Empty
data BTreeF b = NodeF b b | EmptyF
  deriving (Functor, Show)

hyloRecurse :: [[Bit]] -> [Bit]
hyloRecurse = init . hylo alg coalg
  where
    alg :: BTreeF [Bit] -> [Bit]
    alg EmptyF        = []
    alg (NodeF [] os) = O:os
    alg (NodeF zs []) = O:zs
    alg (NodeF zs os) = I:min os zs

    coalg :: [[Bit]] -> BTreeF [[Bit]]
    coalg [] = EmptyF
    coalg ns = NodeF (tail <$> zs) (tail <$> os)
        where
          (zs, os) = partition (\x -> head x == O) . filter (not . null) $ ns

bs2w :: [Bit] -> Word32
bs2w bs = go 0 bs
  where
    go acc []     = acc
    go acc (I:bs) = go ((shiftL acc 1) .|. 1) bs
    go acc (O:bs) = go (shiftL acc 1) bs

w2bs :: Word32 -> [Bit]
w2bs w = fmap (\n -> if (bit n .&. w) /= 0 then I else O) [31,30..0]

hylo :: Functor f => (f b -> b) -> (a -> f a) -> a -> b
hylo f g = h where h = f . fmap h . g

import Data.Bits
import Data.List

doit :: Int -> [Int] -> Int
doit _    [] = -1
doit (-1) _  = 0
doit b xs = min (max (combine al) ar) (max al (combine ar))
  where mask = 1 `shift` b
        (ls, rs) = partition (\x -> x .&. mask == 0) xs
        al = doit (b-1) ls
        ar = doit (b-1) rs
        combine val | val == -1 = val
        combine val             = val .|. mask

main :: IO ()
main = doit 29 . map read . words <$> (getLine >> getLine) >>= print

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

main = getLine >> getLine >>= print.solve 31.map read.words

solve :: Int -> [Int] -> Int
solve (-1) _ = 0
solve _ [] = bit 31
solve p xs
	| all (flip testBit p) xs || all (not.flip testBit p) xs = solve p' (f xs)
	| otherwise = bit p .|. min (solve p' $ f $ filter (flip testBit p) xs) (solve p' $ f $ filter (not.flip testBit p) xs)
	where
		p' = p - 1
		f = map (.&. complement (bit p))

import           Data.Bits
import           Data.List
import           Data.Word

main = do
  _ <- getLine
  ns <- fmap read . words <$> getLine :: IO [Word32]
  print $ solve 32 ns
data Bit = O | I

bitStringToWord :: (Bits a, Num a) => [Bit] -> a
bitStringToWord bs = go 0 bs
  where
    go acc []     = acc
    go acc (I:bs) = go ((shiftL acc 1) .|. 1) bs
    go acc (O:bs) = go (shiftL acc 1) bs

data BTree = Node BTree BTree | Leaf Bit

solve :: Int -> [Word32] -> Word32
solve 0 _ = 0
solve i [] = 0
solve i ns = go (i-1) zs os
  where
    go i [] [] = 0
    go i [] on = solve i ns
    go i zs [] = solve i zs
    go i zs os = min (solve i zs) (solve i os) + 2^i
    (zs,os) = partition (\x -> ((bit (i-1)) .&. x) /= 0) ns

{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE TypeFamilies  #-}

import           Data.Bits
import           Data.List
import           Data.Word

main = do
  _ <- getLine
  ns <- fmap read . words <$> getLine :: IO [Word32]
  let bs = w2bs <$> ns
  -- print $ ixRecurse 32 ns
  print . bs2w $ structuralRecurse bs
  -- print . bs2w $ hyloRecurse bs

ixRecurse :: Int -> [Word32] -> Word32
ixRecurse 0 _ = 0
ixRecurse i [] = 0
ixRecurse i ns = go (i-1) zs os
  where
    go i [] [] = 0
    go i [] on = ixRecurse i ns
    go i zs [] = ixRecurse i zs
    go i zs os = min (ixRecurse i zs) (ixRecurse i os) + 2^i
    (zs,os) = partition (\x -> ((bit (i-1)) .&. x) /= 0) ns

data Bit = O | I
  deriving (Show, Eq, Ord)

structuralRecurse :: [[Bit]] -> [Bit]
structuralRecurse ns = go zs os
  where
    go [] [] = []
    go [] os = O:structuralRecurse (tail <$> os)
    go zs [] = O:structuralRecurse (tail <$> zs)
    go zs os = I:min (structuralRecurse . fmap tail $ zs) (structuralRecurse . fmap tail $ os)
    (zs, os) = partition (\x -> head x == O) . filter (not . null) $ ns

data BTreeF b = NodeF b b | EmptyF
  deriving (Functor, Show)

hyloRecurse :: [[Bit]] -> [Bit]
hyloRecurse = hylo alg coalg
  where
--    alg :: BTreeF a [Bit] -> [Bit]
alg EmptyF        = return O
alg (NodeF zs os) = I:min (zs) (os)
--    coalg :: [[Bit]] -> BTreeF [a] [[Bit]]
coalg [] = EmptyF
coalg ns = fmap tail <$> (NodeF zs os)
      where
        (zs, os) = partition (\x -> head x == O) . filter (not . null) $ ns

bs2w :: [Bit] -> Word32
bs2w bs = go 0 bs
  where
    go acc []     = acc
    go acc (I:bs) = go ((shiftL acc 1) .|. 1) bs
    go acc (O:bs) = go (shiftL acc 1) bs

w2bs :: Word32 -> [Bit]
w2bs w = fmap (\n -> if (bit n .&. w) /= 0 then I else O) [31,30..0]

hylo :: Functor f => (f b -> b) -> (a -> f a) -> a -> b
hylo f g = h where h = f . fmap h . g

{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
import System.IO
import Data.Ord
import Data.Int
import Data.Bits
import Data.Char
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Class
import Control.Monad.Trans.State.Strict (StateT)
import qualified Control.Monad.Trans.State.Strict as StateT
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as C

getNewLine :: SIO ByteString
getNewLine = (lift $ C.hGetLine stdin) >>= (\z -> let x = C.dropWhile isSpace z in if C.null x then getNewLine else return x)

getRemain :: ByteString -> SIO ByteString
getRemain b = let bns = C.dropWhile isSpace b in
                if C.null bns then getNewLine >>= liftM2 (>>=) StateT.put (const . return)
                else return bns

data HInt
data HInt64
data HNormal
data HString
data HList

type SIO a = StateT ByteString IO a

class IOInteract a where
    convert :: ByteString -> (a, ByteString)
    toShowS :: a -> String -> String
    toShow :: a -> String
    toShow x = toShowS x []

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

type family IOType x where
    IOType Int = HInt
    IOType Int64 = HInt64
    IOType String = HString
    IOType [x] = HList
    IOType x = HNormal

class IOInteractp flag a where
    convertp :: flag -> ByteString -> (a, ByteString)
    toShowSp :: flag -> a -> String -> String

instance (Show a, Read a) => IOInteractp HNormal a where
    convertp _ x = let (a, b) = C.break isSpace x in (read $ C.unpack a, b)
    toShowSp _ x = shows x

instance IOInteractp HInt Int where
    convertp _ x = fromMaybe (error "parse") $ C.readInt x
    toShowSp _ x = shows x

instance IOInteractp HInt64 Int64 where
    convertp _ x = let (a, b) = fromMaybe (error "parse") $ C.readInteger x in (fromIntegral a, b)
    toShowSp _ x = shows x

instance IOInteractp HString String where
    convertp _ x = let (a, b) = C.break isSpace x in (C.unpack a, b)
    toShowSp _ x = showString x

instance (IOInteract a) => IOInteractp HList [a] where
    convertp _ x = let (a, b) = convert x in ([a], b)
    toShowSp _ [] = id
    toShowSp _ (x : []) = toShowS x
    toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs

get :: IOInteract a => SIO a
get = uncurry (flip (liftM2 seq . StateT.put) . return) =<< fmap convert . getRemain =<< StateT.get
put :: IOInteract a => a -> SIO ()
put = lift . (hPutStr stdout) . toShow
putln :: IOInteract a => a -> SIO ()
putln = lift . (hPutStrLn stdout) . toShow
flush :: SIO ()
flush = lift (hFlush stdout)

main :: IO ()
main = StateT.evalStateT main_ C.empty

main_ :: SIO ()
-------------------------------------------- template ------------------------------------------------------
-- for io performance comparison from @Russell_Emerine's code
main_ = get >>= flip replicateM get >>= putln . solve 31

solve :: Int -> [Int] -> Int
solve (-1) _ = 0
solve _ [] = bit 31
solve p xs
	| all (flip testBit p) xs || all (not.flip testBit p) xs = solve p' (f xs)
	| otherwise = bit p .|. min (solve p' $ f $ filter (flip testBit p) xs) (solve p' $ f $ filter (not.flip testBit p) xs)
	where
		p' = p - 1
		f = map (.&. complement (bit p))

{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE TypeFamilies  #-}

import           Data.Bits
import           Data.List
import           Data.Word

main = do
  _ <- getLine
  ns <- fmap read . words <$> getLine :: IO [Word32]
  let bs = w2bs <$> ns
  -- print $ ixRecurse 32 ns
  print . bs2w $ structuralRecurse bs
  -- print . bs2w $ hyloRecurse bs

ixRecurse :: Int -> [Word32] -> Word32
ixRecurse 0 _ = 0
ixRecurse i [] = 0
ixRecurse i ns = go (i-1) zs os
  where
    go i [] [] = 0
    go i [] on = ixRecurse i ns
    go i zs [] = ixRecurse i zs
    go i zs os = min (ixRecurse i zs) (ixRecurse i os) + 2^i
    (zs,os) = partition (\x -> ((bit (i-1)) .&. x) /= 0) ns

data Bit = O | I
  deriving (Show, Eq, Ord)

structuralRecurse :: [[Bit]] -> [Bit]
structuralRecurse ns = go zs os
  where
    go [] [] = []
    go [] os = O:structuralRecurse (tail <$> os)
    go zs [] = O:structuralRecurse (tail <$> zs)
    go zs os = I:min (structuralRecurse . fmap tail $ zs) (structuralRecurse . fmap tail $ os)
    (zs, os) = partition (\x -> head x == O) . filter (not . null) $ ns

data BTreeF b = NodeF b b | EmptyF
  deriving (Functor, Show)

hyloRecurse :: [[Bit]] -> [Bit]
hyloRecurse = hylo alg coalg
  where
--    alg :: BTreeF a [Bit] -> [Bit]
alg EmptyF        = return O
alg (NodeF zs os) = I:min (zs) (os)
--    coalg :: [[Bit]] -> BTreeF [a] [[Bit]]
coalg [] = EmptyF
coalg ns = fmap tail <$> (NodeF zs os)
      where
        (zs, os) = partition (\x -> head x == O) . filter (not . null) $ ns

bs2w :: [Bit] -> Word32
bs2w bs = go 0 bs
  where
    go acc []     = acc
    go acc (I:bs) = go ((shiftL acc 1) .|. 1) bs
    go acc (O:bs) = go (shiftL acc 1) bs

w2bs :: Word32 -> [Bit]
w2bs w = fmap (\n -> if (bit n .&. w) /= 0 then I else O) [4,3..0]

hylo :: Functor f => (f b -> b) -> (a -> f a) -> a -> b
hylo f g = h where h = f . fmap h . g

{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE TypeFamilies  #-}

import           Data.Bits
import           Data.List
import           Data.Word

main = do
  _ <- getLine
  ns <- fmap read . words <$> getLine :: IO [Word32]
  let bs = w2bs <$> ns
  -- print $ ixRecurse 32 ns
  -- print . bs2w $ structuralRecurse bs
  print . bs2w $ hyloRecurse bs

ixRecurse :: Int -> [Word32] -> Word32
ixRecurse 0 _ = 0
ixRecurse i [] = 0
ixRecurse i ns = go (i-1) zs os
  where
    go i [] [] = 0
    go i [] on = ixRecurse i ns
    go i zs [] = ixRecurse i zs
    go i zs os = min (ixRecurse i zs) (ixRecurse i os) + 2^i
    (zs,os) = partition (\x -> ((bit (i-1)) .&. x) /= 0) ns

data Bit = O | I
  deriving (Show, Eq, Ord)

structuralRecurse :: [[Bit]] -> [Bit]
structuralRecurse ns = go zs os
  where
    go [] [] = return O
    go [] os = structuralRecurse (tail <$> os)
    go zs [] = structuralRecurse (tail <$> zs)
    go zs os = I:min (structuralRecurse zs) (structuralRecurse os)
    (zs, os) = partition (\x -> head x == O) . filter (not . null) $ ns

data BTreeF a b = NodeF a b b | EmptyF
  deriving (Functor, Show)

hyloRecurse :: [[Bit]] -> [Bit]
hyloRecurse = hylo alg coalg
  where
    alg EmptyF          = return O
    alg (NodeF a zs os) = I:min zs os
    coalg [] = EmptyF
    coalg ns = NodeF [] zs os
      where
        (zs, os) = partition (\x -> head x == O) . filter (not . null) $ ns

bs2w :: [Bit] -> Word32
bs2w bs = go 0 bs
  where
    go acc []     = acc
    go acc (I:bs) = go ((shiftL acc 1) .|. 1) bs
    go acc (O:bs) = go (shiftL acc 1) bs

w2bs :: Word32 -> [Bit]
w2bs w = fmap (\n -> if (bit n .&. w) /= 0 then I else O) [31,30..0]

hylo :: Functor f => (f b -> b) -> (a -> f a) -> a -> b
hylo f g = h where h = f . fmap h . g


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

del _ [] = []
del x (m:ms) | x==m = ms
             | otherwise = m : ( del x ms)

process [s] _ = s
process x (a:as) = process (del a x) as

main = do
	getLine
	a<- map (fst.fromJust.C.readInt).C.words <$> C.getLine ::IO [Int]
	let b = foldl (\acc z-> I.insertWith (+) z 1 acc) I.empty a
	let e =  I.keys $  I.filter (==( I.foldl max 0 b))  b
	print $ process e (reverse a)

import Control.Applicative
import Data.List
import qualified Data.IntMap as I

del _ [] = []
del x (m:ms) | x==m = ms
             | otherwise = m : ( del x ms)

process [s] _ = s
process x (a:as) = process (del a x) as

main = do
	getLine
	a<- map read.words <$> getLine ::IO [Int]
	let b = foldl (\acc z-> I.insertWith (+) z 1 acc) I.empty a
	let c =  I.elems b
	let d = maximum c
	let e =map fst $  filter (\z-> snd z ==d) $ I.assocs b
	print $ process e (reverse a)

import Data.List
main = do
    n <- readLn :: IO Int
    a <- fmap ((map read) . words) getLine :: IO[Int]
    let arr = nub a
        (_,ans) = maximum . map (\x -> ((fn (0,0) x (zip a [1..])),x)) $ arr
    print ans

fn :: (Int,Int) -> Int -> [(Int,Int)] -> (Int,Int)
fn ans _ [] = ans
fn (mx,ls) e ((x,i):xs)
 |e==x = fn (mx+1,-i) e xs
 |otherwise = fn (mx,ls) e xs

module Main where

-- (num,likes,step)
red :: ([(Int, Int,Int)], Int) -> Int -> ([(Int,Int,Int)], Int)
red (list, step) like =
        let
                addLike num step st [] = (num,1,step):st
                addLike num step st ((n,l,s):xs) | n == num = ((n,l+1,step):st)++xs
                                                 | otherwise = addLike num step ((n,l,s):st) xs
        in (addLike like step [] list, step + 1)

findBest (x:xs) =
        let
                helper best [] = best
                helper best@(n,l,s) ((n',l',s'):xs) | l' > l = helper (n',l',s') xs
                                                    | l' == l && s > s' = helper (n',l',s') xs
                                                    | otherwise = helper best xs
                (bst,_,_) = helper x xs
        in
                bst

main = do
        n <-(getLine >>= (return.read)) :: IO Int
        likes <- (getLine >>= (return . words) >>= (return . (map read))) :: IO [Int]
        let (formatted, _) = foldl red ([],0) likes
--      putStrLn $ show formatted
        putStrLn $ show $ findBest  formatted

import Data.List
import Data.Ord

main = interact $ show . go . map read . words . head . tail . lines

go :: [Int] -> Int
go al = let ids = nub al
            lks = zip al [1..]
            il = map (\i -> filter ((i==). fst) lks) ids
            mxl = maximum $ map length il
        in fst . minimumBy (comparing snd) . map (maximumBy (comparing snd)) $ filter ((mxl==). length) il

module Main where

import Data.Ord
import Data.List
import Data.Function

main :: IO ()
main = interact (show . solve . tail . map read . words)

solve :: [Int] -> Int
solve list = maximumBy comparator list where
				comparator = \x y -> case compare (count x list) (count y list) of
					LT -> LT
					GT -> GT
					EQ -> compare (lastIndexOf y list) (lastIndexOf x list)

lastIndexOf :: Int -> [Int] -> Int
lastIndexOf x = fst . last . filter ((==) x . snd) . zip [0..]

count :: Int -> [Int] -> Int
count x = length . filter (==x)

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

del _ [] = []
del x (m:ms) | x==m = ms
             | otherwise = m : ( del x ms)

process [s] _ = s
process x (a:as) = process (del a x) as

main = do
	getLine
	a<- map read.words <$> getLine ::IO [Int]
	let b = accumArray (+) 0 (1,1000000) $ zip a (repeat 1)
	let c =  elems b
	let d = maximum c
	let e =map fst $  filter (\z-> snd z ==d) $ assocs b
	print $ process e (reverse a)

import Data.List
import Data.Functor
import Data.Function (on)

main :: IO()
main = do
    _ <- getLine
    a <- words <$> getLine
    let ai = sort $ zip a [1..]
        gai = groupBy ((==) `on` fst) ai
        lai = map (\x -> (negate (length x), (snd (last x), fst (head x)))) gai
        sai = sort lai
    putStrLn $ snd $ snd $ head sai


import Data.List
import System.IO

readInteger:: IO Int
readInteger = readLn

readIntegers 0 = return []
readIntegers n = do
    x <- readInteger
    rest <- readIntegers (n - 1)
    return (x : rest)

process e o = if el > ol
    then take (max (el - ol - 1) 0) e
    else take (max (ol - el - 1) 0) o
    where
        ol = length o
        el = length e

solve l = sum (process (sort (filter even l)) (sort (filter odd l)))

sanitize = map read . words

main = do
    readInteger
    input <- getLine
    putStrLn (show (solve (sanitize input)))

import Data.List
process o e
  | (length e) > (length o) = sum (drop ((length o) + 1) e)
  | otherwise = sum (drop ((length e) + 1) o)
main = do
  _ <- getLine
  line <- getLine
  let
    a = map read $ words $ line
    o = reverse $ sort $ filter odd a
    e = reverse $ sort $ filter even a
  putStrLn $ show $ process o e

import Data.Bifunctor
import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Data.List
import Control.Arrow

solve x =
    let f x = (length x, sort x)
        (a,b) =  arr (uncurry min) &&& arr (uncurry max)  $ bimap f f $ partition ((/=0).(`mod`2)) x
    in sum $ drop (succ $ fst a) $ reverse $ snd b

main = print =<< solve . map (fst . fromJust . B.readInt) . B.words <$> (getLine >> B.getLine)

import Data.List
main = interact $ show . solve . map read . tail . words
solve as | le > lo = sum (drop (lo+1) e)
         | otherwise = sum (drop (le+1) o)
  where (e,o) = partition even (reverse (sort as))
        le = length e
        lo = length o

import Data.List ( sortOn, partition )
import Data.Ord  ( Down(..))

main :: IO ()
main = interact $ show . parity . fmap read . tail . words

parity :: [Integer] -> Integer
parity = minimize . leftover . partition even . sortOn Down

minimize :: [Integer] -> Integer
minimize [] = 0
minimize ns = sum $ tail ns

leftover :: ([Integer], [Integer]) -> [Integer]
leftover (evens, odds) | length evens > length odds = annihilate evens odds
                       | otherwise = annihilate odds evens

annihilate :: [a] -> [a] -> [a]
annihilate bigger smaller = drop (length smaller) bigger

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

getSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int

ru, ri :: C.ByteString -> Int

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

solve (n:a) = sum x' + sum y'
  where
    (b, c) = partition odd a
    x = reverse $ sort b
    y = reverse $ sort c
    lx = length x
    ly = length y
    l = succ $ min lx ly
    x' = drop l x
    y' = drop l y

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


import           Data.Bits
import           Data.Array.ST.Safe
import           Data.Array
import           Data.Array.MArray.Safe
import           Control.Monad.ST.Safe
--import           Debug.Trace
import           Control.Monad

pairs :: [a] -> [(a, a)]
pairs []           = []
pairs (x : y : xs) = (x, y) : pairs xs

build :: [[Int]] -> Bool -> [[Int]]
build tree@([t] : ts) fn = tree
build tree@(t : ts) doOr =
    let fn        = if doOr then (.|.) else xor
        nextLevel = map (uncurry fn) (pairs t) :: [Int]
    in  build (nextLevel : tree) (not doOr)

-- Head of tree at position idx is updated to newval.
-- Compute new value for next level of the tree.
update :: [STUArray s Int Int] -> Int -> Int -> Bool -> ST s ()
update [t] 0 newval _ = writeArray t 0 newval
update (t : ts) idx newval doOr = do
    let fn   = if doOr then (.|.) else xor
        idx' = idx `div` 2
    writeArray t idx newval
    i1 <- readArray t (idx' * 2)
    i2 <- readArray t (idx' * 2 + 1)
    let newval' = i1 `fn` i2
    update ts idx' newval' (not doOr)

g :: [STUArray s Int Int] -> [(Int, Int)] -> ST s [Int]
g mtree []                   = return []
g mtree ((idx, newval) : qs) = do
    update mtree idx newval True
    ret  <- readArray (last mtree) 0
    rest <- g mtree qs
    return $ ret : rest

f :: [Int] -> [[Int]] -> [Int]
f as queries =
    let tree     = reverse $ build [as] True
        tree'    = [ listArray (0, length t - 1) t | t <- tree ]
        queries' = [ (idx - 1, val) | [idx, val] <- queries ]
    in  runST $ do
            mtree <- mapM thaw tree'
            g mtree queries'

main'' = do
    let as      = [1 .. 2 ^ 17]
        queries = [ [i, i] | i <- [1 .. 10000] ]
    print $ f as queries

main' = do
    let as      = [1, 6, 3, 5]
        queries = [[1, 4], [3, 4], [1, 2], [1, 2]]
    putStrLn $ (unlines . map show) (f as queries)

main = do
    [n, m]  <- map read . words <$> getLine :: IO [Int]
    as      <- map read . words <$> getLine :: IO [Int]
    queries <- map (map read . words) . lines <$> getContents :: IO [[Int]]
    putStrLn $ (unlines . map show) (f as queries)

import Control.Monad (liftM, replicateM)
import Data.Array.IO
import Data.Array.ST
import Data.Array.Unboxed
import Data.Bits ((.|.), xor)
import Data.Char (isSpace)
import Prelude hiding (or, reads)

type Tree  =  UArray Int Int

(?) :: Bool -> a -> a -> a
(?) p a b  =  if p then a else b

readPair :: IO (Int, Int)
readPair  =  do
    x  <-  readInt
    y  <-  readInt
    return (x, y)

readInt :: IO Int
readInt  =  do
    c  <-  getChar
    isSpace c ? readInt $ readInt' (fromEnum c - fromEnum '0')
  where
    readInt' a  =  do
        c  <-  getChar
        isSpace c ? return a $ readInt' (10*a + fromEnum c - fromEnum '0')

or :: Int -> Int -> Int
or  =  (.|.)

level :: Int -> Int
level n  =  truncate (1e-07 + log (fromIntegral n) / log 2)

fInLevel :: Int -> Int -> (Int -> Int -> Int)
fInLevel n i
  | odd (n + level i)  =  or
  | otherwise  =  xor

createTree :: Int -> [Int] -> Tree
createTree n as  =  runSTUArray $ do
    tree  <-  newArray_ (1, 2^(n + 1) - 1)
    sequence_ [writeArray tree i x
                | (i, x) <- zip [2^n..] as]
    sequence_
      [
        do
          a  <-  readArray tree (2*i)
          b  <-  readArray tree (2*i+1)
          writeArray tree i (fInLevel n i a b)
        | i <- [2^n-1, 2^n-2 .. 1]
      ]
    return tree

solve :: Int -> [Int] -> [(Int, Int)] -> IO ()
solve n as qs  =  do
    let tree  =  createTree n as
    tree'  <-  unsafeThaw tree
    mapM_ (solve' tree')
        $ map (\(x, y) -> (x + 2^n - 1, y)) qs
  where
    solve' :: IOUArray Int Int -> (Int, Int) -> IO ()
    solve' array (1, d)  =  print d
    solve' array (i1, d1)  =  do
        let i0  =  i1 `div` 2
        let i2  =  if odd i1 then i1 - 1 else i1 + 1
        d2  <-  readArray array i2
        let d0  =  fInLevel n i0 d1 d2
        writeArray array i1 d1
        solve' array (i0, d0)

main :: IO ()
main  =  do
    (n, m)  <-  readPair
    as  <-  replicateM (2^n) readInt
    qs  <-  replicateM m readPair
    solve n as qs

import           Data.Bits
import           Data.Array.ST.Safe
import           Data.Array
import           Data.Array.MArray.Safe
import           Control.Monad.ST.Safe
--import           Debug.Trace
import           Control.Monad

pairs :: [a] -> [(a, a)]
pairs []           = []
pairs (x : y : xs) = (x, y) : pairs xs

build :: [[Int]] -> Bool -> [[Int]]
build tree@([t] : ts) fn = tree
build tree@(t : ts) doOr =
    let fn        = if doOr then (.|.) else xor
        nextLevel = map (uncurry fn) (pairs t) :: [Int]
    in  build (nextLevel : tree) (not doOr)

-- Head of tree at position idx is updated to newval.
-- Compute new value for next level of the tree.
update :: [STArray s Int Int] -> Int -> Int -> Bool -> ST s ()
update [t] 0 newval _ = do
    --tOld <- getElems t
    writeArray t 0 newval
    --tNew <- getElems t
    --traceM $ show tOld ++ " -> " ++ show tNew
    return ()
update (t : ts) idx newval doOr = do
    let fn   = if doOr then (.|.) else xor
        idx' = idx `div` 2
    --tOld <- getElems t
    writeArray t idx newval
    --tNew <- getElems t
    --traceM $ show tOld ++ " -> " ++ show tNew
    i1 <- readArray t (idx' * 2)
    i2 <- readArray t (idx' * 2 + 1)
    let newval' = i1 `fn` i2
    update ts idx' newval' (not doOr)

--g :: [Array Int Int] -> [[Int]] -> [Int]
--g _ [] = []
--g tree ([idx, newval] : qs) =
--    let (ret, tree') = update tree (idx - 1) newval True in ret : g tree' qs

g :: [STArray s Int Int] -> [(Int, Int)] -> ST s [Int]
g mtree []                   = return []
g mtree ((idx, newval) : qs) = do
    update mtree idx newval True
    --t <- mapM getElems mtree
    --traceShowM t
    ret  <- readArray (last mtree) 0
    rest <- g mtree qs
    return $ ret : rest

f :: [Int] -> [[Int]] -> [Int]
f as queries =
    let tree     = reverse $ build [as] True
        tree'    = [ listArray (0, length t - 1) t | t <- tree ]
        queries' = [ (idx - 1, val) | [idx, val] <- queries ]
    in  runST $ do
            mtree <- mapM thaw tree'
            g mtree queries'

--main = do
--    let as      = [1 .. 2 ^ 17]
--        queries = [ [1, 0] | _ <- [1 .. 10000] ]
--    print $ f as queries

main = do
    let as      = [1, 6, 3, 5]
        queries = [[1, 4], [3, 4], [1, 2], [1, 2]]
    putStrLn $ (unlines . map show) (f as queries)

main' = do
    [n, m]  <- map read . words <$> getLine :: IO [Int]
    as      <- map read . words <$> getLine :: IO [Int]
    queries <- map (map read . words) . lines <$> getContents :: IO [[Int]]
    putStrLn $ (unlines . map show) (f as queries)

import           Data.Bits
import           Data.Array.ST.Safe
import           Data.Array
import           Data.Array.MArray.Safe
import           Control.Monad.ST.Safe

pairs :: [a] -> [(a, a)]
pairs []           = []
pairs (x : y : xs) = (x, y) : pairs xs

build :: [[Int]] -> Bool -> [[Int]]
build tree@([t] : ts) fn = tree
build tree@(t : ts) doOr =
    let fn        = if doOr then (.|.) else xor
        nextLevel = map (uncurry fn) (pairs t) :: [Int]
    in  build (nextLevel : tree) (not doOr)

-- Head of tree at position idx is updated to newval.
-- Compute new value for next level of the tree.
update :: [STArray s Int Int] -> Int -> Int -> Bool -> ST s ()
update [t     ] 0   newval _    = writeArray t 0 newval
update (t : ts) idx newval doOr = do
    let fn   = if doOr then (.|.) else xor
        idx' = idx `div` 2
    writeArray t idx newval
    i1 <- readArray t (idx' * 2)
    i2 <- readArray t (idx' * 2 + 1)
    let newval' = i1 `fn` i2
    update ts idx' newval' (not doOr)

--g :: [Array Int Int] -> [[Int]] -> [Int]
--g _ [] = []
--g tree ([idx, newval] : qs) =
--    let (ret, tree') = update tree (idx - 1) newval True in ret : g tree' qs

g :: [STArray s Int Int] -> [[Int]] -> ST s [Int]
g mtree []                   = return []
g mtree ([idx, newval] : qs) = do
    update mtree idx newval True
    ret  <- readArray (last mtree) 0
    rest <- g mtree qs
    return $ ret : rest

f :: [Int] -> [[Int]] -> [Int]
f as queries =
    let tree  = reverse $ build [as] True
        tree' = [ listArray (0, length t - 1) t | t <- tree ]
    in  runST $ do
            mtree <- mapM thaw tree'
            g mtree queries

--main = do
--    let as      = [1 .. 2 ^ 17]
--        queries = [ [1, 0] | _ <- [1 .. 10000] ]
--    print $ f as queries

main = do
    [n, m]  <- map read . words <$> getLine :: IO [Int]
    as      <- map read . words <$> getLine :: IO [Int]
    queries <- map (map read . words) . lines <$> getContents :: IO [[Int]]
    putStrLn $ (unlines . map show) (f as queries)

import           Data.Bits
import           Data.Array.ST.Safe
import           Data.Array
import           Data.Array.MArray.Safe
import           Control.Monad.ST.Safe
--import           Debug.Trace
import           Control.Monad

pairs :: [a] -> [(a, a)]
pairs []           = []
pairs (x : y : xs) = (x, y) : pairs xs

build :: [[Int]] -> Bool -> [[Int]]
build tree@([t] : ts) fn = tree
build tree@(t : ts) doOr =
    let fn        = if doOr then (.|.) else xor
        nextLevel = map (uncurry fn) (pairs t) :: [Int]
    in  build (nextLevel : tree) (not doOr)

-- Head of tree at position idx is updated to newval.
-- Compute new value for next level of the tree.
update :: [STUArray s Int Int] -> Int -> Int -> Bool -> ST s ()
update [t] 0 newval _ = writeArray t 0 newval
update (t : ts) idx newval doOr = do
    let fn   = if doOr then (.|.) else xor
        idx' = idx `div` 2
    writeArray t idx newval
    i1 <- readArray t (idx' * 2)
    i2 <- readArray t (idx' * 2 + 1)
    let newval' = i1 `fn` i2
    update ts idx' newval' (not doOr)

g :: [STUArray s Int Int] -> [(Int, Int)] -> ST s [Int]
g mtree []                   = return []
g mtree ((idx, newval) : qs) = do
    update mtree idx newval True
    ret  <- readArray (last mtree) 0
    rest <- g mtree qs
    return $ ret : rest

f :: [Int] -> [[Int]] -> [Int]
f as queries =
    let tree     = reverse $ build [as] True
        tree'    = [ listArray (0, length t - 1) t | t <- tree ]
        queries' = [ (idx - 1, val) | [idx, val] <- queries ]
    in  runST $ do
            mtree <- mapM thaw tree'
            g mtree queries'

main = do
    let as      = [1 .. 2 ^ 17]
        queries = [ [i, i] | i <- [1 .. 10000] ]
    print $ f as queries

main' = do
    let as      = [1, 6, 3, 5]
        queries = [[1, 4], [3, 4], [1, 2], [1, 2]]
    putStrLn $ (unlines . map show) (f as queries)

main'' = do
    [n, m]  <- map read . words <$> getLine :: IO [Int]
    as      <- map read . words <$> getLine :: IO [Int]
    queries <- map (map read . words) . lines <$> getContents :: IO [[Int]]
    putStrLn $ (unlines . map show) (f as queries)

import Control.Monad (liftM, replicateM)
import Data.Array.IO
import Data.Array.ST
import Data.Array.Unboxed
import Data.Bits ((.|.), xor)
import Data.Char (isSpace)
import Prelude hiding (or, reads)

type Tree  =  UArray Int Int

(?) :: Bool -> a -> a -> a
(?) p a b  =  if p then a else b

readPair :: IO (Int, Int)
readPair  =  do
    x  <-  readInt
    y  <-  readInt
    return (x, y)

readInt :: IO Int
readInt  =  do
    c  <-  getChar
    isSpace c ? readInt $ readInt' (fromEnum c - fromEnum '0')
  where
    readInt' a  =  do
        c  <-  getChar
        isSpace c ? return a $ readInt' (10*a + fromEnum c - fromEnum '0')

or :: Int -> Int -> Int
or  =  (.|.)

level :: Int -> Int
level n  =  truncate (log (fromIntegral n) / log 2)

fInLevel :: Int -> Int -> (Int -> Int -> Int)
fInLevel n i
  | odd (n + level i)  =  or
  | otherwise  =  xor

createTree :: Int -> [Int] -> Tree
createTree n as  =  runSTUArray $ do
    tree  <-  newArray_ (1, 2^(n + 1) - 1)
    sequence_ [writeArray tree i x
                | (i, x) <- zip [2^n..] as]
    sequence_
      [
        do
          a  <-  readArray tree (2*i)
          b  <-  readArray tree (2*i+1)
          writeArray tree i (fInLevel n i a b)
        | i <- [2^n-1, 2^n-2 .. 1]
      ]
    return tree

solve :: Int -> [Int] -> [(Int, Int)] -> IO ()
solve n as qs  =  do
    let tree  =  createTree n as
    tree'  <-  unsafeThaw tree
    mapM_ (solve' tree')
        $ map (\(x, y) -> (x + 2^n - 1, y)) qs
  where
    solve' :: IOUArray Int Int -> (Int, Int) -> IO ()
    solve' array (1, d)  =  print d
    solve' array (i1, d1)  =  do
        let i0  =  i1 `div` 2
        let i2  =  if odd i1 then i1 - 1 else i1 + 1
        d2  <-  readArray array i2
        let d0  =  fInLevel n i0 d1 d2
        writeArray array i1 d1
        solve' array (i0, d0)

main :: IO ()
main  =  do
    (n, m)  <-  readPair
    as  <-  replicateM (2^n) readInt
    qs  <-  replicateM m readPair
    solve n as qs

import Control.Monad (liftM, replicateM)
import Data.Array.IO
import Data.Array.ST
import Data.Array.Unboxed
import Data.Bits ((.|.), xor)
import Prelude hiding (or, reads)

type Tree  =  UArray Int Int

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

readPair :: Read a => IO (a, a)
readPair  =  do
    [x, y]  <-  reads
    return (x, y)

or :: Int -> Int -> Int
or  =  (.|.)

level :: Int -> Int
level n  =  truncate (log (fromIntegral n) / log 2)

fInLevel :: Int -> Int -> (Int -> Int -> Int)
fInLevel n i
  | odd (level i + n)  =  or
  | otherwise  =  xor

createTree :: Int -> [Int] -> Tree
createTree n as  =  runSTUArray $ do
    tree  <-  newArray_ (1, 2^(n + 1) - 1)
    sequence_ [writeArray tree i x
                | (i, x) <- zip [2^n..] as]
    sequence_
      [
        do
          a  <-  readArray tree (2*i)
          b  <-  readArray tree (2*i+1)
          writeArray tree i (fInLevel n i a b)
        | i <- [2^n-1, 2^n-2 .. 1]
      ]
    return tree

solve :: Int -> [Int] -> [(Int, Int)] -> IO ()
solve n as qs  =  do
    let tree  =  createTree n as
    tree'  <-  unsafeThaw tree
    mapM_ (solve' tree')
        $ map (\(x, y) -> (x + 2^n - 1, y)) qs
  where
    solve' :: IOUArray Int Int -> (Int, Int) -> IO ()
    solve' array (1, d)  =  print d
    solve' array (i1, d1)  =  do
        let i0  =  i1 `div` 2
        let i2  =  if odd i1 then i1 - 1 else i1 + 1
        d2  <-  readArray array i2
        let d0  =  fInLevel n i0 d1 d2
        writeArray array i0 d0
        solve' array (i0, d0)

main :: IO ()
main  =  do
    {-
    let n  =  17
    let m  =  100000
    let as  =  [1 .. 2^n]
    let qs  =  take m $ cycle [(i, 0) | i <- as]
    -}
    [n, m]  <-  reads
    as  <-  reads
    qs  <-  replicateM m readPair
    solve n as qs


upperBound n l = last $ takeWhile (<= n) l

cards = scanl (\cum n -> cum + 3 * n - 1) 0 [1..]

f :: Int -> Int
f n | n < 2     = 0
    | otherwise = 1 + f (n - (upperBound n cards))

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

findMaxSize :: Int -> Int
findMaxSize p = floor $ (sqrt (24 * fromIntegral p + 1) -1)/6

size :: Int -> Int
size h = (h * (3*h + 1)) `div` 2

solve :: Int -> Int
solve p
    | m == 0    = 0
    | otherwise = 1 + solve (p- size m)
    where
        m = findMaxSize p

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    (p:_) <- readNums
    print $ solve p
    testCases (t-1)

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

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

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


import Control.Arrow ((>>>))

main :: IO ()
main =
  interact $
    lines
      >>> last
      >>> solve 1 0 0 0
      >>> show
      >>> (++ "\n")

myMod :: Integer
myMod = 10 ^ 9 + 7

madd :: Integer -> Integer -> Integer
madd a b = (a + b) `mod` myMod

mmul :: Integer -> Integer -> Integer
mmul a b = (a * b) `mod` myMod

solve :: Integer -> Integer -> Integer -> Integer -> String -> Integer
solve _ _ _ abc [] = abc
solve n a ab abc (x : xs)
  | x == 'a' = solve n (madd a n) ab abc xs
  | x == 'b' = solve n a (madd ab a) abc xs
  | x == 'c' = solve n a ab (madd abc ab) xs
  | x == '?' =
    solve
      (mmul 3 n)
      (madd (mmul 3 a) n)
      (madd (mmul 3 ab) a)
      (madd (mmul 3 abc) ab)
      xs

import Data.List

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

sp :: Int -> Int -> Int
sp x y = rem (x + y) p

trip :: Int -> Int
trip x = sp x (sp x x)

data State = State !Int !Int !Int !Int

step :: State -> Char -> State
step (State w x y z) c = case  c  of
  'a' -> State w (sp w x) y z
  'b' -> State w x (sp x y) z
  'c' -> State w x y (sp y z)
  '?' -> State (trip w) (sp w $ trip x) (sp x $ trip y) (sp y $ trip z)
  _ -> error "invalid char in input"

solve :: [Char] -> Int
solve li = let
  State _ _ _ ans = foldl' step (State 1 0 0 0) li
  in  ans

main :: IO ()
main = do
  _nStr <- getLine
  s <- getLine
  print $ solve s

import Control.Arrow ((>>>))

main :: IO ()
main =
  interact $
    lines
      >>> last
      >>> solve 1 0 0 0
      >>> show
      >>> (++ "\n")

myMod :: Int
myMod = 10 ^ 9 + 7

madd :: Int -> Int -> Int
madd a b = (a + b) `mod` myMod

mmul :: Int -> Int -> Int
mmul a b = (a * b) `mod` myMod

solve :: Int -> Int -> Int -> Int -> String -> Int
solve _ _ _ abc [] = abc
solve n a ab abc (x : xs)
  | x == 'a' = solve n (madd a 1) ab abc xs
  | x == 'b' = solve n a (madd ab a) abc xs
  | x == 'c' = solve n a ab (madd abc ab) xs
  | x == '?' =
    solve
      (mmul 3 n)
      (madd (mmul 3 a) n)
      (madd (mmul 3 ab) a)
      (madd (mmul 3 abc) ab)
      xs

import Control.Arrow ((>>>))

main :: IO ()
main =
  interact $
    lines
      >>> last
      >>> solve 1 0 0 0
      >>> show
      >>> (++ "\n")

myMod :: Int
myMod = 10 ^ 9 + 7

madd :: Int -> Int -> Int
madd a b = (a + b) `mod` myMod

mmul :: Int -> Int -> Int
mmul a b = (a * b) `mod` myMod

solve :: Int -> Int -> Int -> Int -> String -> Int
solve _ _ _ abc [] = abc
solve n a ab abc (x : xs)
  | x == 'a' = solve n (madd a n) ab abc xs
  | x == 'b' = solve n a (madd ab a) abc xs
  | x == 'c' = solve n a ab (madd abc ab) xs
  | x == '?' =
    solve
      (mmul 3 n)
      (madd (mmul 3 a) n)
      (madd (mmul 3 ab) a)
      (madd (mmul 3 abc) ab)
      xs


import Control.Applicative ((<$>))
import Data.ByteString.Char8 (words, lines, readInt, getLine, getContents, unpack)
import Data.Int (Int64)
import Data.Maybe (fromJust)
import Prelude hiding (words, lines, getLine, getContents)

readInt' = fst . fromJust . readInt
readInts = map readInt' . words <$> getLine

main = do
  getLine
  ps <- fmap (map fromIntegral) readInts :: IO [Int64]
  s <- fmap unpack getLine

  let
    as = scanl (+) 0 $ zipWith (\c p -> if c == 'A' then p else 0) s ps
    bs = scanl (+) 0 $ zipWith (\c p -> if c == 'B' then p else 0) s ps
    s1 = last as
    s2 = last bs

    prefs = zipWith (\a b -> a + s2 - b) as bs
    sufs = zipWith (\a b -> b + s1 - a) as bs

  print $ max (maximum prefs) (maximum sufs)

import qualified Data.ByteString.Char8 as C8
import Data.Maybe

readInteger :: String -> Integer
readInteger s = read s :: Integer

suffixScore :: [Integer] -> String -> [Integer] -> [Integer]
suffixScore [] _ xs = xs
suffixScore _ [] xs = xs
suffixScore (score:scores) (piece:pieces) xs =
  let prev = head xs
      adder = flipValueOf score piece
      newValue = prev + adder
      xs' = (newValue:xs)
  in suffixScore scores pieces xs'

flipValueOf :: Integer -> Char -> Integer
flipValueOf n 'A' = n
flipValueOf n 'B' = (-n)

prefixScore :: [Integer] -> String -> [Integer] -> [Integer]
prefixScore scores pieces xs = suffixScore (reverse scores) (reverse pieces) xs

getInitialScore :: [Integer] -> String -> Integer
getInitialScore scores pieces = sum bsVals
  where bs = ((=='B') . snd ) `filter` (scores `zip` pieces)
        bsVals = map fst bs

main :: IO()
main = do
    n <- getLine >>= return . readInteger
    line <- C8.getLine
    pieces <- getLine
    let
        scores = map (fst . fromJust . C8.readInteger) (C8.words line)
        initialScore = getInitialScore scores pieces
        suffixScores = suffixScore scores pieces [initialScore]
        prefixScores = prefixScore scores pieces [initialScore]
    putStrLn $ show $ (foldl1 max) (suffixScores ++ prefixScores)


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
-- readInt :: B.ByteString -> Int
-- readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  [n,m,k] <- map read.words <$> getLine
  bs <- B.concat.B.words <$> B.getContents
  let !arr = solve n m bs
  putStrLn.unwords $ map (show.unsafeAt arr) [0..m-1]

solve :: Int -> Int -> B.ByteString -> UArray Int Int
solve n m bs = runSTUArray $ do
  marr <- newArray (0, m - 1) 0 :: ST s (STUArray s Int Int)
  rep n $ \i -> do
    rep m $ \j -> do
      case B.index bs (i * m + j) of
        'U' | even i     -> unsafeModify marr j       (1+)
        'R' | j + i < m  -> unsafeModify marr (j + i) (1+)
        'L' | 0 <= j - i -> unsafeModify marr (j - i) (1+)
        _                -> return ()
  return marr

import Data.Array.IO
import Data.IORef
import Control.Monad
import Data.Tuple
import Data.List
import Data.Char
import qualified Data.ByteString.Lazy as B

parse :: B.ByteString -> [Int]
parse s = do
	q <- B.splitWith (\x-> x == 13 || x == 10 || x == 32) s
	if B.length q == 0 then
		[]
	else
		return $ foldl' (\a b-> a * 10 + (fromIntegral b) - (ord '0')) 0 (B.unpack q)

main :: IO ()
main = do
	n:m:k:_ <- liftM (map read) $ liftM words getLine
	s <- (((forM (replicate n 0) $ \_ -> getLine >>= (newListArray (0, m-1)))) >>= (newListArray (0, n-1))) :: IO (IOArray Int (IOArray Int Char))
	r <- ((newArray (0, m-1) 0) :: IO (IOArray Int Int))
	forM_ [0..(n-1)] $ \i -> do
		line <- readArray s i
		forM_ [0..(m-1)] $ \j -> do
			p <- readArray line j
			case p of
				'D' -> return ()
				'U' ->
					if i `mod` 2 == 0 then do
						q <- readArray r j
						writeArray r j (q + 1)
					else return ()
				'L' -> do
					let jj = j - i
					if jj >= 0 && jj < m then do
						q <- readArray r jj
						writeArray r jj (q + 1)
					else return ()
				'R' -> do
					let jj = j + i
					if jj >= 0 && jj < m then do
						q <- readArray r jj
						writeArray r jj (q + 1)
					else return ()
				_ -> return ()
			--qqq <- getElems r
			--putStrLn $ show (i, j, i `mod` 2 > 0, p, qqq)
	rr <- getElems r
	putStrLn $ concat $ map (\x -> (show x) ++ " ") rr

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
-- readInt :: B.ByteString -> Int
-- readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  [n,m,k] <- map read.words <$> getLine
  bs <- B.concat.B.words <$> B.getContents
  let !arr = solve n m bs
  putStrLn.unwords $ map (show.unsafeAt arr) [0..m-1]

solve :: Int -> Int -> B.ByteString -> UArray Int Int
solve n m bs = runSTUArray $ do
  marr <- newArray (0,m-1) 0 :: ST s (STUArray s Int Int)
  rep n $ \i-> do
    rep m $ \j-> do
      case B.index bs (i*m+j) of
        'U' | i > 1           -> unsafeModify marr j     (1+)
        'R' | i+j < m         -> unsafeModify marr (i+j) (1+)
        'L' | 0 <= j-i, j-i<m -> unsafeModify marr (j-i) (1+)
        _                     -> return ()
  return marr

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
-- readInt :: B.ByteString -> Int
-- readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  [n,m,k] <- map read.words <$> getLine
  bs <- B.concat.B.words <$> B.getContents
  let !arr = solve n m bs
  putStrLn.unwords $ map (show.unsafeAt arr) [0..m-1]

solve :: Int -> Int -> B.ByteString -> UArray Int Int
solve n m bs = runSTUArray $ do
  marr <- newArray (0, m - 1) 0 :: ST s (STUArray s Int Int)
  rep n $ \i -> do
    rep m $ \j -> do
      case B.index bs (i * m + j) of
        'U' | i > 1                         -> unsafeModify marr j       (1+)
        'R' | j + i < m, i > 0              -> unsafeModify marr (j + i) (1+)
        'L' | 0 <= j - i, j - i < m, i > 0  -> unsafeModify marr (j - i) (1+)
        _                                   -> return ()
  return marr