import Control.Monad
import Data.List (words)
import Data.Sequence (Seq,Seq (Empty, (:<|), (:|>)), fromList, (><), (<|), (|>), empty)
import Data.Foldable (toList)

-- ex:
-- 4 4
-- 01?????0

type SChar = Seq Char

calc1 :: SChar -> Int -> Int -> SChar -> SChar -> (Int,Int,SChar)
calc1 Empty a b pref suf = (a,b, pref >< suf)
calc1 ('1' :<| Empty) a b pref suf = (a,b-1, pref >< ('1' <| suf))
calc1 ('0' :<| Empty) a b pref suf = (a-1,b, pref >< ('0' <| suf))
calc1 (x :<| Empty) a b pref suf = (a,b, pref >< (x <| suf))
calc1 s a b pref suf =
  let (x1 :<| xs1) = s
      (xs :|> xn) = xs1
  in
    case (x1,xn) of
      ('?','1') -> calc1 xs a (b-2) (pref |> '1') (xn <| suf)
      ('1','?') -> calc1 xs a (b-2) (pref |> x1) ('1' <| suf)
      ('?','0') -> calc1 xs (a-2) b (pref |> '0') (xn <| suf)
      ('0','?') -> calc1 xs (a-2) b (pref |> x1) ('0' <| suf)
      ('0','0') -> calc1 xs (a-2) b (pref |> x1) (xn <| suf)
      ('1','1') -> calc1 xs a (b-2) (pref |> x1) (xn <| suf)
      (_,_) -> calc1 xs a b (pref |> x1) (xn <| suf)

calc2 :: SChar -> Int -> Int -> SChar -> SChar -> SChar
calc2 Empty a b _ _ | a /= 0 || b /= 0 = fromList "-1"
calc2 Empty 0 0 pref suf = pref >< suf
calc2 ('?':<|Empty) a b pref suf
  | a == 1 && b == 0 = pref >< ('0' <| suf)
  | a == 0 && b == 1 = pref >< ('1' <| suf)
  | otherwise = fromList "-1"
calc2 ('1' :<| Empty) a b pref suf = calc2 empty a b pref ('1' <| suf)
calc2 ('0' :<| Empty) a b pref suf = calc2 empty a b pref ('0' <| suf)
calc2 (x :<| Empty) _ _ _ _ = fromList "-1"

calc2 s a b pref suf | a<0 && b<0 = fromList "-1"
calc2 s a b pref suf =
  let (x1 :<| xs1) = s
      (xs :|> xn) = xs1
  in
    case (x1,xn) of
      ('?','?') | a>1 -> calc2 xs (a-2) b (pref |> '0') ('0' <| suf)
      ('?','?') | b>1 -> calc2 xs a (b-2) (pref |> '1') ('1' <| suf)
      (_,_) -> calc2 xs a b (pref |> x1) (xn <| suf)

calc :: String -> Int -> Int -> String
calc line a b =
  let sq = fromList line
      (a',b',sq') = calc1 sq a b empty empty
  in
    toList $ calc2 sq' a' b' empty empty

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let [a,b] = map read $ words line :: [Int]
    line <- getLine
    --print (a,b,line)
    --print $ calc1 (fromList line) a b empty empty
    putStrLn $ calc line a b

import qualified Data.Map as M
import Data.Map((!))

import qualified Data.Set as S
import qualified Data.List as L

result :: Int -> Int -> String -> String
result a b str'
	| not isP = "-1"
	| a + b /= n = "-1"
	| mod a 2 == 1 && mod b 2 == 1 = "-1"
	| S.size val /= div (a-num0) 2 = "-1"
	| sum [1|s<-solution, s=='0'] /= a = "-1"
	| otherwise = solution
	where
		n = length str'
		num0 = sum [1 | s <- str, s=='0']
		two_ = [i | (i, s) <- zip [0..(div n 2 - 1)] str, s == '?', strM ! (n-1-i) == '?']
		isP = foldr (\i b-> (&&) b $ strM ! i == strM ! (n-1-i)) True $ [0..(div n 2 - 1)]

		strM' = M.fromList $ zip [0..] str'
		strM = M.fromList $ zip [0..] str
		str = fmap aux [0..(n-1)] where
			aux i
				| strM' ! i /= '?' = strM' ! i
				| strM' ! (n-1-i) /= '?' = strM' ! (n-1-i)
				| mod n 2 == 1 && i == div n 2 = if mod a 2 == 0 then '1' else '0'
				| otherwise = '?'

		val = S.fromList $ take (div (a-num0) 2) two_
		aux0 (i, s)
			| s /= '?' = s
			| s == '?' && (S.member i val || S.member (n-1-i) val) = '0'
			| otherwise = '1'

		solution = fmap aux0 $ zip [0..] str

main = do
	t <- getLine >>= return . read :: IO Int

	let loop t = if t==0 then return () else do
		l <- getLine >>= return . (fmap read) . words :: IO [Int]
		let (a, b) = (l !! 0, l !! 1)

		str <- getLine

		putStrLn $ result a b str

		loop $ t - 1

	loop t

import qualified Data.Map as M
import Data.Map((!))

import qualified Data.Set as S
import qualified Data.List as L

result :: Int -> Int -> String -> String
result a b str'
	| not isP = "-1"
	| a + b /= n = "-1"
	| mod a 2 == 1 && mod b 2 == 1 = "-1"
	| length val /= div (a-num0) 2 = "-1"
	| otherwise = fmap aux0 $ zip [0..] str
	where
		n = length str'
		num0 = sum [1 | s <- str, s=='0']
		two_ = [i | (i, s) <- zip [0..(div n 2 - 1)] str, s == '?', str !! (n-1-i) == '?']
		isP = foldr (\i b-> (&&) b $ str !! i == str !! (n-1-i)) True $ [0..(div n 2 - 1)]

		str = fmap aux [0..(n-1)] where
			aux i
				| str' !! i /= '?' = str' !! i
				| str' !! (n-1-i) /= '?' = str' !! (n-1-i)
				| mod n 2 == 1 && i == div n 2 = if mod a 2 == 0 then '1' else '0'
				| otherwise = '?'

		val = take (div (a-num0) 2) two_
		aux0 (i, s)
			| s /= '?' = s
			| s == '?' && (elem i val || elem (n-1-i) val) = '0'
			| otherwise = '1'

main = do
	t <- getLine >>= return . read :: IO Int

	let loop t = if t==0 then return () else do
		l <- getLine >>= return . (fmap read) . words :: IO [Int]
		let (a, b) = (l !! 0, l !! 1)

		str <- getLine

		putStrLn $ result a b str

		loop $ t - 1

	loop t

import Control.Monad
import Data.List (words)
import Data.Sequence (Seq,Seq (Empty, (:<|), (:|>)), fromList, (><), (<|), (|>), empty)
import Data.Foldable (toList)

-- ex:
-- 4 4
-- 01?????0

type SChar = Seq Char

calc1 :: SChar -> Int -> Int -> SChar -> SChar -> (Int,Int,SChar)
calc1 Empty a b pref suf = (a,b, pref >< suf)
calc1 ('1' :<| Empty) a b pref suf = (a,b-1, pref >< ('1' <| suf))
calc1 ('0' :<| Empty) a b pref suf = (a-1,b, pref >< ('0' <| suf))
calc1 (x :<| Empty) a b pref suf = (a,b, pref >< (x <| suf))
calc1 s a b pref suf =
  let (x1 :<| xs1) = s
      (xs :|> xn) = xs1
  in
    case (x1,xn) of
      ('?','1') -> calc1 xs a (b-2) (pref |> '1') (xn <| suf)
      ('1','?') -> calc1 xs a (b-2) (pref |> x1) ('1' <| suf)
      ('?','0') -> calc1 xs (a-2) b (pref |> '0') (xn <| suf)
      ('0','?') -> calc1 xs (a-2) b (pref |> x1) ('0' <| suf)
      ('0','0') -> calc1 xs (a-2) b (pref |> x1) (xn <| suf)
      ('1','1') -> calc1 xs a (b-2) (pref |> x1) (xn <| suf)
      (_,_) -> calc1 xs a b (pref |> x1) (xn <| suf)

calc2 :: SChar -> Int -> Int -> SChar -> SChar -> SChar
calc2 Empty a b _ _ | a /= 0 || b /= 0 = fromList "-1"
calc2 Empty 0 0 pref suf = pref >< suf
calc2 ('?':<|Empty) a b pref suf
  | a == 1 && b == 0 = pref >< ('0' <| suf)
  | a == 0 && b == 1 = pref >< ('1' <| suf)
  | otherwise = fromList "-1"
calc2 ('1' :<| Empty) a b pref suf = calc2 empty a b pref ('1' <| suf)
calc2 ('0' :<| Empty) a b pref suf = calc2 empty a b pref ('0' <| suf)
calc2 (x :<| Empty) _ _ _ _ = fromList "-1"

calc2 s a b pref suf | a<0 && b<0 = fromList "-1"
calc2 s a b pref suf =
  let (x1 :<| xs1) = s
      (xs :|> xn) = xs1
  in
    case (x1,xn) of
      ('?','?') | a>0 -> calc2 xs (a-2) b (pref |> '0') ('0' <| suf)
      ('?','?') | b>0 -> calc2 xs a (b-2) (pref |> '1') ('1' <| suf)
      (_,_) -> calc2 xs a b (pref |> x1) (xn <| suf)

calc :: String -> Int -> Int -> String
calc line a b =
  let sq = fromList line
      (a',b',sq') = calc1 sq a b empty empty
  in
    toList $ calc2 sq' a' b' empty empty

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let [a,b] = map read $ words line :: [Int]
    line <- getLine
    --print (a,b,line)
    --print $ calc1 (fromList line) a b empty empty
    putStrLn $ calc line a b


import Data.Sequence( empty, viewl, spanl, (<|), fromList, null,
			ViewL( EmptyL, (:<)), (><), (|>))
import qualified Data.Sequence as SEQ
main = do
    getLine
    statements_ <- getLine
    let tailSeq seq = case viewl seq    of
			EmptyL		-> empty
			(_:<rem)	-> rem
	drop1stn _ 0 sequence = sequence
	drop1stn e n sequence =
	    case viewl sequence of
		EmptyL	    -> empty
		s:<stRem    -> if e==s
				then drop1stn e (n-1) stRem
				else s<|drop1stn e n stRem
	oppo 'R' = 'D'
	oppo 'D' = 'R'
	proc sequence =
	    let
		s:<stRem = viewl sequence
		(friends, enemyHeaded) = spanl (s==) stRem
		sz = 1 + SEQ.length friends
		nextSeq = (drop1stn (oppo s) sz enemyHeaded) ><
				(s <| friends)
	    in
		if SEQ.null enemyHeaded
		    then [s]
		    else proc nextSeq
    putStr . proc $ fromList statements_

import Data.Sequence( empty, viewl, spanl, (<|), fromList, null,
			ViewL( EmptyL, (:<)), (><), (|>))
import qualified Data.Sequence as SEQ
main = do
    getLine
    statements_ <- getLine
    let tailSeq seq = case viewl seq    of
			EmptyL		-> empty
			(_:<rem)	-> rem
	drop1stn _ _ EmptyL = empty
	drop1stn _ 0 (s:<stRem) = s<|stRem
	drop1stn e n (s:<stRem)
	  | e==s		= drop1stn e (n-1) (viewl stRem)
	  | otherwise		= s<|drop1stn e n (viewl stRem)
	oppo 'R' = 'D'
	oppo 'D' = 'R'
	proc (s:<stRem) =
	    let
		(friends, enemyHeaded) = spanl (s==) stRem
		sz = 1 + SEQ.length friends
		nextSeq = (drop1stn (oppo s) sz$viewl enemyHeaded) ><
				(s <| friends)
	    in
		if SEQ.null enemyHeaded
		    then [s]
		    else proc $ viewl nextSeq
    putStr . proc . viewl $ fromList statements_

simulate = walk "" 0
  where walk past future []
          | all (== head past) past = [head past]
          | otherwise               = walk "" future $ reverse past
        walk past future ('D' : s)
          | future < 0 = walk past (future+1) s
          | otherwise  = walk ('D' : past) (future+1) s
        walk past future ('R' : s)
          | future > 0 = walk past (future-1) s
          | otherwise  = walk ('R' : past) (future-1) s

main = do
  s <- getContents
  let voters = lines s !! 1
  putStrLn $ simulate voters

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

main = do
    n <- read `fmap` getLine :: IO Int
    s <- zip [0..] `fmap` getLine
    let (d, r) = partition (\(_,c) -> c == 'D') s
    let d' = S.fromList $ map fst d
    let r' = S.fromList $ map fst r
    let (d'', r'') = fight n d' r'
    if S.length d'' == 0
    then putStrLn "R"
    else putStrLn "D"

type Queue = S.Seq Int

fight :: Int -> Queue -> Queue -> (Queue, Queue)
fight n d r
    | S.length d == 0 = (d, r)
    | S.length r == 0 = (d, r)
    | head' d < head' r = fight n (tail' d S.|> (head' d + n)) (tail' r)
    | otherwise = fight n (tail' d) (tail' r S.|> (head' r + n))

head' q = S.index q 0
tail' q = S.drop 1 q
last' q = S.index q (S.length q - 1)

solve = walk 0 0 0
  where walk k m s [] | s > 0 || s == 0 && k > 0 = "D"
                      | s < 0 || s == 0 && m > 0 = "R"
                      | otherwise = show (k, m, s)
        walk k 0 s ('D' : rest) = walk (k+1) 0 (s+1) rest
        walk k m s ('D' : rest) = walk k (m-1) s rest
        walk 0 k s ('R' : rest) = walk 0 (k+1) (s-1) rest
        walk k m s ('R' : rest) = walk (k-1) m s rest

main = do
  s <- getContents
  let voters = lines s !! 1
  putStrLn $ solve voters

solve voters@(first : _) = walk 0 0 0 voters
  where walk k m s [] | k - m + s > 0 = "D"
                      | k - m + s < 0 = "R"
                      | otherwise     = [first]
        walk k 0 s ('D' : rest) = walk (k+1) 0 (s+1) rest
        walk k m s ('D' : rest) = walk k (m-1) s rest
        walk 0 k s ('R' : rest) = walk 0 (k+1) (s-1) rest
        walk k m s ('R' : rest) = walk (k-1) m s rest

main = do
  s <- getContents
  let voters = lines s !! 1
  putStrLn $ solve voters

solve voters@(first : _) = walk 0 0 0 voters
  where walk k m s [] | s > 0 || s == 0 && k > 0 = "D"
                      | s < 0 || s == 0 && m > 0 = "R"
                      | otherwise                = [first]
        walk k 0 s ('D' : rest) = walk (k+1) 0 (s+1) rest
        walk k m s ('D' : rest) = walk k (m-1) s rest
        walk 0 k s ('R' : rest) = walk 0 (k+1) (s-1) rest
        walk k m s ('R' : rest) = walk (k-1) m s rest

main = do
  s <- getContents
  let voters = lines s !! 1
  putStrLn $ solve voters


main = do
    aux <- getLine
    let n = read aux :: Int
    let xs = [x | x <- [4,5..(n-4)], complex x, complex (n - x)]
    putStrLn (show (head xs) ++ " " ++ show (n - (head xs)))

prime k = null [x | x <- [2..(k - 1)], mod k x == 0]

complex k = if (prime k) then (False) else (True)

{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import Text.Printf

readInt = ( readLn :: IO Int )
getInts = map ( read :: String -> Int ) . words <$> getLine

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

main = do
	n <- readInt

	let
		m = which 6 9 $ even n

	printf "%d %d\n" m ( n - m )

import Control.Monad

import Data.Array.Unboxed

primes = primesToNA (2 * 10^6)
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]
  where
    ar = f 5 $ accumArray (\ a b -> False) True (3,n)
                        [(i,()) | i <- [9,15..n]]
    f p a | q > n = a
          | True  = if null x then a2 else f (head x) a2
      where q = p*p
            a2  :: UArray Int Bool
            a2 = a // [(i,False) | i <- [q, q+2*p..n]]
            x  = [i | i <- [p+2,p+4..n], a2 ! i]

isPrime n = n `elem` primes

main = do
  n <- readLn

  putStrLn $ unwords $ map show $ head [ [i,j] | i <- [2..n-2], let j = n - i, not (isPrime i), not (isPrime j)]

main = do
    input <- getLine
    let n = read input
    if odd n then
        putStrLn $ ("9 " ++ (show $ n - 9))
    else
        putStrLn $ ("4 " ++ (show $ n - 4))

-- https://wiki.haskell.org/Converting_numbers
--
-- figure out how to convert fractional types to
-- integers and vice-versa

iscomp y e
  | y == e = False
  | (mod y e) == 0 = True
  | otherwise = iscomp y (e+1)

findsum a b
  | iscomp b 2 && iscomp (a-b) 2 = b
  | otherwise = findsum a (b+1)

main = do
  gg <- getLine
  let ss = (read gg)::Int
      hh = findsum ss 2

  putStr (show hh)
  putStr " "
  putStr (show (ss-hh))
  putStr "\n"

main = do
    n <- readLn
    let answer = if even n then [4, n - 4] else [9, n - 9]
    putStrLn $ unwords $ map show answer

main = do
    n <- readLn

    let
        primes = takeWhile (<= n) $ [2, 3] ++ (filter (\x -> and [x `mod` p /= 0 | p <- takeWhile (\p -> p*p <= x) primes]) [4..])

        (a, b) = head [(a, b) | a <- [2..n-2], let b = n-a, notElem a primes, notElem b primes]

    putStrLn $ show a ++ " " ++ show b

solve n
  | even n = [4,n-4]
  | otherwise = [9,n-9]
main = interact $ unwords . map show . solve . read

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

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

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

primeArray :: Int -> UArray Int Bool
primeArray n = runSTUArray $ do
    arr <- newArray (0,n) True
    writeArray arr 0 False
    writeArray arr 1 False
    forM_ (2:[3,5..n]) $ \i -> do
        b <- readArray arr i
        when b $ forM_ [2*i,3*i..n] $ \j -> writeArray arr j False
    return arr

main = do
    n <- readLn
    let a = primeArray n
    let (x,y) = head [ (x,y) | x <- [2..n-1], let y = n-x, not (a ! x) && not (a ! y) ]
    printf "%d %d\n" x y

import System.IO

main :: IO ()
main = getLine >>= putStrLn . (\(a,b) -> show a ++ " " ++ show b) . breakIntoComposite . read

breakIntoComposite :: Integer -> (Integer, Integer)
breakIntoComposite n = (first, n - first)
    where first = 4 + 5 * (n `mod` 2)

isPrime num = [x | x <- [1..num], num `mod` x == 0] == [1,num]
decompose x = [n:d:[] | n <- [2..x-2], let d = (x - n)]
sumNotPrimes n = concat $ take 1 [x:y:[] | [x,y] <- decompose n, isPrime x == False && isPrime y == False]
main = do
	str <- getLine
	(\[a,b] -> putStrLn ((show a) ++ " " ++ (show b))) $ sumNotPrimes (read str)

import Data.List
import Data.Maybe
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve. read.  head . lines
solve :: Int->String
solve x=if x `mod` 2 ==0 then "4" ++" "++ show (x-4) else let (y1,y2)=head [(a,b) |b<-[4,6..], let a = x-b, a `mod` 3 == 0] in  show y1 ++ " " ++ show y2

main = interact $ p . read
p a = if mod a 2 == 1 then "9 "++show (a-9) else "4 "++show (a-4)

main = interact $ p . read
p a = if odd a then "9 "++show (a-9) else "4 "++show (a-4)

getInt :: IO Int
getInt = readLn

isPrime :: Int -> Int -> Bool
isPrime a i | i > a `quot` 2 = True
            | a `mod` i == 0 = False
            | otherwise = isPrime a (i + 1)

divsum :: Int -> Int -> Int -> (Int, Int)
divsum a i j | i == 0 || j == a = (-1, -1)
             | (not (isPrime i 2)) && (not (isPrime j 2)) && (a == i + j) = (i, j)
             | otherwise = divsum a (i - 1) (j + 1)

out a = show (fst a) ++ " " ++ show (snd a)
solve a = putStrLn $ out (divsum a (a - 1) 1)
main = getInt >>= solve

import Control.Applicative
import Data.List

isprime x =all (/=0) [mod x i |i<-[2..(div x 2) ]]

main=do
    n<- read <$> getLine ::IO Int
    putStrLn $ intercalate " " $ map show $ head $ [ [i,j]|i<-[4..], not (isprime i), let j= n-i, not(isprime j)]

main :: IO ()
main = readLn >>= putStrLn . unwords . map show . solve

solve :: Int -> [Int]
solve n | even n = [ 4, n - 4 ]
        | otherwise = [ 9, n - 9 ]

import Prelude hiding (readList, showList)
import Control.Monad
import Control.Applicative
import Data.List

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

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

readInt :: IO Int
readInt = head <$> readList' (undefined::Int)

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

u :: a
u = undefined

isComp :: Int -> Bool
isComp x = any ((==0) . mod x) [2..x-1]

isOk :: Int -> Int -> Bool
isOk x y = isComp x && isComp y

main :: IO ()
main = do
  n <- readInt
  let x= head $ filter (\x -> isOk x (n-x)) [2..n-1]
  showList [x,n-x]

main = do
    input <- getLine
    let n = read input
    if odd n then putStrLn $ ("9 " ++ (show $ n-9))
    else putStrLn $ ("4 " ++ (show $ n-4))

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

solve :: Int -> String
solve n = if odd n then "9 " ++ show (n - 9) else "4 " ++ show (n - 4)

main :: IO ()
main = interact $ solve . read

{-# 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 = readLn >>= putStrLn.unwords.map show.solve

sieveLimit :: Int
sieveLimit = sieveWidth

sieveWidth :: Int
sieveWidth = 0xfffff

intSqrt :: Int -> Int
intSqrt x = floor . sqrt $ fromIntegral x

solve :: Int -> [Int]
solve n = head [[x,n-x]|x<-[2..], not(isPrime x), not (isPrime (n-x))]
   where
     isPrime 2 = True
     isPrime n | even n || n < 2= False
     isPrime n = unsafeAt isPrimeArray (n `quot` 2)
     !lim = (sieveLimit + sieveWidth - 1) `quot` sieveWidth * sieveWidth
     !isPrimeArray = runSTUArray $ do
       isp <- newArray (0, lim `quot` 2) True :: ST s (STUArray s Int Bool)
       unsafeWrite isp 0 False
       forM_ [0, sieveWidth .. lim - sieveWidth] $ \l -> do
         let !l2 = l `quot` 2
             !r  = l + sieveWidth
             !r2 = r `quot` 2
         forM_ [1 .. intSqrt r `quot` 2] $ \i-> do
           flg <- unsafeRead isp i
           when flg $ do
             let !p = 2 * i + 1
                 go !j = when (j < r2) $ do
                   unsafeWrite isp j False
                   go $ j + p
             go $ ((l2 - 2 * i * i) `quot` p + i) * p + i
       return isp

import Text.Printf

main = do
    n <- readLn
    if n `mod` 2 == 0
        then printf "%d %d\n" (8::Int) ((n - 8)::Int)
        else printf "%d %d\n" (9::Int) ((n - 9)::Int)

main = do
    n <- getLine >>= return . read
    let x = if even n then 4 else 9
    let y = n - x
    putStrLn $ unwords . map show $ [x, y]

import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Data.Array as Arr
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import Data.List
import Control.Applicative
import Control.Monad
import Data.Function

main = do
  [n] <- getInts
  let
    solution
      | odd n = [9, n-9]
      | otherwise = [4, n-4]
  putStrLn $ unwords $ map show solution

-- helper functions --

readInt = fst . fromJust . B.readInt
getInts = map readInt . B.words <$> B.getLine

memoArr :: Ix i => (i, i) -> (i -> r) -> (i -> r)
memoArr range f = f' where
  f' i
    | Arr.inRange range i = arr ! i
    | otherwise = f i
  arr = Arr.listArray range (map f (Arr.range range))

dpArr :: Ix i => (i, i) -> ((i -> r) -> (i -> r)) -> (i -> r)
dpArr ixs f = fix (memoArr ixs . f)

isPrime :: Int -> Bool
isPrime 1 = False
isPrime n = null [x | x <- takeWhile (\m -> m*m <= n) [2..], n `mod` x == 0]

getComposite :: Int -> (Int, Int)
getComposite x = head [(m, x-m) | m <- [4..], not $ isPrime m, not $ isPrime (x-m)]

main = do
    n <- getLine
    let (a, b) = getComposite (read n)
    putStrLn ((show a) ++ " " ++ (show b))

import Control.Applicative

process a | even a = putStrLn ( "4 " ++ show (a-4))
	  | a==13 = putStrLn ( "4 9")
	  | a==15 = putStrLn ( "6 9")
	  | a==17 = putStrLn ("8 9")
          | mod a 5 == 1 = putStrLn ( "6 " ++ show (a-6))
	  | mod a 5 == 2 = putStrLn ( "12 " ++ show (a-12))
          | mod a 5 == 3 = putStrLn ( "8 " ++ show (a-8))
          | mod a 5 == 4 = putStrLn ( "4 " ++ show (a-4))
          | mod a 5 == 0 = putStrLn ( "10 " ++ show (a-10))

main= do
	a<-   read  <$> getLine::IO Int
	process a

main = do
  n <- readLn :: IO Int
  putStr.show $ if odd n then 9 else 4
  putStrLn $ " " ++ show (if odd n then n - 9 else n - 4)

main = interact $ unwords . map show . solve . read
solve n = if even n then [4, n - 4] else [9, n - 9]

process :: Int -> (Int,Int)
process n = (x,n-x)
    where
        x = [6,4,8] !! (n `mod` 3)

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    let (a,b) = process n
    putStrLn (show a ++ " " ++ show b)

main = interact $ (\x -> if even x then "4 "++show (x-4) else "9 "++show (x-9)) . read

decomp :: Int -> [Int]
decomp n
    | even n = [4, n - 4]
    | otherwise = [9, n - 9]

solve :: String -> String
solve = unwords.fmap show.decomp.read

main :: IO ()
main = interact $ solve

isComp n = 0 `elem` (map (\x -> n `rem` x) [2.. (n `quot` 2)])
f n = head [(a,b) | a <- [3..(n `quot` 2)], let b = n - a,
                    isComp a, isComp b]
main = do
  k <-getLine
  let n = read k :: Int
      ans = f n
  putStrLn $ (show $ fst ans)++" "++(show $ snd ans)

f::Int -> [Int]
f x | even x = [4,x-4]
    | 1>0 = [9,x-9]
main = interact $ unwords.map show.f.read

main = do
    n <- readLn

    let
        primes = takeWhile (<= n) $ [2, 3] ++ (filter (\x -> and [x `mod` p /= 0 | p <- takeWhile (\p -> p*p <= x) primes]) [4..])

        (a, b) = head [(a, b) | a <- [2..n-2], let b = n-a, notElem a primes, notElem b primes]

    print $ show a ++ " " ++ show b

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

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

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

primeArray :: Int -> UArray Int Bool
primeArray n = runSTUArray $ do
    arr <- newArray (0,n) True
    writeArray arr 0 False
    writeArray arr 1 False
    forM_ (2:[3,5..n]) $ \i -> do
        b <- readArray arr i
        when b $ forM_ [2*i,3*i..n] $ \j -> writeArray arr j False
    return arr

main = do
    n <- readLn
    let a = primeArray n
    let (x,y) = head [ (x,y) | x <- [1..n], let y = n-x, not (a ! x) && not (a ! y) ]
    printf "%d %d\n" x y

getInt :: IO Int
getInt = readLn

isPrime :: Int -> Int -> Bool
isPrime a i | i > a `quot` 2 = True
            | a `mod` i == 0 = False
            | otherwise = isPrime a (i + 1)

divsum :: Int -> Int -> Int -> (Int, Int)
divsum a i j | i == 0 || j == a = (-1, -1)
             | (not (isPrime i 2)) && (not (isPrime j 2)) && (a == i + j) = (i, j)
             | otherwise = divsum a (i - 1) (j + 1)

solve a = putStrLn $ show (divsum a (a - 1) 1)
main = getInt >>= solve

main :: IO ()
main = readLn >>= putStrLn . unwords . map show . solve

solve :: Int -> [Int]
solve n | even n = [ 2, n - 2 ]
        | otherwise = [ 9, n - 9 ]

import Control.Applicative

main= do
	a<-   read  <$> getLine::IO Int
	if even a then putStrLn ( "4 " ++ show (a-4)) else if mod a 5 ==3 then putStrLn ( "8 " ++ show (a-8)) else putStrLn ( "6 " ++ show (a-6))

decomp :: Int -> [Int]
decomp n
    | even n = [2, n - 2]
    | otherwise = [9, n - 9]

solve :: String -> String
solve = unwords.fmap show.decomp.read

main :: IO ()
main = interact $ solve


import Data.Array
import List

getA = fmap (map read . words) getLine

main = do
	[n] <- getA
	x <- getA
	putStr $ let r = gao n x in unlines [show (length r), unwords (map show r)]

gao n x = if null e then [] else head e where
	a = listArray (1, n) x
	b = map head $ groupBy (\i j -> a!i == a!j) [1 .. n]
	c = length b
	d = listArray (1, c) b
	e = filter (\[i, j, k] -> (a!i < a!j) /= (a!j < a!k)) [[d!(i-1), d!i, d!(i+1)] | i <- [2 .. c - 1]]

import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import Text.Printf
import qualified Data.ByteString.Char8 as BS

main :: IO ()
main = do
  let readInt = fst . fromJust . BS.readInt
  n  <- readInt <$> BS.getLine
  xs  <- map readInt . BS.words <$> BS.getLine
  let diff = dropWhile ((== 0) . snd) . zip ([1 ..] :: [Int])
            $ zipWith (-) xs (tail xs)
      found idx1 (idx2, _) = printf "3\n%d %d %d\n" idx1 idx2 (idx2 + 1)
      notFound = print 0
  case diff of
    (idx1, d1) : _ | d1 < 0    -> maybe notFound (found idx1)
                                  $ find ((> 0) . snd) diff
                   | d1 > 0    -> maybe notFound (found idx1)
                                  $ find ((< 0) . snd) diff
    _                          -> notFound

import List
import Control.Arrow

bend :: [(Int, Int)] -> Maybe (Int, Int, Int)
bend ((ia, a):next@((ib, b):(ic, c):_)) =
  case (compare a b, compare b c) of
    (LT, GT) -> Just (ia, ib, ic)
    (GT, LT) -> Just (ia, ib, ic)
    _ -> bend next
bend _ = Nothing

solve xs =
  case bend (deduplicated xs) of
    Just (a, b, c) -> "3\n" ++ (concat $ intersperse " " (map show [a, b, c]))
    Nothing ->  "0\n"
  where
    deduplicated = map read . words . (!! 1) . lines >>>
                   tail . scanl (\ (i, _) n -> (i + 1, n)) (0, 0) >>>
                   map head . groupBy (\ (_, a) (_, b) -> a == b)

main = interact solve

import List
import Control.Arrow

bend :: [(Int, Int)] -> Maybe (Int, Int, Int)
bend ((ia, a):next@((ib, b):(ic, c):_)) =
  case (compare a b, compare b c) of
    (LT, GT) -> Just (ia, ib, ic)
    (GT, LT) -> Just (ia, ib, ic)
    _ -> bend next
bend _ = Nothing

solve xs =
  case bend (deduplicated xs) of
    Just (a, b, c) -> "3\n" ++ (concat $ intersperse " " (map show [a, b, c]))
    Nothing ->  "0\n"
  where
    deduplicated = map read . words . (!! 1) . lines >>>
                   zip [1..] >>>
                   map head . groupBy (\ (_, a) (_, b) -> a == b)

main = interact solve

import Data.List(groupBy, find)
import qualified Data.ByteString.Char8 as BS
import Data.Maybe(fromJust)
main = do
  getLine
  b <- fmap (map readInt . BS.words) BS.getLine
  let a :: [(Int,Int)]
      a = map head . groupBy (\x y -> snd x == snd y) . zip [1..] $ b
      n = length a
      triples = zip3 a (tail a) (tail $ tail a)
      good ((_,a),(_,b),(_,c)) = a>b && b<c || a<b && b>c
      ans = case find good triples of
        Nothing -> []
        Just ((a,_),(b,_),(c,_)) -> [a,b,c]
  if n < 3 || null ans
     then putStrLn "0"
     else do putStrLn "3"
             putStrLn . unwords . map show $ ans

readInt = fst . fromJust . BS.readInt

import Data.Array
import List

getA = fmap (map read . words) getLine

main = do
	[n] <- getA
	x <- getA
	putStr $ let r = gao n x in unlines [show (length r), unwords (map show r)]

gao n x = if null e then [] else head e where
	a = listArray (1, n) x
	b = map head $ groupBy (\i j -> a!i == a!j) [1 .. n]
	c = length b
	d = listArray (1, c) b
	e = filter (\[i, j, k] -> (a!i < a!j) /= (a!j < a!k)) [[d!i-1, d!i, d!i+1] | i <- [2 .. c - 1]]

import List

bend :: Int -> [Int] -> Maybe (Int, Int, Int)
bend i (a:next@(b:c:_)) =
  case (compare a b, compare b c) of
    (LT, GT) -> Just (i, i + 1, i + 2)
    (GT, LT) -> Just (i, i + 1, i + 2)
    _ -> bend (i + 1) next
bend _ _ = Nothing

solve xs =
  case (bend 1) $ (map read) $ words $ (!! 1) $ lines $ xs of
    Just (a, b, c) -> "3\n" ++ (concat $ intersperse " " (map show [a, b, c]))
    Nothing ->  "0\n"

main = interact solve

import List
import Control.Arrow

bend :: [(Int, Int)] -> Maybe (Int, Int, Int)
bend ((ia, a):next@((ib, b):(ic, c):_)) =
  case (compare a b, compare b c) of
    (LT, GT) -> Just (ia, ib, ic)
    (GT, LT) -> Just (ia, ib, ic)
    _ -> bend next
bend _ = Nothing

solve xs =
  case bend (deduplicated xs) of
    Just (a, b, c) -> "3\n" ++ (concat $ intersperse " " (map show [a, b, c]))
    Nothing ->  "0\n"
  where
    deduplicated = map read . words . (!! 1) . lines >>>
                   (\xs -> [ (ia, a) | ia <- [1..], a <- xs ]) >>>
                   map head . groupBy (\ (_, a) (_, b) -> a == b)

main = interact solve


import           Control.Monad
import qualified Data.Map.Strict as Map
import qualified Data.Set        as Set

main :: IO ()
main = do
  n <- fmap read getLine
  strs <- replicateM n getLine
  let seconds = Set.fromList $ concatMap tail strs
      firsts = Set.toList $ Set.difference (Set.fromList $ map head strs) seconds
      conts  = Map.fromList $ concatMap (\xs -> zip xs $ tail xs) strs
      start [] _ = []
      start (f:fs) cs = continue f fs cs
      continue cur fs cs = cur: case Map.lookup cur cs of
        Just next -> continue next fs cs
        Nothing -> start fs cs
  putStrLn $ start firsts conts

{-# OPTIONS_GHC -O2 -optc-O2 #-}
import Prelude hiding (lookup)
import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.Map (fromList, elems, lookup)
import Data.Set (difference)
import qualified Data.Set as S

solve :: [String] -> String
solve xs = S.foldr go "" root
    where
    next = fromList . concat . zipWith zip xs $ map tail xs
    -- all the observed values which are not preceded by any letter
    root = S.fromList (concat xs) `difference` S.fromList (elems next)

    go i acc = case i `lookup` next of
        Just j  -> i: go j acc
        Nothing -> i: acc

main = do
    n <- read <$> getLine
    a <- replicateM n getLine
    putStrLn $ solve a

import           Control.Monad
import           Data.List
import qualified Data.Map.Strict as Map
import qualified Data.Set        as Set

main :: IO ()
main = do
  n <- fmap read getLine
  strs <- replicateM n getLine
  let prereq =  Map.unionsWith Set.union $ map req strs
      req = Map.fromList . snd . mapAccumL prev Set.empty
      prev prevs x = (Set.insert x prevs, (x, prevs))
      go prer | Map.null prer = []
              | otherwise     =
        let (first, _) = Map.findMin $ Map.filter Set.null prer
            prer'      = Map.map (Set.delete first) $  Map.delete first prer
            in first : go prer'
  putStrLn $ go prereq


#!/usr/bin/env stack
-- stack --resolver nightly-2020-08-16 script

import Control.Monad

solve :: IO ()
solve = do
  getLine
  as <- map read . words <$> getLine
  bs <- map read . words <$> getLine
  let moves = zip (subtract (minimum as) <$> as) (subtract (minimum bs) <$> bs)
  print $ sum $ (\(a, b) -> a + b - min a b) <$> moves

main :: IO ()
main = do
  getLine >>= flip replicateM_ solve . read

#!/usr/bin/env stack
-- stack --resolver nightly-2020-08-16 script

import Data.List
import Control.Monad

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

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

readLineInts :: String -> [Int]
readLineInts s = map readInt $ words s

getInts :: IO [Int]
getInts = readLineInts <$> getLine

main :: IO ()
main = do
    testCount <- getInt
    replicateM_ testCount test

test :: IO ()
test = do
    getInt
    as <- map read . words <$> getLine
    bs <- map read . words <$> getLine
    let minA = minimum as
    let minB = minimum bs
    let actCount = sum $ map (pToAct minA minB) $ zip as bs
    print actCount

pToAct :: (Ord a, Num a) => a -> a -> (a, a) -> a
pToAct minA minB (a, b) = max (a - minA) (b - minB)

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

solve :: Int -> IO ()
solve 0 = putStrLn ""
solve t = do
  line <- getLine
  line <- getLine
  let a = convert line :: [Integer]
  let la = foldl min (head a) a
  line <- getLine
  let b = convert line :: [Integer]
  let lb = foldl min (head b) b
  let c = map (\(x, y) -> max (x - la) (y - lb)) (zip a b)
  print $ sum c
  solve $ t - 1

main :: IO ()
main = do
  line <- getLine
  let [t] = convert line :: [Int]
  solve t

import Control.Monad
import Data.Int

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    getLine
    a <- map read . words <$> getLine
    b <- map read . words <$> getLine
    print (solve a b)

solve :: [Int64] -> [Int64] -> Int64
solve a b = sum $ zipWith (\x y -> max (x - a_min) (y - b_min)) a b
  where
    a_min = minimum a
    b_min = minimum b

module Main where

    solve :: IO ()
    solve = do
        _ <- getLine
        sa <- getLine
        sb <- getLine
        let a = map (\x -> read x :: Integer) $ words sa
            b = map (\x -> read x :: Integer) $ words sb
            ma = minimum a
            mb = minimum b
            n = length a
        print $ sum [max (a !! i - ma) (b !! i - mb) | i <- [0..n - 1]]

    iter :: Integer -> IO ()
    iter 1 = solve
    iter n = do
        solve
        iter $ n - 1

    main :: IO ()
    main = do
        s <- getLine
        iter (read s :: Integer)

import Control.Monad -- for replicateM_

solve :: [Integer] -> [Integer] -> Integer
solve a b = answer
    where
        min_a = minimum a
        min_b = minimum b
        substract_min_a = map (\x -> x - min_a) a
        substract_min_b = map (\x -> x - min_b) b
        answer = sum $ zipWith (\x y -> max x y) substract_min_a substract_min_b

deal :: IO()
deal = do
    getLine
    a <- map read . words <$> getLine
    b <- map read . words <$> getLine
    putStrLn $ show $ solve a b

main :: IO()
main = getLine >>= flip replicateM_ deal . read

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

process n [] [] _ _ = n
process n (x:xs) (y:ys) mx my = process (n+(max (x-mx) (y-my) )) xs ys mx my

onecase = do
		getLine
		x<- map read <$> words <$> getLine ::IO [Integer]
		y<- map read <$> words <$> getLine ::IO [Integer]
		print $ process 0 x y (minimum x) (minimum y)

main= do
		a<- read <$> getLine ::IO Int
		replicateM_ a onecase

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))

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

process :: [[Integer]] -> [Integer]
process [] = []
process ([_] : xs : ys : rest) = solve xs ys : process rest

solve :: [Integer] -> [Integer] -> Integer
solve xs ys = sum $ zipWith max (reduce xs) (reduce ys)
  where
    reduce xs = subtract (minimum xs) <$> xs

{-# LANGUAGE Safe #-}

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

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

process :: [[Integer]] -> [Integer]
process [] = []
process ([_] : xs : ys : rest) = solve xs ys : process rest

solve :: [Integer] -> [Integer] -> Integer
solve xs ys =
  sum $
    zipWith
      max
      (zipWith (-) xs (repeat (minimum xs)))
      (zipWith (-) ys (repeat (minimum ys)))

solve :: [Integer] -> [Integer] -> Integer
solve as bs = sum  $ zipWith solve' as bs
  where
    minA = minimum as
    minB = minimum bs
    solve' a b = max (a - minA) (b - minB)

clean :: [String] -> [(String, String)]
clean []           = []
clean (_ : a : b: ss) = (a,b) : clean ss
clean _            = undefined

mapPair :: (a -> b) -> (a, a) -> (b, b)
mapPair f (a, b) = (f a, f b)

main :: IO ()
main = interact
  (unlines . map (show . uncurry solve . mapPair (map read . words) ) . clean . tail . lines)

import Control.Monad
import Data.List

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    n <- getLine
    as <- map read . words <$> getLine
    bs <- map read . words <$> getLine
    let
      minA = foldl' min (head as) (tail as)
      minB = foldl' min (head bs) (tail bs)
      cost = sum $ zipWith act as bs where
        act a b = max (a - minA) (b - minB)
    putStrLn $ show cost

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

main = getLine >>= flip replicateM_ test . read

test = do
  getLine
  as <- map read . words <$> getLine
  bs <- map read . words <$> getLine
  let moves = zip (subtract (minimum as) <$> as) (subtract (minimum bs) <$> bs)
  print $ sum $ (\(a, b) -> a + b - min a b) <$> moves

solve :: [Int] -> [Int] -> Int
solve as bs = sum  $ zipWith solve' as bs
  where
    minA = minimum as
    minB = minimum bs
    solve' a b = max (a - minA) (b - minB)

clean :: [String] -> [(String, String)]
clean []           = []
clean (_ : a : b: ss) = (a,b) : clean ss
clean _            = undefined

mapPair :: (a -> b) -> (a, a) -> (b, b)
mapPair f (a, b) = (f a, f b)

main :: IO ()
main = interact
  (unlines . map (show . uncurry solve . mapPair (map read . words) ) . clean . tail . lines)

#!/usr/bin/env stack
-- stack --resolver nightly-2020-08-16 script

import Data.List
import Control.Monad

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

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

readLineInts :: String -> [Int]
readLineInts s = map readInt $ words s

getInts :: IO [Int]
getInts = readLineInts <$> getLine

main :: IO ()
main = do
    testCount <- getInt
    replicateM_ testCount test

test :: IO ()
test = do
    n <- getInt
    as <- getInts
    bs <- getInts
    let minA = minimum as
    let minB = minimum bs
    let actCount = sum $ map (pToAct minA minB) $ zip as bs
    print actCount

pToAct :: (Ord a, Num a) => a -> a -> (a, a) -> a
pToAct minA minB (a, b) = max (a - minA) (b - minB)

#!/usr/bin/env stack
-- stack --resolver lts-16.10 script

import Data.List
import Control.Monad

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

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

readLineInts :: String -> [Int]
readLineInts s = map readInt $ words s

getInts :: IO [Int]
getInts = readLineInts <$> getLine

main :: IO ()
main = do
    testCount <- getInt
    replicateM_ testCount test

test :: IO ()
test = do
    n <- getInt
    as <- getInts
    bs <- getInts
    let minA = minimum as
    let minB = minimum bs
    let actCount = sum $ map (pToAct minA minB) $ zip as bs
    print actCount

pToAct :: (Ord a, Num a) => a -> a -> (a, a) -> a
pToAct minA minB (a, b) = max (a - minA) (b - minB)


main = interact $ parse . tail . lines

parse (x:xs)
  | i == k = "YES"
  | otherwise = "NO"
  where i = (map read (words x)) :: [Int]
        j = map f xs
        k = map (length) j

f = filter (\a -> a == 'a'
                  || a=='e'
                  || a=='i'
                  || a=='o'
                  || a=='u'
                  || a=='y')

import Control.Monad

getInt = read `fmap` getLine :: IO Int

containsVowel str = any (`elem` "aeiouy") str
countVowel str = length (filter (`elem` "aeiouy") str)

main = do
    n <- getInt
    patterns <- (map read . words) `fmap` getLine :: IO [Int]
    lines <- replicateM n getLine
    results <- forM (zip patterns lines) $ \(pat, line) -> do
        let cands = filter containsVowel (words line)
        if pat == sum (map countVowel cands)
        then return True
        else return False
    if all id results
    then putStrLn "YES"
    else putStrLn "NO"

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as B
import Text.Printf

readInt = ( readLn :: IO Int )
readInts = map ( read :: String -> Int ) . words <$> getLine

getList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

main = do
	getLine
	ps <- readInts
	ss <- lines <$> getContents
	putStrLn $ which "YES" "NO" $ ps == map f ss

f s = length $ filter ( `elem` "aeiouy" ) $ s

import           Control.Applicative
import           Control.Monad
import           Data.Bool

main :: IO ()
main = do
  n <- readLn
  xs <- map read.words <$> getLine
  css <- replicateM n getLine
  putStrLn . bool "NO" "YES" .and $ zipWith (==) xs [length$filter(`elem`"aeiouy")cs|cs<-css]

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as B
import Text.Printf

readInt = ( readLn :: IO Int )
readInts = map ( read :: String -> Int ) . words <$> getLine

getList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

main = do
	getLine
	ps <- readInts
	ss <- lines <$> getContents
	putStrLn $ which "YES" "NO" $ and $ zipWith f ps ss

f p s
	| vowels == 0 = True
	| otherwise = vowels == p
	where
		vowels = length $ filter ( `elem` "aeiouy" ) $ s


import Control.Monad
import Data.List
import Data.Maybe
import qualified Data.ByteString.Char8 as B
import Control.Applicative (liftA2)

readInt = readLn :: IO Int
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

sg = group . sort
lh = liftA2 (,) head length
count = map lh . sg
yesno b = if b then "YES" else "NO"

solve :: ([Int] -> Int) -> [[Int]] -> Bool
solve g v = length missing == 0
            || (maximum . map snd . count . concat) missing == length missing
    where val     = g $ head v
          missing = filter (not . elem val) v

main :: IO ()
main = do
    [n, m] <- readInts
    v <- replicateM m readInts
    putStrLn $ yesno $ (solve head v || solve last v)

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NumDecimals #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}

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

import Data.Char
import Data.List
import Data.Maybe

import qualified Data.ByteString.Char8 as B

import Data.Array.ST.Safe
import Data.STRef

-- import Debug.Trace
import Text.Printf

readInt = readLn :: IO Int
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readNInts = readInt >>= flip replicateM readInt

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

main = do
	[ n, m ] <- readInts
	ps <- map mp <$> replicateM m readInts
	putStrLn $ which "YES" "NO" $ solve ps ( fst $ head ps ) (-1) || solve ps ( snd $ head ps ) (-1)

solve [] _ _ = True
solve ( ( a, b ) : ps ) x y
	| a == x || b == x = solve ps x y
	| y == -1 = solve ps x a || solve ps x b
	| a == y || b == y = solve ps x y
	| otherwise = False


--import Debug.Trace
import qualified Data.ByteString.Char8 as B
import Control.Applicative
import Control.Arrow
import Control.Monad
import Data.List
import Data.Maybe

main = do
  let a = (10^2000 - 1) `div` 9
      b = 10^2000 - a
  print a
  print b

-- Below is template code
readInt = fst . fromJust . B.readInt
lineInt = readInt <$> B.getLine
lineInts = map readInt . B.words <$> B.getLine

--infixr 0 ##
--(##) x msg = traceShow msg x

main = putStrLn . unwords $ [replicate 2230 '5', replicate 2229 '4' ++ "5"]

import Control.Monad
import Data.Bool
import Data.Tuple
import Data.Maybe
import Data.Tree
import Data.Graph
import Data.Array.IArray
import Data.List
import Data.List.Split
import qualified Data.ByteString.Char8 as B

iogetints :: IO [Int]
iogetints = getLine >>= (return . map read . words)

freadEdgeList :: IO [Edge]
freadEdgeList = B.getContents >>= (return . pairify . map (fst . fromJust . B.readInt) . B.words)

indexed :: [a] -> [(Int, a)]
indexed = go 0 where
 go :: Int -> [a] -> [(Int, a)]
 go _ [] = []
 go i (x:xs) = (i, x) : (go (succ i) xs)

foldTree :: (a -> [b] -> b) -> Tree a -> b
foldTree f = go where
 go (Node x ts) = f x (map go ts)

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

buildTree :: Int -> Vertex -> [Edge] -> Tree Vertex
buildTree n r es = fdfs (-1) r where
 g = accumArray (flip (:)) [] (1, n) $ ap (++) (map swap) $ es :: Graph
 fdfs :: Vertex -> Vertex -> Tree Vertex
 fdfs p v = Node v $ map (fdfs v) $ delete p $ g!v

both :: (a -> b) -> (a, a) -> (b, b)
both f (x, y) = (f x, f y)

solve :: String
solve = (replicate 2000 '8') ++ "9" ++ "\n" ++ (replicate 2001 '1')

main :: IO ()
main = do
  putStrLn $ solve


import Control.Monad
import Data.List
main = do
  t <- readLn
  replicateM_ t $ do
    x <- getLine
    y <- getLine
    let xl = elemIndex '1' (drop yl $ reverse x)
        Just yl = elemIndex '1' (reverse y)
    print $ maybe 0 id xl

import Control.Monad
import Data.List

main :: IO ()
main = do
    t <- liftM read getLine
    forM_ [1..t] $ \_ -> do
        x <- liftM reverse getLine
        y <- liftM reverse getLine
        let firstYOne = length . takeWhile (== '0') $ y
        let nextXOne = length . takeWhile (== '0') $ drop firstYOne x
        print nextXOne

f=length.fst.span('1'>);s[]=[];s(x:y:z)=(show$f$drop(f y)x):s z;main=interact$unlines.s.map reverse.tail.words


import Data.Maybe
import Data.List
import Data.Int
import qualified Data.Map as Map

type Cimap = Map.Map Char Int64
type Iimap = Map.Map Int64 Int64

g :: String -> [Int64] -> Char -> Iimap
g a b c = gg a b c (Map.empty) where
	gg "" _ _ acc = acc
	gg (x:xs) (p:ps) c acc
		| c /= x = gg xs ps c acc
		| c == x = gg xs ps c (Map.alter (func) p acc) where
			func Nothing 	= Just 1
			func (Just x) 	= Just (x + 1)

q :: Iimap -> Iimap -> Int64
q a b = Map.foldWithKey (\k x ks -> ks + if k `Map.member` b then x * (b Map.! k) else 0) 0 a

ans :: Cimap -> String -> Int64
ans wf s = f s ( map (wf Map.!) s) where
	f "" _ = 0
	f [c] _ = 0
	f s wfm = f left leftwfm + f right rightwfm + mid where
		(left, right) = splitAt (length s `div` 2) s
		(leftwfm, rightwfm) = splitAt (length s `div` 2) wfm
		lmid = map (g (reverse left) (map (\x -> -x) $ scanl (+) 0 $ reverse leftwfm)) ['a'..'z']
		rmid = map (g right (scanl (+) 0 $ rightwfm))  ['a'..'z']
		mid = sum $ map (\(a,b) -> q a b) (zip lmid rmid)

main :: IO()
main = do
	a <- fmap (map read . words) getLine
	s <- getLine
	putStrLn $ (show $ ans (Map.fromList $ zip ['a'..'z'] a) s)

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Exception hiding (mask)
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, runSTArray)
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.Strict as M
import qualified Data.IntMap as IM
import qualified Data.Set as S
import qualified Data.IntSet as IS
import Data.STRef
import GHC.Arr (Array, STArray, Ix(..))
import Debug.Trace

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;_->error$"readInt error : bs = "++show bs;}
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep n f=foldr((>>).f)(return())[0..n-1]
rev n f=foldr((>>).f.negate)(return())[1-n..0]
for :: Monad m => Int -> Int -> (Int -> m ()) -> m ()
for a b f=foldr((>>).f)(return())[a..b]
{-# INLINE rep #-}
{-# INLINE rev #-}
{-# INLINE for #-}
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
  xs <- map (fromIntegral.readInt).B.words <$> B.getLine
  cs <- getLine
  print $ solve (listArray(0,25)xs) cs

solve :: UArray Int Int64 -> String -> Int64
solve xs cs = sum $ map solve' ['a'..'z']
   where
     !n = length cs

     arr :: UArray Int Int64
     arr = listArray(0, n - 1).tail$scanl(\acc c->acc + unsafeAt xs (fromEnum c - 97)) 0 cs

     solve' :: Char -> Int64
     solve' c0 = go 0 M.empty 0 cs
      where
        go !res !memo !i (c:cs)
          | c == c0 && i > 0 = case M.lookup (unsafeAt arr $ i - 1) memo of
                                 Just x -> go (res + x) (M.insertWith (+) (unsafeAt arr i) 1 memo) (i+1) cs
                                 Nothing -> go res (M.insertWith (+) (unsafeAt arr i) 1 memo) (i+1) cs
          | c /= c0 = go res memo (i + 1) cs
          | otherwise = go res (M.insert (unsafeAt arr i) 1 memo) (i + 1) cs
        go res _ _ [] = res

module Main (main) where

import Control.Monad
import Data.Functor
import Data.Char(ord)
import qualified Data.Map.Strict as Map

isDigit x = x=='-' || (x>='0' && x<='9')
split f l@(a:as) lft
	| f a = split f as (a:lft)
	| otherwise = (reverse lft, as)
split _ [] lft = (reverse lft, [])
readInts::String -> [Integer]
readInts [] = []
readInts l@(x:xs)
	| isDigit x = let (a, b) = split isDigit l [] in (read a):(readInts b)
	| otherwise = readInts xs

main = do
	wts <- Map.fromList . (zip ['a'..'z']) . readInts <$> getLine
	let mapping (w, _, _) c = ((+) w $ wts Map.! c, w, c)
	str <- scanl mapping (0, 0, '-') <$> getLine
	let
		fn (mp, sm) (ps, pps, c) = (mp', sm') where
			mp' = Map.insertWith (+) (ps, c) 1 mp
			sm' = (+) sm $ Map.findWithDefault 0 (pps, c) mp
	let res = snd $ foldl fn (Map.empty, 0) str
	print res


import Data.Ord
import Data.Int
import qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>), take)
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Prelude hiding (showList)
import Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if DSeq.null s then
                aux s
            else
                return $ toList s
        else
            aux $ s DSeq.|> x
    in aux DSeq.Empty

type EIO a = ExceptT String IO a

get :: Read a => EIO a
get = ExceptT $ liftM readEither getToken
gets :: EIO String
gets = ExceptT $ liftM Right getToken
puts :: String -> EIO ()
puts = lift . putStr
putsln :: String -> EIO ()
putsln = lift . putStrLn
put :: Show a => a -> EIO ()
put = putsln . show
putln :: Show a => a -> EIO ()
putln = putsln . show
showList :: Show a => [a] -> String
showList [] = []
showList (x : l) = shows x $ showChar ' ' $ showList l

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

main_ :: EIO ()
main_ = do
    n <- get
    a <- replicateM n get
    putsln $ showList $ f1 n a

f1 :: Int -> [Int64] -> [Int64]
f1 n a =    let bitarray = runSTUArray $ do
                na <- newArray (0, 64) 0 :: ST s (STUArray s Int Int64)
                foldlM (\i c ->
                    do
                        forM_ (f2 c 0) (\x -> do
                        v <- readArray na x
                        if v == 0 then
                            writeArray na x (- i)
                        else
                            writeArray na x 1
                        )
                        return $ i + 1) 1 a
                return na
            in
            let maxb = foldl (\i j ->
                    if (bitarray ! j < 0) then ((- (bitarray ! j)) - 1) else i) 0 [0..63]
            in
            let changedList = runSTUArray $ do
                na <- newArray (0, n-1) 0 :: ST s (STUArray s Int Int64)
                foldlM (\i c -> do
                    writeArray na i c
                    return $ i + 1) 0 a
                v <- readArray na (fromIntegral maxb)
                v2 <- readArray na 0
                writeArray na 0 v
                writeArray na (fromIntegral maxb) v2
                return na
            in
            elems changedList

f2 :: Int64 -> Int -> [Int]
f2 c i =    if c == 0 then []
            else
                if (mod c 2) == 1 then i : (f2 (div c 2) (i + 1))
                else f2 (div c 2) (i + 1)

{-# LANGUAGE TypeFamilies, TypeOperators, DataKinds, ConstraintKinds,
UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
import GHC.TypeLits (TypeError, ErrorMessage (Text))
import Data.Ord
import Data.Int
import qualified Data.Sequence as DSeq (fromList, null, Seq( Empty ), (|>), (<|), (><), take)
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Prelude hiding (showList)
import Text.Read (readEither)

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

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

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

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

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

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

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

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

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

get :: IOInteract a => EIO a
get = ExceptT $ liftM convertEither getToken
put :: IOInteract a => a -> EIO ()
put = lift . putStr . toShow
putln :: IOInteract a => a -> EIO ()
putln = lift . putStrLn . toShow

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

main_ :: EIO ()
main_ = do
    n <- get :: EIO Int
    a <- replicateM n get :: EIO [Int64]
    putln (f1 n a :: [Int64])

f1 :: Int -> [Int64] -> [Int64]
f1 n a =    let bitarray = runSTUArray $ do
                na <- newArray (0, 64) 0 :: ST s (STUArray s Int Int64)
                foldlM (\i c ->
                    do
                        forM_ (f2 c 0) (\x -> do
                        v <- readArray na x
                        if v == 0 then
                            writeArray na x (- i)
                        else
                            writeArray na x 1
                        )
                        return $ i + 1) 1 a
                return na
            in
            let maxb = foldl (\i j ->
                    if (bitarray ! j < 0) then ((- (bitarray ! j)) - 1) else i) 0 [0..63]
            in
            let changedList = runSTUArray $ do
                na <- newArray (0, n-1) 0 :: ST s (STUArray s Int Int64)
                foldlM (\i c -> do
                    writeArray na i c
                    return $ i + 1) 0 a
                v <- readArray na (fromIntegral maxb)
                v2 <- readArray na 0
                writeArray na 0 v
                writeArray na (fromIntegral maxb) v2
                return na
            in
            elems changedList

f2 :: Int64 -> Int -> [Int]
f2 c i =    if c == 0 then []
            else
                if (mod c 2) == 1 then i : (f2 (div c 2) (i + 1))
                else f2 (div c 2) (i + 1)

{-# LANGUAGE TypeFamilies, TypeOperators, DataKinds, ConstraintKinds,
UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
import GHC.TypeLits (TypeError, ErrorMessage (Text))
import Data.Ord
import Data.Int
import qualified Data.Sequence as DSeq (fromList, null, Seq( Empty ), (|>), (<|), (><), take)
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Prelude hiding (showList)
import Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if DSeq.null s then
                aux s
            else
                return $ toList s
        else
            aux $ s DSeq.|> x
    in aux DSeq.Empty

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

class IOInteract a where
    convertEither :: String -> Either String a
    toCharSeq :: a -> DSeq.Seq Char
    toString :: a -> String
    toString x = toList $ toCharSeq x

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

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

class IOInteractp flag a where
    convertEitherp :: flag -> String -> Either String a
    toCharSeqp :: flag -> a -> DSeq.Seq Char

instance (Show a, Read a) => IOInteractp HNormal a where
    convertEitherp _ x = readEither x
    toCharSeqp _ x = DSeq.fromList $ show x

instance IOInteractp HString String where
    convertEitherp _ x = Right x
    toCharSeqp _ x = DSeq.fromList x

instance (IOInteract a) => IOInteractp HList [a] where
    convertEitherp _ x = mapM convertEither $ words x
    toCharSeqp _ [] = DSeq.Empty
    toCharSeqp _ (x : xs) = foldl (\c i -> c DSeq.>< i) (toCharSeq x) (fmap (\x -> ' ' DSeq.<| (toCharSeq x)) xs)

get :: IOInteract a => EIO a
get = ExceptT $ liftM convertEither getToken
put :: IOInteract a => a -> EIO ()
put = lift . putStr . toString
putln :: IOInteract a => a -> EIO ()
putln = lift . putStrLn . toString

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

main_ :: EIO ()
main_ = do
    n <- get :: EIO Int
    a <- replicateM n get :: EIO [Int64]
    putln (f1 n a :: [Int64])

f1 :: Int -> [Int64] -> [Int64]
f1 n a =    let bitarray = runSTUArray $ do
                na <- newArray (0, 64) 0 :: ST s (STUArray s Int Int64)
                foldlM (\i c ->
                    do
                        forM_ (f2 c 0) (\x -> do
                        v <- readArray na x
                        if v == 0 then
                            writeArray na x (- i)
                        else
                            writeArray na x 1
                        )
                        return $ i + 1) 1 a
                return na
            in
            let maxb = foldl (\i j ->
                    if (bitarray ! j < 0) then ((- (bitarray ! j)) - 1) else i) 0 [0..63]
            in
            let changedList = runSTUArray $ do
                na <- newArray (0, n-1) 0 :: ST s (STUArray s Int Int64)
                foldlM (\i c -> do
                    writeArray na i c
                    return $ i + 1) 0 a
                v <- readArray na (fromIntegral maxb)
                v2 <- readArray na 0
                writeArray na 0 v
                writeArray na (fromIntegral maxb) v2
                return na
            in
            elems changedList

f2 :: Int64 -> Int -> [Int]
f2 c i =    if c == 0 then []
            else
                if (mod c 2) == 1 then i : (f2 (div c 2) (i + 1))
                else f2 (div c 2) (i + 1)

import Data.Bits
main :: IO ()
main = do
  _ <- getLine
  as <- (map read.words) <$> getLine
  putStrLn $ (unwords.map show) $ solve as

type Situation = ([Indexed Value],Iterator)
type Iterator = Int
type Indexed a = (Int, a)
type Value = Int

solve :: [Int] -> [Int]
solve as =
  case mix of
    Just (ix,val) -> val : ( take ix as) ++ (drop (ix+1) as)
    Nothing -> as
  where
    mix = stelle (zip [0..] as, 29)

stelle :: Situation -> Maybe (Indexed Value)
stelle (_, -1) = Nothing
stelle (vals, i) =
  if (anzahl::Int) == 1
    then mIndex
    else stelle (vals, i-1)
  where
    (anzahl,mIndex) = foldr bin acc vals
    bin (ix,val) (count,m) =
      if testBit val i
        then
          (count+1,Just (ix,val))
        else
          (count,m)
    acc = (0,Nothing)

{-# LANGUAGE TypeFamilies, TypeOperators, DataKinds, ConstraintKinds,
UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
import Data.Ord
import Data.Int
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Text.Read (readEither)

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

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

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

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

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

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

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

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

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

get :: IOInteract a => EIO a
get = ExceptT $ liftM convertEither getToken
put :: IOInteract a => a -> EIO ()
put = lift . putStr . toShow
putln :: IOInteract a => a -> EIO ()
putln = lift . putStrLn . toShow

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

main_ :: EIO ()
-- template --
main_ = do
    n <- get
    a <- replicateM n get
    putln $ f1 n a

f1 :: Int -> [Int64] -> [Int64]
f1 n a =    let bitarray = runSTUArray $ do
                na <- newArray (0, 64) 0 :: ST s (STUArray s Int Int64)
                foldlM (\i c ->
                    do
                        forM_ (f2 c 0) (\x -> do
                        v <- readArray na x
                        if v == 0 then
                            writeArray na x (- i)
                        else
                            writeArray na x 1
                        )
                        return $ i + 1) 1 a
                return na
            in
            let maxb = foldl (\i j ->
                    if (bitarray ! j < 0) then ((- (bitarray ! j)) - 1) else i) 0 [0..63]
            in
            let changedList = runSTUArray $ do
                na <- newArray (0, n-1) 0 :: ST s (STUArray s Int Int64)
                foldlM (\i c -> do
                    writeArray na i c
                    return $ i + 1) 0 a
                v <- readArray na (fromIntegral maxb)
                v2 <- readArray na 0
                writeArray na 0 v
                writeArray na (fromIntegral maxb) v2
                return na
            in
            elems changedList

f2 :: Int64 -> Int -> [Int]
f2 c i =    if c == 0 then []
            else
                if (mod c 2) == 1 then i : (f2 (div c 2) (i + 1))
                else f2 (div c 2) (i + 1)

{-# LANGUAGE TypeFamilies, TypeOperators, DataKinds, ConstraintKinds,
UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
import GHC.TypeLits (TypeError, ErrorMessage (Text))
import Data.Ord
import Data.Int
import qualified Data.Sequence as DSeq (fromList, null, Seq( Empty ), (|>), (<|), (><), take)
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Prelude hiding (showList)
import Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if DSeq.null s then
                aux s
            else
                return $ toList s
        else
            aux $ s DSeq.|> x
    in aux DSeq.Empty

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

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

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

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

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

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

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

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

get :: IOInteract a => EIO a
get = ExceptT $ liftM convertEither getToken
put :: IOInteract a => a -> EIO ()
put = lift . putStr . toShow
putln :: IOInteract a => a -> EIO ()
putln = lift . putStrLn . toShow

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

main_ :: EIO ()
main_ = do
    n <- get :: EIO Int
    a <- replicateM n get :: EIO [Int64]
    putln (f1 n a :: [Int64])

f1 :: Int -> [Int64] -> [Int64]
f1 n a =    let bitarray = runSTUArray $ do
                na <- newArray (0, 64) 0 :: ST s (STUArray s Int Int64)
                foldlM (\i c ->
                    do
                        forM_ (f2 c 0) (\x -> do
                        v <- readArray na x
                        if v == 0 then
                            writeArray na x (- i)
                        else
                            writeArray na x 1
                        )
                        return $ i + 1) 1 a
                return na
            in
            let maxb = foldl (\i j ->
                    if (bitarray ! j < 0) then ((- (bitarray ! j)) - 1) else i) 0 [0..63]
            in
            let changedList = runSTUArray $ do
                na <- newArray (0, n-1) 0 :: ST s (STUArray s Int Int64)
                foldlM (\i c -> do
                    writeArray na i c
                    return $ i + 1) 0 a
                v <- readArray na (fromIntegral maxb)
                v2 <- readArray na 0
                writeArray na 0 v
                writeArray na (fromIntegral maxb) v2
                return na
            in
            elems changedList

f2 :: Int64 -> Int -> [Int]
f2 c i =    if c == 0 then []
            else
                if (mod c 2) == 1 then i : (f2 (div c 2) (i + 1))
                else f2 (div c 2) (i + 1)

import Data.Bits
main :: IO ()
main = do
  _ <- getLine
  as <- (map read.words) <$> getLine
  putStrLn $ (unwords.map show) $ solve as

type Situation = ([Indexed Value],Iterator)
type Iterator = Int
type Indexed a = (Int, a)
type Value = Int

solve :: [Int] -> [Int]
solve as =
  case mix of
    Just (ix,val) -> val : ( take ix as) ++ (drop (ix+1) as)
    Nothing -> as
  where
    mix = stelle (zip [0..] as, 28)

stelle :: Situation -> Maybe (Indexed Value)
stelle (_, -1) = Nothing
stelle (vals, i) =
  if (anzahl::Int) == 1
    then mIndex
    else stelle (vals, i-1)
  where
    (anzahl,mIndex) = foldr bin acc vals
    bin (ix,val) (count,m) =
      if testBit val i
        then
          (count+1,Just (ix,val))
        else
          (count,m)
    acc = (0,Nothing)


{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad.Trans.State.Lazy
import Control.Monad
import Data.Array.Unboxed
import Data.Array.ST.Safe
import Control.Monad.ST.Safe
import Data.List
import Data.Int

main =  mapM_ print . evalState app . B.words =<< B.getContents

app = do
  n <- poi
  xs <- replicateM n poi
  return [solve n xs]
  where
    pop = state $ \(x:xs) -> (x, xs)
    poi = fmap int pop
    int = maybe undefined fst . B.readInt

solve n xs = foldl' (\s i -> if c!i == 0 then s else (s + fromIntegral (c!i) * fromIntegral (a!i) `rem` fromIntegral d * fromIntegral (t!(c!i - 1))) `rem` fromIntegral d) (0 :: Int64) $ range b
  where
    m = maximum xs
    d = 1000000007
    b = (2, m)
    e = accumArray (+) 0 (1, m) $ zip xs (repeat 1) :: UArray Int Int
    c = listArray b [sum [e!(i * j) | j <- [1..m `quot` i]] | i <- range b] :: UArray Int Int
    a = runSTUArray $ do
      z <- newListArray b $ range b :: ST s (STUArray s Int Int)
      sequence_ [sequence_ [do { zi <- readArray z i; zt <- readArray z (i * j); writeArray z (i * j) (zt - zi) } | j <- [2..m `quot` i]] | i <- range b]
      return z
    t = listArray (0, m) $ iterate (\i -> i * 2 `rem` d) 1 :: UArray Int Int

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad.Trans.State.Lazy
import Control.Monad
import Data.Array.Unboxed
import Data.Array.ST.Safe
import Control.Monad.ST.Safe
import Data.List
import Data.Int

main =  print . evalState app . B.words =<< B.getContents

app = do
  n <- poi
  solve `fmap` replicateM n poi
  where
    pop = state $ \(x:xs) -> (x, xs)
    poi = fmap int pop
    int = maybe undefined fst . B.readInt

solve xs = foldl' (\s i -> if c!i == 0 then s else (s + fromIntegral (c!i) * fromIntegral (a!i) `rem` fromIntegral d * fromIntegral (t!(c!i - 1))) `rem` fromIntegral d) (0 :: Int64) $ range b
  where
    m = maximum xs
    d = 1000000007
    b = (2, m)
    e = accumArray (+) 0 (1, m) $ zip xs (repeat 1) :: UArray Int Int
    c = listArray b [sum [e!(i * j) | j <- [1..m `quot` i]] | i <- range b] :: UArray Int Int
    a = runSTUArray $ do
      z <- newListArray b $ range b :: ST s (STUArray s Int Int)
      sequence_ $ concat [[join $ liftM2 ((writeArray z (i * j) .) . subtract) (readArray z i) (readArray z (i * j)) | j <- [2..m `quot` i]] | i <- range b]
      return z
    t = listArray (0, m) $ iterate (\i -> i * 2 `rem` d) 1 :: UArray Int Int

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad.Trans.State.Lazy
import Control.Monad
import Data.Array.Unboxed
import Data.List
import Data.Int

main =  mapM_ print . evalState app . B.words =<< B.getContents

app = do
  n <- poi
  xs <- replicateM n poi
  return [solve n xs]
  where
    pop = state $ \(x:xs) -> (x, xs)
    poi = fmap int pop
    int = maybe undefined fst . B.readInt

solve n xs = foldl' (\s i -> if c!i == 0 then s else (s + fromIntegral (c!i) * fromIntegral (a!i) `rem` fromIntegral d * fromIntegral (t!(c!i - 1))) `rem` fromIntegral d) (0 :: Int64) $ range b
  where
    m = maximum xs
    d = 1000000007
    b = (2, m)
    e = accumArray (+) 0 (1, m) $ zip xs (repeat 1) :: UArray Int Int
    c = listArray b [sum [e!(i * j) | j <- [1..m `quot` i]] | i <- range b] :: UArray Int Int
    a = accumArray (+) 0 b $ concat [(i, i):[(i * j, -i) | j <- [2..m `quot` i]] | i <- range b] :: UArray Int Int
    t = listArray (0, m) $ iterate (\i -> i * 2 `rem` d) 1 :: UArray Int Int

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad.Trans.State.Lazy
import Control.Monad
import Data.Array.Unboxed
import Data.List

main =  mapM_ print . evalState app . B.words =<< B.getContents

app = do
  n <- poi
  xs <- replicateM n poi
  return [solve n xs]
  where
    pop = state $ \(x:xs) -> (x, xs)
    poi = fmap int pop
    int = maybe undefined fst . B.readInt

solve n xs = foldl' (\s i -> if c!i == 0 then s else (s + c!i * a!i `rem` d * t!(c!i - 1)) `rem` d) 0 $ range b
  where
    m = maximum xs
    d = 1000000007
    b = (2, m)
    e = accumArray (+) 0 (1, m) $ zip xs (repeat 1) :: UArray Int Int
    c = listArray b [sum [e!(i * j) | j <- [1..m `quot` i]] | i <- range b] :: UArray Int Int
    a = accumArray (+) 0 b $ concat [(i, i):[(i * j, -i) | j <- [2..m `quot` i]] | i <- range b] :: UArray Int Int
    t = listArray (0, m) $ iterate (\i -> i * 2 `rem` d) 1 :: UArray Int Int


main = do
    [n,b,d] <- return . map read . words =<< getLine
    oranges <- return . map read . words =<< getLine
    let acceptable = filter (<=b) oranges
	squeeze [] _ n = n
	squeeze (o:os) w n
	  | d < w+o	    = squeeze os 0 (n+1)
	  | otherwise	    = squeeze os (w+o) n
    print $ squeeze acceptable 0 0

main :: IO ()
main = do
        firstLine <- getLine
        secondLine <- getLine

        let params = (map read . words) firstLine :: [Int]
        let oranges = (map read . words) secondLine :: [Int]
        let result = dumps (params !! 1) (params !! 2) 0 oranges
        print result

dumps :: (Integral a) => a -> a -> a -> [a] -> a
dumps b d currentlevel [] = 0 -- if the list is empty, vasya should not dump
dumps b d currentlevel (x:xs)
        | x > b = dumps b d currentlevel xs --the orange is larger
        | currentlevel + x > d = 1 + dumps b d 0 xs
        | otherwise = dumps b d (currentlevel + x) xs

import Numeric

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

main = interact $ show.f.parse.words
parse = map fastRead

g [] y temp ans = ans
g (x:xs) y temp ans
  | (temp+x) > y = g xs y 0 (ans+1)
  | otherwise = g xs y (temp+x) ans

f (x:y:z:xs) = g (filter (<=y)  xs) z 0 0

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

f a _ tb  d [] = a + if tb > d then 1 else 0
f a b tb d (o:os) =
    if o > b
        then f a b tb d os
        else if tb > d
            then f (a+1) b o d os
            else f a b (o+tb) d os

ints = map (fst . fromJust . B.readInt) . B.words <$> B.getLine
main = do
    [n,b,d] <- ints
    as <- ints
    print $ f 0 b 0 d as

--ghc 8.0.1 /opt/ghc/8.0.1/lib/ghc-8.0.0.20160127/

solve n b d r xs
  | n == 0              = 0
  | (head) xs > b       = solve (n-1) b d r (tail xs)
  | r + (head xs) > d           = 1 + solve (n-1) b d 0 (tail xs)
  | otherwise           = solve (n-1) b d (r + head xs) (tail xs)

main = getLine >>= (return . map read . words) >>= \[n, b, d] ->
         getLine >>= (return . map read . words) >>= putStrLn . show . (solve n b d 0)

main = interact $ show . solve . map read . tail . words
solve (b:d:as) = go 0 $ filter (<= b) as where
  go _ [] = 0
  go v (a:as) | v' > d = 1 + go 0 as
              | otherwise = go v' as
    where v' = v + a

main = getContents >>= print . solve 0 0 . map read . words

solve cnt tmp (n:b:d:as)
    | null as = cnt
    | b < head as = solve cnt tmp (n:b:d:tail as)
    | tmp + head as <= d = solve cnt (tmp + head as) (n:b:d:tail as)
    | otherwise = solve (cnt + 1) 0 (n:b:d:tail as)

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

  solve :: [Int] -> Int ->  Int -> Int -> Int -> Int
  solve [] _ _ _ accumulator = accumulator
  solve (x:xs) currentValue b d accumulator =
    let nextValue = currentValue + x
      in case (x <= b, nextValue > d) of
      (True, True) -> solve xs 0 b d (accumulator + 1)
      (True, False) -> solve xs nextValue b d accumulator
      (False, _) -> solve xs currentValue b d accumulator

  -- converting list to Set
  -- let mySet = S.fromList myList

  main :: IO()
  main = do
    [n,b,d] <- getLine >>= return . (map readInt) . words
    xs <- getLine >>= return . (map readInt) . words
    putStrLn $ show $ solve xs 0 b d 0
    -- n <- getLine >>= return . readInt
    -- putStrLn $ show $ solve [5,6] 0 7 10 0
    -- putStrLn "hello world"

calc :: [Int] -> Int -> Int -> Int
calc [] acum d     = if acum > d then 1 else 0
calc (x:xs) acum d = if acum > d then 1 + calc xs x d else calc xs (acum + x) d

process :: String -> String
process str =
  let [header, body] = lines str
      [n, b, d]      = map read $ words header
      a              = filter (<= b) . map read . take n . words $ body
  in show $ calc a 0 d

main :: IO ()
main = interact process

import Numeric

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

main = interact $ show.f.parse.words
parse = map fastRead

g [] y temp ans = ans
g (x:xs) y temp ans
  | (temp+x) > y = g xs y 0 (ans+1)
  | otherwise = g xs y (temp+x) ans

f (x:y:z:xs) = g (filter (<y)  xs) z 0 0

import Numeric

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

main = interact $ show.f.parse.words
parse = map fastRead

f (x:y:z:xs) = (sum (filter (<y)  xs)) `div` z

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

f a _ _  d td  [] = a + if td > d then 1 else 0
f a b tb w tw (o:os) =
    if o > b
        then f a b tb w tw os
        else if tw > w
            then f (a+1) b (o+tb) w 0 os
            else if (o+tb) > b
                then f a b 0 w (w+o+tb-b) os
                else f a b (o+tb) w tw os

ints = map (fst . fromJust . B.readInt) . B.words <$> B.getLine
main = do
    [n,b,d] <- ints
    as <- ints
    print $ f 0 b 0 d 0 as

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

f a _ _  _ d  [] = a + if d > 0 then 1 else 0
f a b tb w tw (o:os) =
    if o > b
        then f a b tb w tw os
        else if tw > w
            then f (a+1) b (o+tb) w 0 os
            else if (o+tb) > b
                then f a b 0 w (w+o+tb-b) os
                else f a b (o+tb) w tw os

ints = map (fst . fromJust . B.readInt) . B.words <$> B.getLine
main = do
    [n,b,d] <- ints
    as <- ints
    print $ f 0 b 0 d 0 as

main = getContents >>= print . solve 0 0 . map read . words

solve cnt tmp (n:b:d:as)
    | null as = cnt
    | b < head as = solve cnt tmp (n:b:d:tail as)
    | tmp + head as <= d = solve cnt (tmp + head as) (n:b:d:tail as)
    | otherwise = solve (cnt + 1) ((tmp + head as) `mod` d) (n:b:d:tail as)

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

  solve :: [Int] -> Int ->  Int -> Int -> Int -> Int
  solve [] _ _ _ accumulator = accumulator
  solve (x:xs) currentValue b d accumulator =
    let nextValue = currentValue + x
      in case (x < b, nextValue > d) of
      (True, True) -> solve xs 0 b d (accumulator + 1)
      (True, False) -> solve xs nextValue b d accumulator
      (False, _) -> solve xs currentValue b d accumulator

  -- converting list to Set
  -- let mySet = S.fromList myList

  main :: IO()
  main = do
    [n,b,d] <- getLine >>= return . (map readInt) . words
    xs <- getLine >>= return . (map readInt) . words
    putStrLn $ show $ solve xs 0 b d 0
    -- n <- getLine >>= return . readInt
    -- putStrLn $ show $ solve [5,6] 0 7 10 0
    -- putStrLn "hello world"


--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language Safe                      #-}
{-# language ImportQualifiedPost       #-}
{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [n] <- ri
        replicateM n ri
    mapM_ (putStrLn.show.solve) tcs

solve boxes = 2 * ((-minX) + (-minY) + maxX + maxY)
  where
    minX = min 0 . minimum . map head $ boxes
    maxX = max 0 . maximum . map head $ boxes
    minY = min 0 . minimum . map last $ boxes
    maxY = max 0 . maximum . map last $ boxes

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

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

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

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

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

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

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

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

-- debug x t = x
-- trace t x = x
-- tracing t x = x
-- debugging x t = x

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

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

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

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

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

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

{- END OF GENERAL -}

solve :: Int -> [(Int, Int)] -> Int
solve n points = 2 * ((maximum xs - minimum xs) + (maximum ys - minimum ys))
    where
        xs = 0 : map fst points
        ys = 0 : map snd points

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