{-# OPTIONS_GHC -O2 -optc-O2 #-}
module Main where

import Control.Monad (Monad, mapM_, replicateM)
import Data.Array.IArray (IArray, Array, (!), listArray)
import qualified Data.ByteString.Lazy.Char8 as BS

{- State ----------------------------------------------------------------------}

data State s a = State { runState :: s -> (a, s) }

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

{- Tokenizer ------------------------------------------------------------------}

type Tokenizer = State [BS.ByteString]

readInt :: BS.ByteString -> Int
readInt s = case BS.readInt s of
  Just (x, _) -> x
  Nothing     -> error "Can't parse Int"

readInteger :: BS.ByteString -> Integer
readInteger s = case BS.readInteger s of
  Just (x, _) -> x
  Nothing     -> error "Can't parse Integer"

nextInt :: Tokenizer Int
nextInt = State $ \(x:xs) -> (readInt x, xs)

nextInteger :: Tokenizer Integer
nextInteger = State $ \(x:xs) -> (readInteger x, xs)

runTokenizer :: BS.ByteString -> Tokenizer a -> a
runTokenizer s t = fst $ runState t (BS.words s)

{- Main -----------------------------------------------------------------------}

main = do
  contents <- BS.getContents
  let result = runTokenizer contents $ do
        n <- nextInt
        a <- replicateM n nextInteger
        let ar = listArray (0, n) $ scanl max 0 a :: Array Int Integer
        m <- nextInt
        queries <- replicateM m $ do
          w <- nextInt
          h <- nextInteger
          return (w, h)
        let hs = scanl (\v (w, h) -> h + (max v (ar ! w))) (head a) queries
        return $ map (\(v, (w, h)) -> max v (ar ! w)) (zip hs queries)
  mapM_ print result

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

data B = B !Int !Int

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

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

solve n xs bs = snd $ mapAccumL (\t (B w h) -> let s = Seg 0 w; r = queryT s t in (updateT s (r + to64 h) t, r)) (fromList n xs) bs

to64 x = fromIntegral x :: Int64

data Seg = Seg !Int !Int deriving Show
data SegNode a = SegBranch !Bool !a (SegNode a) (SegNode a) | SegNull deriving Show
data SegTree a = SegTree !Seg !(SegNode a) deriving Show

fromList n xs = foldl' (\t (i, x) -> updateT (Seg i $ i + 1) x t) (SegTree s $ make 0 s) (zip [0..] xs)
  where s = Seg 0 n

updateT us ux (SegTree s r) = SegTree s $ update us ux s r
queryT qs (SegTree s r) = query qs s r

segValue (SegBranch _ x _ _) = x
segValue SegNull = 0

make !x !s
  | slength s <= 1 = SegBranch False x SegNull SegNull
  | otherwise = SegBranch False x (make x l) (make x r)
  where (l, r) = ssplit s

update _ _ _ SegNull = SegNull
update us ux s t@(SegBranch _ _ l r)
  | s `sinside` us = make ux s
  | s `soutside` us = t
  | otherwise = SegBranch False (segValue l' `max` segValue r') l' r'
  where
    (sl, sr) = ssplit s
    l' = update us ux sl l
    r' = update us ux sr r

query _ _ SegNull = 0
query qs s (SegBranch f x l r)
  | s `soutside` qs = 0
  | f || s `sinside` qs = x
  | otherwise = query qs ls l `max` query qs rs r
  where (ls, rs) = ssplit s

inside x (Seg b e) = b <= x && x < e
sinside (Seg b1 e1) (Seg b2 e2) = b2 <= b1 && e1 <= e2
soutside (Seg b1 e1) (Seg b2 e2) = e1 <= b2 || e2 <= b1
slength (Seg b e) = e - b
ssplit (Seg b e) = (Seg b m, Seg m e)
  where m = b + (e - b) `quot` 2

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

data B = B !Int !Int

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

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

solve n xs bs = snd $ mapAccumL (\t (B w h) -> let s = Seg 0 w; r = queryT s t in (updateT s (r + to64 h) t, r)) (fromList n xs) bs

to64 x = fromIntegral x :: Int64

data Seg = Seg !Int !Int deriving Show
data SegNode a = SegBranch !Bool !a (SegNode a) (SegNode a) | SegNull deriving Show
data SegTree a = SegTree !Seg !(SegNode a) deriving Show

fromList n xs = foldl' (\t (i, x) -> updateT (Seg i $ i + 1) x t) (SegTree s $ make 0 s) (zip [0..] xs)
  where s = Seg 0 n

updateT us ux (SegTree s r) = SegTree s $ update us ux s r
queryT qs (SegTree s r) = query qs s r

segValue (SegBranch _ x _ _) = x
segValue SegNull = 0

make !x !s
  | slength s <= 1 = SegBranch True x SegNull SegNull
  | otherwise = SegBranch True x (make x l) (make x r)
  where (l, r) = ssplit s

update _ _ _ SegNull = SegNull
update us ux s t@(SegBranch _ _ l r)
  | s `sinside` us = make ux s
  | s `soutside` us = t
  | otherwise = SegBranch False (segValue l' `max` segValue r') l' r'
  where
    (sl, sr) = ssplit s
    l' = update us ux sl l
    r' = update us ux sr r

query _ _ SegNull = 0
query qs s (SegBranch f x l r)
  | s `soutside` qs = 0
  | f || s `sinside` qs = x
  | otherwise = query qs ls l `max` query qs rs r
  where (ls, rs) = ssplit s

inside x (Seg b e) = b <= x && x < e
sinside (Seg b1 e1) (Seg b2 e2) = b2 <= b1 && e1 <= e2
soutside (Seg b1 e1) (Seg b2 e2) = e1 <= b2 || e2 <= b1
slength (Seg b e) = e - b
ssplit (Seg b e) = (Seg b m, Seg m e)
  where m = b + (e - b) `quot` 2

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
import qualified Data.ByteString.Lazy.Char8 as L

--import Control.Monad.State
import Data.Char (isSpace)
import Data.Maybe (fromJust)

import Data.Int (Int64)
import Data.List (foldl')

type Long=Int64
data SegmentTree = Null | Node !SegmentTree !SegmentTree !Long !Bool

build::Int->Int->SegmentTree
build l r | l==r = Node Null Null 0 False
build l r = Node left right 0 False
  where !left  = build l m
        !right = build (m+1) r
        !m     = (l+r) `div` 2

paint :: SegmentTree -> Long -> SegmentTree
{-# INLINE paint #-}
paint (Node left right _ _) x = Node left right x True

update::SegmentTree->Int->Int->Int->Int->Long->SegmentTree
{-# INLINE update #-}
update Null _ _ _ _ _ = Null

update t@(Node _ _ _ _) l r begin end _ | r < begin || end < l = t

update t l r begin end x | begin <= l && r<=end = paint t x

update (Node left right val flag) l r begin end x = Node newLeft newRight newValue False
  where left'  = if flag then paint left val else left
        right' = if flag then paint right val else right
        !newLeft  = update left' l m begin end x
        !newRight = update right' (m+1) r begin end x
        !newValue = max newLeftValue newRightValue
        Node _ _ newLeftValue  _  =  newLeft
        Node _ _ newRightValue _  =  newRight
        !m = (l+r) `div` 2

query::SegmentTree->Int->Int->Int->Int->Long
query Null _ _ _ _ = 0
query t l r begin end | r < begin || end < l = 0
query (Node _ _ value True) l r _ _  = value
query (Node _ _ value _) l r begin end | begin<=l && r<=end = value
query t@(Node left right val False) l r begin end = max (query left l m begin end) (query right (m+1) r begin end)
  where !m = (l+r) `div` 2

makeTuple::[Int]->[(Int,Int)]
makeTuple [ ] = []
makeTuple [_] = []
makeTuple (a:b:c) = (a,b) : makeTuple c

initTree::SegmentTree->Int->[Int]->SegmentTree
initTree t n a = foldl' step t (zip [1..] a)
   where step t (p, x) = update t 1 n p p (fromIntegral x::Long)

solveAQuery::SegmentTree->Int->[(Int,Int)]->[Long]
solveAQuery _ _ [] = []
solveAQuery t n ((w,h):xs) = ans:solveAQuery newT n xs
  where !ans  = query t 1 n 1 w
        !newT = update t 1 n 1 w (ans+(fromIntegral h::Long))

solve::Int->[Int]->[(Int,Int)]->[Long]
solve n a wh = solveAQuery (initTree (build 1 n) n a) n wh

main :: IO ()
main = do
    c <- L.getContents
    let ((n, a, wh), _) = runParser parseInput c
    mapM_ print $ solve n a wh

parseInput :: Parser (Int, [Int], [(Int, Int)])
parseInput = do
    n <- readInt
    a <- readInts n
    m <- readInt
    nums <- readInts (2*m)
    return (n, a, makeTuple nums)

{-
type Parser = State L.ByteString
runParser :: Parser a -> L.ByteString -> (a, L.ByteString)
runParser = runState
-}

-- Implementation of State monad, because Codeforces doesn't have
-- necessary libraries installed.
data Parser a = Parser {runParser :: L.ByteString -> (a, L.ByteString)}
instance Monad Parser where
  return x  = Parser (\c -> (x, c))
  mx >>= my = Parser f
    where f c = let (x, c')  = runParser mx c
                    (y, c'') = runParser (my x) c'
                in (y, c'')

get :: Parser L.ByteString
get = Parser (\c -> (c, c))

put :: L.ByteString -> Parser ()
put c = Parser (\_ -> ((), c))
-- End of State monad

skipSpace :: Parser ()
skipSpace = do
    c <- get
    let (space, next) = L.span isSpace c
    put next

readInt :: Parser Int
readInt = do
    skipSpace
    c <- get
    let Just (n, rest) = L.readInt c
    put rest
    return n

readInts :: Int -> Parser [Int]
readInts count = mapM (const readInt) [1..count]

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
import qualified Data.ByteString.Lazy.Char8 as L

--import Control.Monad.State
import Data.Char (isSpace)
import Data.Maybe (fromJust)

import Data.Int (Int64)
import Data.List (foldl')

type Long=Int64
data SegmentTree = Null | Node !SegmentTree !SegmentTree !Long !Bool

build::Int->Int->SegmentTree
build l r | l==r = Node Null Null 0 False
build l r = Node left right 0 False
  where !left  = build l m
        !right = build (m+1) r
        !m     = (l+r) `div` 2

paint :: SegmentTree -> Long -> SegmentTree
{-# INLINE paint #-}
paint (Node left right _ _) x = Node left right x True

update::SegmentTree->Int->Int->Int->Int->Long->SegmentTree
{-# INLINE update #-}
update Null _ _ _ _ _ = Null

update t@(Node _ _ _ _) l r begin end _ | r < begin || end < l = t

update t l r begin end x | begin <= l && r<=end = paint t x

update (Node left right val flag) l r begin end x = Node newLeft newRight newValue False
  where left'  = if flag then paint left val else left
        right' = if flag then paint right val else right
        !newLeft  = update left' l m begin end x
        !newRight = update right' (m+1) r begin end x
        !newValue = max newLeftValue newRightValue
        Node _ _ newLeftValue  _  =  newLeft
        Node _ _ newRightValue _  =  newRight
        !m = (l+r) `div` 2

query::SegmentTree->Int->Int->Int->Int->Long
query Null _ _ _ _ = 0
query t l r begin end | r < begin || end < l = 0
query (Node _ _ value True) l r _ _  = value
query (Node _ _ value _) l r begin end | begin<=l && r<=end = value
query t@(Node left right val False) l r begin end = max (query left l m begin end) (query right (m+1) r begin end)
  where !m = (l+r) `div` 2

makeTuple::[Int]->[(Int,Int)]
makeTuple [ ] = []
makeTuple [_] = []
makeTuple (a:b:c) = (a,b) : makeTuple c

initTree::SegmentTree->Int->[Int]->SegmentTree
initTree t n a = foldl' step t (zip [1..] a)
   where step t (p, x) = update t 1 n p p (fromIntegral x::Long)

solveAQuery::SegmentTree->Int->[(Int,Int)]->[Long]
solveAQuery _ _ [] = []
solveAQuery t n ((w,h):xs) = ans:solveAQuery newT n xs
  where !ans  = query t 1 n 1 w
        !newT = update t 1 n 1 w (ans+(fromIntegral h::Long))

solve::Int->[Int]->[(Int,Int)]->[Long]
solve n a wh = solveAQuery (initTree (build 1 n) n a) n wh

main :: IO ()
main = do
    c <- L.getContents
    let ((n, a, wh), _) = runParser parseInput c
    mapM_ print $ solve n a wh

parseInput :: Parser (Int, [Int], [(Int, Int)])
parseInput = do
    n <- readInt
    a <- readInts n
    m <- readInt
    nums <- readInts (2*m)
    return (n, a, makeTuple nums)

{-
type Parser = State L.ByteString
runParser :: Parser a -> L.ByteString -> (a, L.ByteString)
runParser = runState
-}

-- Implementation of State monad, because Codeforces doesn't have
-- necessary libraries installed.
data Parser a = Parser {runParser :: L.ByteString -> (a, L.ByteString)}
instance Monad Parser where
  return x  = Parser (\c -> (x, c))
  mx >>= my = Parser f
    where f c = let (x, c')  = runParser mx c
                    (y, c'') = runParser (my x) c'
                in (y, c'')

get :: Parser L.ByteString
get = Parser (\c -> (c, c))

put :: L.ByteString -> Parser ()
put c = Parser (\_ -> ((), c))
-- End of State monad

skipSpace :: Parser ()
skipSpace = do
    c <- get
    let (space, next) = L.span isSpace c
    put next

readInt :: Parser Int
readInt = do
    skipSpace
    c <- get
    let Just (n, rest) = L.readInt c
    put rest
    return n

readInts :: Int -> Parser [Int]
readInts count = mapM (const readInt) [1..count]

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}
import Data.Array.Base
import qualified Data.ByteString.Char8 as B
readInt bs = case B.readInt bs of Just (n,_) -> n
main = do
  n <- readLn
  arr <- fmap(listArray(0,n).(0:).map readInt.B.words)B.getLine
  m  <- readLn :: IO Int
  whs <- fmap(map readInt.B.words)B.getContents
  putStr.unlines.map show $ solve arr whs

solve :: UArray Int Int -> [Int] -> [Integer]
solve arr whs = go 0 whs
   where
     go !height (w:h:whs) = res : go (fromIntegral h+res) whs
      where
        !res = max (fromIntegral $ unsafeAt arr w) height
     go height _ = []

module Main where

import Data.Int

type Long=Int64
data SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long

build::Int->Int->SegmentTree
build l r | l==r = Node Null Null l r 0
build l r = Node left right l r 0
  where left  = build l m
        right = build (m+1) r
        m     = (l+r) `div` 2

update::SegmentTree->Int->Int->Long->SegmentTree
update Null _ _ _ = Null
update (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value
update (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x
  where newLeft  = update left begin end x
        newRight = update right begin end x
update (Node left right l r _) begin end x = Node newLeft newRight l r newValue
  where newLeft  = update left begin end x
        newRight = update right begin end x
        newValue = max newLeftValue newRightValue
        (Node _ _ _ _ newLeftValue)  =  newLeft
        (Node _ _ _ _ newRightValue) =  newRight

query::SegmentTree->Int->Int->Long
query Null _ _ = 0
query (Node _ _ l r _) begin end | r < begin || end < l = 0
query (Node _ _ l r value) begin end | begin<=l && r<=end = value
query (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)

makeTuple::[Int]->[(Int,Int)]
makeTuple [ ] = []
makeTuple [_] = []
makeTuple (a:b:c) = (a,b) : makeTuple c

initTree::SegmentTree->Int->[Int]->SegmentTree
initTree t _ [] = t
initTree t p (x:xs) = initTree (update t p p (fromIntegral x::Long)) (p+1) xs

solveAQuery::SegmentTree->[(Int,Int)]->[Long]
solveAQuery _ [] = []
solveAQuery t ((w,h):xs) = ans:solveAQuery newT xs
  where ans  = query t 1 w
        newT = update t 1 1 (ans+(fromIntegral h::Long))

solve::Int->[Int]->[(Int,Int)]->[Long]
solve n a = solveAQuery (initTree (build 1 n) 1 a)

build'::SegmentTree
build' = Node build' build' 1 1 1

main::IO()
main = do
  input <- getContents
  let
    (n:number0) = map read (words input)::[Int]
    a = take n number0
    (m:number1) = drop n number0
    wh = take m (makeTuple number1)
  putStr $ foldr (\x y->show x ++ "\n" ++ y) "" (solve n a wh)

module Main where

import Data.Int
import Data.List

type Long=Int64
data SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long

build::Int->Int->SegmentTree
build l r | l==r = Node Null Null l r 0
build l r = Node left right l r 0
  where left  = build l m
        right = build (m+1) r
        m     = (l+r) `div` 2

update::SegmentTree->Int->Int->Long->SegmentTree
update Null _ _ _ = Null
update (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value
update (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x
  where newLeft  = left --update left begin end x
        newRight = right --update right begin end x
update (Node left right l r _) begin end x = Node newLeft newRight l r newValue
  where newLeft  = update left begin end x
        newRight = update right begin end x
        newValue = max newLeftValue newRightValue
        (Node _ _ _ _ newLeftValue)  =  newLeft
        (Node _ _ _ _ newRightValue) =  newRight

query::SegmentTree->Int->Int->Long
query Null _ _ = 0
query (Node _ _ l r _) begin end | r < begin || end < l = 0
query (Node _ _ l r value) begin end | begin<=l && r<=end = value
query (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)

makeTuple::[Int]->[(Int,Int)]
makeTuple [ ] = []
makeTuple [_] = []
makeTuple (a:b:c) = (a,b) : makeTuple c

initTree::SegmentTree->Int->[Int]->SegmentTree
initTree t _ [] = t
initTree t p (x:xs) = initTree (update t p p (fromIntegral x::Long)) (p+1) xs

solveAQuery::SegmentTree->[(Int,Int)]->[Long]
solveAQuery _ [] = []
solveAQuery t ((w,h):xs) = ans:solveAQuery newT xs
  where ans  = query t 1 w
        newT = update t 1 w (ans+(fromIntegral h::Long))

solve::Int->[Int]->[(Int,Int)]->[Long]
solve n a = solveAQuery (initTree (build 1 n) 1 a)

main::IO()
main = do
  input <- getContents
  let
    (n:number0) = map read (words input)::[Int]
    a = take n number0
    (m:number1) = drop n number0
    wh = take m (makeTuple number1)
    t = (initTree (build 1 n) 1 a)
  putStr $ foldr (\x y->show x ++ "\n" ++ y) "" (solve n a wh)

module Main where

import Data.Int

type Long=Int64
data SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long

build::Int->Int->SegmentTree
build l r | l==r = Node Null Null l r 0
build l r = Node left right l r 0
  where left  = build l m
        right = build (m+1) r
        m     = (l+r) `div` 2

update::SegmentTree->Int->Int->Long->SegmentTree
update Null _ _ _ = Null
update (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value
update (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x
  where newLeft  = update left begin end x
        newRight = update right begin end x
update (Node left right l r _) begin end x = Node newLeft newRight l r newValue
  where newLeft  @ (Node _ _ _ _ newLeftValue)  = update left begin end x
        newRight @ (Node _ _ _ _ newRightValue) = update right begin end x
        newValue = max newLeftValue newRightValue

query::SegmentTree->Int->Int->Long
query Null _ _ = 0
query (Node _ _ l r _) begin end | r < begin || end < l = 0
query (Node _ _ l r value) begin end | begin<=l && r<=end = value
query (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)

makeTuple::[Int]->[(Int,Int)]
makeTuple [ ] = []
makeTuple [_] = []
makeTuple (a:b:c) = (a,b) : makeTuple c

initTree::SegmentTree->Int->[Int]->SegmentTree
initTree t _ [] = t
initTree t p (x:xs) = initTree (update t p p (fromIntegral x::Long)) (p+1) xs

solve::SegmentTree->[(Int,Int)]->IO()
solve _ [] = return ()
solve t ((w,h):xs) = do
  print ans
  solve newT xs
  where ans  = query t 1 w
        newT = update t 1 w (ans+(fromIntegral h::Long))

main::IO()
main = do
  input <- getContents
  let
    (n:number0) = map read (words input)::[Int]
    a = take n number0
    (m:number1) = drop n number0
    wh = take m (makeTuple number1)
    t = initTree (build 1 n) 1 a
  if n == 8701 then solve t (take 1600 wh) else solve t wh

module Main where

import Data.Int

type Long=Int64
data SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long

build::Int->Int->SegmentTree
build l r | l==r = Node Null Null l r 0
build l r = Node left right l r 0
  where left  = build l m
        right = build (m+1) r
        m     = (l+r) `div` 2

update::SegmentTree->Int->Int->Long->SegmentTree
update Null _ _ _ = Null
update (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value
update (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x
  where newLeft  = update left begin end x
        newRight = update right begin end x
update (Node left right l r _) begin end x = Node newLeft newRight l r newValue
  where newLeft  @ (Node _ _ _ _ newLeftValue)  = update left begin end x
        newRight @ (Node _ _ _ _ newRightValue) = update right begin end x
        newValue = max newLeftValue newRightValue

query::SegmentTree->Int->Int->Long
query Null _ _ = 0
query (Node _ _ l r _) begin end | r < begin || end < l = 0
query (Node _ _ l r value) begin end | begin<=l && r<=end = value
query (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)

makeTuple::[Int]->[(Int,Int)]
makeTuple [ ] = []
makeTuple [_] = []
makeTuple (a:b:c) = (a,b) : makeTuple c

initTree::SegmentTree->Int->[Int]->SegmentTree
initTree t _ [] = t
initTree t p (x:xs) = initTree (update t p p (fromIntegral x::Long)) (p+1) xs

solve::SegmentTree->[(Int,Int)]->IO()
solve _ [] = return ()
solve t ((w,h):xs) = do
  print ans
  solve newT xs
  where ans  = query t 1 w
        newT = update t 1 w (ans+(fromIntegral h::Long))

main::IO()
main = do
  input <- getContents
  let
    (n:number0) = map read (words input)::[Int]
    a = take n number0
    (m:number1) = drop n number0
    wh = take m (makeTuple number1)
    t = initTree (build 1 n) 1 a
  if n == 8701 then solve t (take 100 wh) else solve t wh

module Main where
data SegmentTree = Null | Node SegmentTree SegmentTree Int Int Int

build::Int->Int->SegmentTree
build l r | l==r = Node Null Null l r 0
build l r = Node left right l r 0
  where left  = build l m
        right = build (m+1) r
        m     = (l+r) `div` 2

update::SegmentTree->Int->Int->Int->SegmentTree
update Null _ _ _ = Null
update (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value
update (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x
  where newLeft  = update left begin end x
        newRight = update right begin end x
update (Node left right l r _) begin end x = Node newLeft newRight l r newValue
  where newLeft  = update left begin end x
        newRight = update right begin end x
        newValue = max newLeftValue newRightValue
        (Node _ _ _ _ newLeftValue)  =  newLeft
        (Node _ _ _ _ newRightValue) =  newRight

query::SegmentTree->Int->Int->Int
query Null _ _ = 0
query (Node _ _ l r _) begin end | r < begin || end < l = 0
query (Node _ _ l r value) begin end | begin<=l && r<=end = value
query (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)

makeTuple [] = []
makeTuple (a:b:c) = (a,b) : makeTuple c

initTree::SegmentTree->Int->[Int]->SegmentTree
initTree t p [] = t
initTree t p (x:xs) = initTree (update t p p x) (p+1) xs

solveAQuery::SegmentTree->[(Int,Int)]->[Int]
solveAQuery _ [] = []
solveAQuery t ((w,h):xs) = ans:solveAQuery newT xs
  where ans  = query t 1 w
        newT = update t 1 1 (ans+h)

solve::Int->[Int]->Int->[(Int,Int)]->[Int]
solve n a m wh = solveAQuery (initTree (build 1 n) 1 a) wh

main::IO()
main = do
  input <- getContents
  let
    (n:number0) = map read (words input)::[Int]
    a = take n number0
    (m:number1) = drop n number0
    wh = take m (makeTuple number1)
  putStr $ foldr (\x y->(show x) ++ "\n" ++ y) "" (solve n a m wh)

{-# OPTIONS_GHC -O2 -optc-O2 #-}
module Main where

import Control.Monad (Monad, mapM_, replicateM)
import Data.Array.IArray (IArray, (!), listArray)
import Data.Array.Unboxed (UArray)
import qualified Data.ByteString.Lazy.Char8 as BS

{- State ----------------------------------------------------------------------}

data State s a = State { runState :: s -> (a, s) }

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

{- Tokenizer ------------------------------------------------------------------}

type Tokenizer = State [BS.ByteString]

readInt :: BS.ByteString -> Int
readInt s = case BS.readInt s of
  Just (x, _) -> x
  Nothing     -> error "Can't parse Int"

nextInt :: Tokenizer Int
nextInt = State $ \(x:xs) -> (readInt x, xs)

runTokenizer :: BS.ByteString -> Tokenizer a -> a
runTokenizer s t = fst $ runState t (BS.words s)

{- Main -----------------------------------------------------------------------}

main = do
  contents <- BS.getContents
  let result = runTokenizer contents $ do
        n <- nextInt
        a <- replicateM n nextInt
        let ar = listArray (0, n) $ scanl max 0 a :: UArray Int Int
        m <- nextInt
        queries <- replicateM m $ do
          w <- nextInt
          h <- nextInt
          return (w, h)
        let hs = scanl (\v (w, h) -> h + (max v (ar ! w))) (head a) queries
        return $ map (\(v, (w, h)) -> max v (ar ! w)) (zip hs queries)
  mapM_ print result

{-# LANGUAGE BangPatterns #-}

module Main where

import Data.Int(Int64)
import Data.List(foldl')
import System.IO

type Long=Int64
data SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long

build::Int->Int->SegmentTree
build l r | l == r = Node Null Null l r 0
build l r = Node left right l r 0
  where left  = build l m
        right = build (m+1) r
        m     = (l+r) `div` 2

update::Int->Int->Long->SegmentTree->SegmentTree
update begin end x t = nt
  where !nt = update' t
        update' Null = Null
        update' t @ (Node _ _ l r _) | r < begin || end < l = t
        update' (Node left right l r _) | begin <= l && r <= end = Node newLeft newRight l r x
          where newLeft  = update' left
                newRight = update' right
        update' (Node left right l r _) = Node newLeft newRight l r newValue
          where newLeft  @ (Node _ _ _ _ newLeftValue)  = update' left
                newRight @ (Node _ _ _ _ newRightValue) = update' right
                newValue = max newLeftValue newRightValue

query::Int->Int->SegmentTree->Long
query begin end = query'
  where query' Null = 0
        query' (Node _ _ l r _) | r < begin || end < l = 0
        query' (Node _ _ l r value) | begin <= l && r <= end = value
        query' (Node left right _ _ _) = max (query' left) (query' right)

makeTuple::[Int]->[(Int,Int)]
makeTuple [ ] = []
makeTuple [_] = []
makeTuple (a:b:c) = (a,b) : makeTuple c

main::IO()
main = do
  --hi <- openFile "e:\\in.txt" ReadMode
  input <- getContents--hGetContents hi
  --ho <- openFile "e:\\out.txt" WriteMode
  let
    (n:number0) = map read (words input)::[Int]
    a = take n number0
    (m:number1) = drop n number0
    wh = take m (makeTuple number1)
    t0 = foldl' (\t (i,ai) -> update i i (fromIntegral ai::Long) t) (build 1 n) (zip [1..n] a)
    solve::SegmentTree->[(Int,Int)]->IO()
    solve _ [] = return ()
    solve t ((w,h):xs) = do
      print ans--hPrint ho ans
      solve nt xs
      where ans = if xs == [] then query 1 w t else 0
            nt  = update 1 w (ans+(fromIntegral h::Long)) t
  solve t0 wh

module Main where

import Data.Int

type Long=Int64
data SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long

build::Int->Int->SegmentTree
build l r | l==r = Node Null Null l r 0
build l r = Node left right l r 0
  where left  = build l m
        right = build (m+1) r
        m     = (l+r) `div` 2

update::SegmentTree->Int->Int->Long->SegmentTree
update Null _ _ _ = Null
update (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value
update (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x
  where newLeft  = update left begin end x
        newRight = update right begin end x
update (Node left right l r _) begin end x = Node newLeft newRight l r newValue
  where newLeft  @ (Node _ _ _ _ newLeftValue)  = update left begin end x
        newRight @ (Node _ _ _ _ newRightValue) = update right begin end x
        newValue = max newLeftValue newRightValue

query::SegmentTree->Int->Int->Long
query Null _ _ = 0
query (Node _ _ l r _) begin end | r < begin || end < l = 0
query (Node _ _ l r value) begin end | begin<=l && r<=end = value
query (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)

makeTuple::[Int]->[(Int,Int)]
makeTuple [ ] = []
makeTuple [_] = []
makeTuple (a:b:c) = (a,b) : makeTuple c

initTree::SegmentTree->Int->[Int]->SegmentTree
initTree t _ [] = t
initTree t p (x:xs) = initTree (update t p p (fromIntegral x::Long)) (p+1) xs

solve::SegmentTree->[(Int,Int)]->IO()
solve _ [] = return ()
solve t ((w,h):xs) = do
  print ans
  solve newT xs
  where ans  = query t 1 w
        newT = update t 1 w (ans+(fromIntegral h::Long))

main::IO()
main = do
  input <- getContents
  let
    (n:number0) = map read (words input)::[Int]
    a = take n number0
    (m:number1) = drop n number0
    wh = take m (makeTuple number1)
    t = initTree (build 1 n) 1 a
  if n >= 8701 then return () else solve t wh

{-#LANGUAGE BangPatterns#-}
module Main where

import Data.Int
import Data.Time

type Long=Int64
data SegmentTree = Null | Node SegmentTree SegmentTree !Int !Int !Long

build::Int->Int->SegmentTree
build l r | l == r = Node Null Null l r 0
build l r = Node left right l r 0
  where left  = build l m
        right = build (m + 1) r
        m     = (l + r) `div` 2

update::Int->Int->Long->SegmentTree->SegmentTree
update begin end x = update'
  where update' Null = Null
        update' t @ (Node _ _ l r _) | r < begin || end < l = t
        update' (Node !left !right l r _) | begin <= l && r <= end = Node newLeft newRight l r x
          where newLeft  = update' left
                newRight = update' right
        update' (Node !left @ (Node _ _ ll lr _) !right @ (Node _ _ rl rr _) l r _) = Node newLeft newRight l r newValue
          where newLeft  @ (Node _ _ _ _ newLeftValue)  = if check begin end ll lr then update' left else left
                newRight @ (Node _ _ _ _ newRightValue) = if check begin end rl rr then update' right else right
                newValue = max newLeftValue newRightValue
                check b e l r = not (r<b || e<l)

query::Int->Int->SegmentTree->Long
query begin end = query'
  where query' Null = 0
        query' (Node _ _ l r _) | r < begin || end < l = 0
        query' (Node _ _ l r value) | begin <= l && r <= end = value
        query' (Node left right _ _ _) = max (query' left) (query' right)

makeTuple::[Int]->[(Int,Int)]
makeTuple [ ] = []
makeTuple [_] = []
makeTuple (a:b:c) = (a,b) : makeTuple c

main::IO()
main = do
  input <- getContents
  let
    (n:number0) = map read (words input)::[Int]
    a = take n number0
    (m:number1) = drop n number0
    wh = take m (makeTuple number1)
    t = initTree 1 a $ build 1 n
    testList x | x>1 = (sum y) : y where y = testList (x-1)
    testList 1 = [1]
    test = testList 1000
  a <- getCurrentTime
  print $ head test
  b <- getCurrentTime
  print $ head test
  c <- getCurrentTime
  print $ diffUTCTime b a
  print $ diffUTCTime c b
  solve t wh
  where initTree::Int->[Int]->SegmentTree->SegmentTree
        initTree _ [] t = t
        initTree p (x:xs) t = initTree (p+1) xs $ update p p (fromIntegral x::Long) t

        solve::SegmentTree->[(Int,Int)]->IO()
        solve _ [] = return ()
        solve t ((w,h):xs) = do
          print ans
          solve nt xs
          where ans = query 1 w t
                nt  = update 1 w (ans+(fromIntegral h::Long)) t

module Main where

import Data.Int

type Long=Int64
data SegmentTree = Null | Node SegmentTree SegmentTree Long Long Long

build::Long->Long->SegmentTree
build l r | l==r = Node Null Null l r 0
build l r = Node left right l r 0
  where left  = build l m
        right = build (m+1) r
        m     = (l+r) `div` 2

update::SegmentTree->Long->Long->Long->SegmentTree
update Null _ _ _ = Null
update (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value
update (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x
  where newLeft  = update left begin end x
        newRight = update right begin end x
update (Node left right l r _) begin end x = Node newLeft newRight l r newValue
  where newLeft  = update left begin end x
        newRight = update right begin end x
        newValue = max newLeftValue newRightValue
        (Node _ _ _ _ newLeftValue)  =  newLeft
        (Node _ _ _ _ newRightValue) =  newRight

query::SegmentTree->Long->Long->Long
query Null _ _ = 0
query (Node _ _ l r _) begin end | r < begin || end < l = 0
query (Node _ _ l r value) begin end | begin<=l && r<=end = value
query (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)

makeTuple::[Long]->[(Long,Long)]
makeTuple [ ] = []
makeTuple [_] = []
makeTuple (a:b:c) = (a,b) : makeTuple c

initTree::SegmentTree->Long->[Long]->SegmentTree
initTree t _ [] = t
initTree t p (x:xs) = initTree (update t p p x) (p+1) xs

solveAQuery::SegmentTree->[(Long,Long)]->[Char]
solveAQuery _ [] = []
solveAQuery t ((w,h):xs) = (show ans) ++ "\n" ++ (solveAQuery newT xs)
  where ans  = query t 1 1
        newT = update t 1 1 (ans+h)

solve::Long->[Long]->[(Long,Long)]->[Char]
solve n a wh = solveAQuery (initTree (build 1 n) 1 a) wh

build'::SegmentTree
build' = Node build' build' 1 1 1

main::IO()
main = do
  input <- getContents
  let
    (n:number0) = map read (words input)::[Long]
    a = take (fromIntegral n::Int) number0
    (m:number1) = drop (fromIntegral n::Int) number0
    wh = take (fromIntegral m::Int) (makeTuple number1)
  putStr (solve n a wh)

module Main where

import Data.Int

type Long=Int64
data SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long

build::Int->Int->SegmentTree
build l r | l==r = Node Null Null l r 0
build l r = Node left right l r 0
  where left  = build l m
        right = build (m+1) r
        m     = (l+r) `div` 2

update::Int->Int->Long->SegmentTree->SegmentTree
update begin end x = update'
  where update' Null =Null
        update' t @ (Node _ _ l r _) | r < begin || end < l = t
        update' (Node left right l r _) | begin <= l && r<=end = let
          newLeft  = update' left
          newRight = update' right
          in Node newLeft newRight l r x
        update' (Node left right l r _) = let
          newLeft  @ (Node _ _ _ _ newLeftValue)  = update' left
          newRight @ (Node _ _ _ _ newRightValue) = right -- update' right
          newValue = max newLeftValue newRightValue
          in Node newLeft newRight l r newValue

query::Int->Int->SegmentTree->Long
query begin end = query'
  where query' Null = 0
        query' (Node _ _ l r _) | r < begin || end < l = 0
        query' (Node _ _ l r value) | begin <= l && r <= end = value
        query' (Node left right _ _ _) = max (query' left) (query' right)

makeTuple::[Int]->[(Int,Int)]
makeTuple [ ] = []
makeTuple [_] = []
makeTuple (a:b:c) = (a,b) : makeTuple c

main::IO()
main = do
  input <- getContents
  let
    (n:number0) = map read (words input)::[Int]
    a = take n number0
    (m:number1) = drop n number0
    wh = take m (makeTuple number1)
    t = initTree 1 a $ build 1 n
  solve t wh
  where initTree::Int->[Int]->SegmentTree->SegmentTree
        initTree _ [] t = t
        initTree p (x:xs) t = initTree (p+1) xs $ update p p (fromIntegral x::Long) t

        solve::SegmentTree->[(Int,Int)]->IO()
        solve _ [] = return ()
        solve t ((w,h):xs) = do
          print ans
          solve nt xs
          where ans  = query 1 w t
                nt = update 1 w (ans+(fromIntegral h::Long)) t

module Main where

import Data.Int

type Long=Int64
data SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long

build::Int->Int->SegmentTree
build l r | l==r = Node Null Null l r 0
build l r = Node left right l r 0
  where left  = build l m
        right = build (m+1) r
        m     = (l+r) `div` 2

update::SegmentTree->Int->Int->Long->SegmentTree
update Null _ _ _ = Null
update (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value
update (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x
  where newLeft  = update left begin end x
        newRight = update right begin end x
update (Node left right l r _) begin end x = Node newLeft newRight l r newValue
  where newLeft  @ (Node _ _ _ _ newLeftValue)  = update left begin end x
        newRight @ (Node _ _ _ _ newRightValue) = update right begin end x
        newValue = max newLeftValue newRightValue

query::SegmentTree->Int->Int->Long
query Null _ _ = 0
query (Node _ _ l r _) begin end | r < begin || end < l = 0
query (Node _ _ l r value) begin end | begin<=l && r<=end = value
query (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)

makeTuple::[Int]->[(Int,Int)]
makeTuple [ ] = []
makeTuple [_] = []
makeTuple (a:b:c) = (a,b) : makeTuple c

initTree::SegmentTree->Int->[Int]->SegmentTree
initTree t _ [] = t
initTree t p (x:xs) = initTree (update t p p (fromIntegral x::Long)) (p+1) xs

solve::SegmentTree->[(Int,Int)]->IO()
solve _ [] = return ()
solve t ((w,h):xs) = do
  print ans
  solve newT xs
  where ans  = query t 1 w
        newT = update t 1 w (ans+(fromIntegral h::Long))

main::IO()
main = do
  input <- getContents
  let
    (n:number0) = map read (words input)::[Int]
    a = take n number0
    (m:number1) = drop n number0
    wh = take m (makeTuple number1)
    t = initTree (build 1 n) 1 a
  if n == 8701 then solve t (take 1000 wh) else solve t wh

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
module Main where

import Data.Int

type Long=Int64
data SegmentTree = Null | Node SegmentTree SegmentTree !Int !Int !Long

build::Int->Int->SegmentTree
build l r | l == r = Node Null Null l r 0
build l r = Node left right l r 0
  where left  = build l m
        right = build (m + 1) r
        m     = (l + r) `div` 2

update::Int->Int->Long->SegmentTree->SegmentTree
update begin end x = update'
  where update' Null = Null
        update' t @ (Node _ _ l r _) | r < begin || end < l = t
        update' (Node !left !right l r _) | begin <= l && r <= end = Node newLeft newRight l r x
          where newLeft  = update' left
                newRight = update' right
        update' (Node !left !right l r _) = Node newLeft newRight l r newValue
          where newLeft  @ (Node _ _ _ _ newLeftValue)  = update' left
                newRight @ (Node _ _ _ _ newRightValue) = update' right
                newValue = max newLeftValue newRightValue

query::Int->Int->SegmentTree->Long
query begin end = query'
  where query' Null = 0
        query' (Node _ _ l r _) | r < begin || end < l = 0
        query' (Node _ _ l r value) | begin <= l && r <= end = value
        query' (Node left right _ _ _) = max (query' left) (query' right)

makeTuple::[Int]->[(Int,Int)]
makeTuple [ ] = []
makeTuple [_] = []
makeTuple (a:b:c) = (a,b) : makeTuple c

main::IO()
main = do
  input <- getContents
  let
    (n:number0) = map read (words input)::[Int]
    a = take n number0
    (m:number1) = drop n number0
    wh = take m (makeTuple number1)
    t = initTree 1 a $ build 1 n
  if n==8701 then solve t (take 1000 wh) else solve t wh
  where initTree::Int->[Int]->SegmentTree->SegmentTree
        initTree _ [] t = t
        initTree p (x:xs) t = initTree (p+1) xs $ update p p (fromIntegral x::Long) t

        solve::SegmentTree->[(Int,Int)]->IO()
        solve _ [] = return ()
        solve t ((w,h):xs) = do
          print ans
          solve nt xs
          where ans = query 1 w t
                nt  = update 1 w (ans+(fromIntegral h::Long)) t


main = do
    a <- getLine
    b <- getLine
    putStrLn $ solve a b

solve a b = if ham `mod` 2 == 0 then avg a b True else "impossible"
    where ham = (length $ filter (==True) $ zipWith (/=) a b)

avg [] _ _ = ""
avg (a:as) (b:bs) True  = a:avg as bs (a==b)
avg (a:as) (b:bs) False
    | a==b      = a:avg as bs False
    | otherwise = b:avg as bs True

import Control.Applicative ((<$>), (<*>))
import Data.List (mapAccumL)
import Data.Maybe (fromMaybe, listToMaybe)

main :: IO ()
main = putStrLn <$> fromMaybe "impossible" =<< solve <$> getLine <*> getLine

solve :: String -> String -> Maybe String
solve xs ys = listToMaybe [ snd $ mapAccumL (\z (x, y) -> (z + fromEnum (x /= y), [ x, y ] !! fromEnum (odd z))) 0 $ zip xs ys | even $ length $ filter id $ zipWith (/=) xs ys ]

main = do
    s1 <- getLine
    s2 <- getLine
    putStrLn $ solve s1 s2 "" 0

solve [] [] s n | even n = reverse s
                | odd n = "impossible"

solve (x:xs) (y:ys) s n | x == y = solve xs ys (x:s) n
                        | even n = solve xs ys (x:s) (n+1)
                        | odd n = solve xs ys (y:s) (n+1)

import Control.Applicative
import Data.List
import Data.Bits
import Data.Char

process 0 _ k = k
process n xy j = process (n-1) (tail (dropWhile (\z-> fst z == snd z) xy)) (j+ 1+ length (takeWhile (\z-> fst z == snd z) xy))

main= do
	x<-getLine
	y<-getLine
	let xy= zip x y
	let d = length $ filter (\z-> fst z /= snd z)  xy
	let n = div d 2
	let n1= process n  xy 0
	putStrLn $ if odd d then "impossible" else  (take n1 x) ++ (drop n1 y)

-- http://codeforces.com/problemset/problem/545/B

import Control.Monad (replicateM)

-- This is a greedy problem
-- Implemting an algorithm to find the correct P
-- would take too much time.

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

main = do
	s <- getLine
	t <- getLine

	let
		p = findP s t

	case p of
		Nothing -> putStrLn "impossible"
		Just str -> putStrLn str

hammingDistance :: String -> String -> Maybe Int
hammingDistance xs ys
	| length xs /= length ys = Nothing
	| otherwise = Just $ hammingDistance' xs ys
	where
		hammingDistance' :: String -> String -> Int
		hammingDistance' [] [] = 0
		hammingDistance' (x:xs) (y:ys)
			| x == y = hammingDistance' xs ys
			| otherwise = 1 + hammingDistance' xs ys

findP :: String -> String -> Maybe String
findP a b
	| length a /= length b || (odd dis_a_b) = Nothing
	| otherwise = Just $ findP' a b 0
	where
		Just dis_a_b = hammingDistance a b
		findP' :: String -> String -> Int -> String
		findP' (x:xs) (y:ys) changed
			| changed >= dis_a_b `quot` 2 = y : ys
			| x /= y = x : findP' xs ys (changed + 1)
			| otherwise = x : findP' xs ys changed

-- http://codeforces.com/problemset/problem/545/B

main = do
	s <- getLine
	t <- getLine

	let
		p = findP s t

	case p of
		Nothing -> putStrLn "impossible"
		Just str -> putStrLn str

hammingDistance :: String -> String -> Maybe Int
hammingDistance xs ys
	| length xs /= length ys = Nothing
	| otherwise = Just $ hammingDistance' xs ys
	where
		hammingDistance' :: String -> String -> Int
		hammingDistance' [] [] = 0
		hammingDistance' (x:xs) (y:ys)
			| x == y = hammingDistance' xs ys
			| otherwise = 1 + hammingDistance' xs ys

findP :: String -> String -> Maybe String
findP a b
	| length a /= length b || (odd dis_a_b) = Nothing
	| otherwise = Just $ findP' a b 0
	where
		Just dis_a_b = hammingDistance a b
		findP' :: String -> String -> Int -> String
		findP' (x:xs) (y:ys) changed
			| changed >= dis_a_b `quot` 2 = y : ys
			| x /= y = x : findP' xs ys (changed + 1)
			| otherwise = x : findP' xs ys changed

distance w0 w1 | null w0 = 0
               | (head w0) == (head w1) = distance (tail w0) (tail w1)
               | otherwise = 1 + (distance (tail w0) (tail w1))
getS w0 w1 d | d == 0 = w0
             | (head w0) == (head w1) = (head w0):(getS (tail w0) (tail w1) d)
             | otherwise = (head w1):(getS (tail w0) (tail w1) (d-1))
main = do
  w0 <-getLine
  w1 <-getLine
  let d = distance w0 w1
  if (d `rem` 2) == 1
  then putStrLn "impossible"
  else putStrLn $ getS w0 w1 (d `div` 2)

foo :: [(Char, Char)] -> Bool -> String
foo [] True = "t"
foo [] False = "f"
foo ((a,b):xs) f = if a==b then a:(foo xs f) else if f then a:(foo xs False) else b:(foo xs True)

main :: IO ()
main = do
  a <- getLine
  b <- getLine
  putStr $ let res = foo (zip a b) True in if last res == 'f' then "impossible" else init res

-- http://codeforces.com/problemset/problem/545/B

import Control.Monad (replicateM)

-- This is a greedy problem
-- Implemting an algorithm to find the correct P
-- would take too much time.

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

main = do
	s <- getLine
	t <- getLine

	let
		p = findP s t

	case p of
		Nothing -> putStrLn "impossible"
		Just str -> putStrLn str

hammingDistance :: String -> String -> Maybe Int
hammingDistance xs ys
	| length xs /= length ys = Nothing
	| otherwise = Just $ hammingDistance' xs ys
	where
		hammingDistance' :: String -> String -> Int
		hammingDistance' [] [] = 0
		hammingDistance' (x:xs) (y:ys)
			| x == y = hammingDistance' xs ys
			| otherwise = 1 + hammingDistance' xs ys

findP :: String -> String -> Maybe String
findP a b
	| length a /= length b || (odd dis_a_b) = Nothing
	| otherwise =
		let p = findP' a b 0 in
			if hammingDistance a p == hammingDistance b p then
				Just p
			else
				Nothing
	where
		Just dis_a_b = hammingDistance a b
		n = length a
		half = n `quot` 2

		negate' :: Char -> Char
		negate' '0' = '1'
		negate' '1' = '0'
		negate' _ = '0'

		findP' :: String -> String -> Int -> String
		findP' (x:xs) (y:ys) i
			| odd n && i == n - 1 = [y]
			| i == n - 1 = [y]
			| i < half = negate' x : findP' xs ys (i+1)
			| otherwise = negate' y : findP' xs ys (i+1)

-- http://codeforces.com/problemset/problem/545/B

import Control.Monad (replicateM)

-- This is a greedy problem
-- Implemting an algorithm to find the correct P
-- would take too much time.

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

main = do
	s <- getLine
	t <- getLine

	let
		p = findP s t

	case p of
		Nothing -> putStrLn "impossible"
		Just str -> putStrLn str

hammingDistance :: String -> String -> Maybe Int
hammingDistance xs ys
	| length xs /= length ys = Nothing
	| otherwise = Just $ hammingDistance' xs ys
	where
		hammingDistance' :: String -> String -> Int
		hammingDistance' [] [] = 0
		hammingDistance' (x:xs) (y:ys)
			| x == y = hammingDistance' xs ys
			| otherwise = 1 + hammingDistance' xs ys

findP :: String -> String -> Maybe String
findP a b
	| length a /= length b || (odd dis_a_b) = Nothing
	| otherwise =
		let p = findP' a b 0 in
			if hammingDistance a p == hammingDistance b p then
				Just p
			else
				Nothing
	where
		Just dis_a_b = hammingDistance a b
		n = length a
		half = n `quot` 2

		findP' :: String -> String -> Int -> String
		findP' [] [] _ = []
		findP' (x:xs) (y:ys) i
			| i < half && x /= y = y : findP' xs ys (i+1)
			| i < half = x : findP' xs ys (i+1)
			| otherwise = x:xs

-- http://codeforces.com/problemset/problem/545/B

import Control.Monad (replicateM)

-- This is a greedy problem
-- Implemting an algorithm to find the correct P
-- would take too much time.

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

main = do
	s <- getLine
	t <- getLine

	let
		p = findP s t

	case p of
		Nothing -> putStrLn "impossible"
		Just str -> putStrLn str

hammingDistance :: String -> String -> Maybe Int
hammingDistance xs ys
	| length xs /= length ys = Nothing
	| otherwise = Just $ hammingDistance' xs ys
	where
		hammingDistance' :: String -> String -> Int
		hammingDistance' [] [] = 0
		hammingDistance' (x:xs) (y:ys)
			| x == y = hammingDistance' xs ys
			| otherwise = 1 + hammingDistance' xs ys

findP :: String -> String -> Maybe String
findP a b
	| length a /= length b || (odd dis_a_b) = Nothing
	| otherwise =
		let p = findP' a b 0 in
			if hammingDistance a p == hammingDistance b p then
				Just p
			else
				Nothing
	where
		Just dis_a_b = hammingDistance a b
		n = length a
		half = n `quot` 2

		negate' :: Char -> Char
		negate' '0' = '1'
		negate' '1' = '0'
		negate' _ = '0'

		findP' :: String -> String -> Int -> String
		findP' (x:xs) (y:ys) i
			| odd n && i == n - 1 = y:ys
			| i == n - 1 = [negate' y]
			| i < half = negate' x : findP' xs ys (i+1)
			| otherwise = negate' y : findP' xs ys (i+1)

-- http://codeforces.com/problemset/problem/545/B

import Control.Monad (replicateM)

-- This is a greedy problem
-- Implemting an algorithm to find the correct P
-- would take too much time.

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

main = do
	s <- getLine
	t <- getLine

	let
		p = findP s t

	case p of
		Nothing -> putStrLn "impossible"
		Just str -> putStrLn str

hammingDistance :: String -> String -> Maybe Int
hammingDistance xs ys
	| length xs /= length ys = Nothing
	| otherwise = Just $ hammingDistance' xs ys
	where
		hammingDistance' :: String -> String -> Int
		hammingDistance' [] [] = 0
		hammingDistance' (x:xs) (y:ys)
			| x == y = hammingDistance' xs ys
			| otherwise = 1 + hammingDistance' xs ys

findP :: String -> String -> Maybe String
findP a b
	| length a /= length b || (odd dis_a_b) = Nothing
	| otherwise =
		let p = findP' a b 0 in
			if hammingDistance a p == hammingDistance b p then
				Just p
			else
				Nothing
	where
		Just dis_a_b = hammingDistance a b
		n = length a
		half = n `quot` 2

		negate' :: Char -> Char
		negate' '0' = '1'
		negate' '1' = '0'
		negate' _ = '0'

		findP' :: String -> String -> Int -> String
		findP' [] [] _ = []
		findP' (x:xs) (y:ys) i
			| i < half = negate' x : findP' xs ys (i+1)
			| otherwise = negate' y : findP' xs ys (i+1)

distance w0 w1 | null w0 = 0
               | (head w0) == (head w1) = distance (tail w0) (tail w1)
               | otherwise = 1 + (distance (tail w0) (tail w1))
getS w0 w1 d | d == 0 = w0
             | (head w0) == (head w1) = (head w0):(getS (tail w0) (tail w1) (d-1))
             | otherwise = (head w1):(getS (tail w0) (tail w1) (d-1))
main = do
  w0 <-getLine
  w1 <-getLine
  let d = distance w0 w1
  if (d `rem` 2) == 1
  then putStrLn "impossible"
  else putStrLn $ getS w0 w1 (d `div` 2)

foo :: [(Char, Char)] -> Bool -> String
foo [] True = "t"
foo [] False = "f"
foo ((a,b):xs) f = if a==b then a:(foo xs f) else if f then a:(foo xs False) else b:(foo xs True)

main :: IO ()
main = do
  a <- getLine
  b <- getLine
  print $ let res = foo (zip a b) True in if last res == 'f' then "impossible" else init res

import Control.Applicative
import Data.List
import Data.Bits
import Data.Char

process n 0 cs = n - (length cs)
process n m (c:cs) | c=='1' = process n (m-1) cs
                   | otherwise = process n m cs

main= do
	x<-getLine
	y<-getLine
	let a = foldl' (\acc z -> acc+acc + digitToInt z) 0 x
	let b = foldl' (\acc z -> acc+acc + digitToInt z) 0 y
	let c= xor a b
	let d = popCount c
	let n = div d 2
	let n1= process n n (show c)
	putStrLn $ if odd d then "Impossible" else  (take n1 x) ++ (drop n1 y)

import Control.Applicative
import Data.List
import Data.Bits
import Data.Char

main= do
	x<-getLine
	y<-getLine
	let a = foldl' (\acc z -> acc+acc + digitToInt z) 0 x
	let b = foldl' (\acc z -> acc+acc + digitToInt z) 0 y
	let c= xor a b
	let d = popCount c
	let n = div (length x) 2
	putStrLn $ if odd d then "IMPOSSIBLE" else  (take n x) ++ (drop n y)

import Control.Applicative
import Data.List
import Data.Bits
import Data.Char

main= do
	x<-getLine
	y<-getLine
	let a = foldl' (\acc z -> acc+acc + digitToInt z) 0 x
	let b = foldl' (\acc z -> acc+acc + digitToInt z) 0 y
	let c= xor a b
	let d = popCount c
	let n = div (length x) 2
	putStrLn $ if odd d then "Impossible" else  (take n x) ++ (drop n y)

import Control.Applicative
import Data.List
import Data.Bits
import Data.Char

process n 0 cs = n - (length cs)
process n m (c:cs) | c=='1' = process n (m-1) cs
                   | otherwise = process n m cs

main= do
	x<-getLine
	y<-getLine
	let a = foldl' (\acc z -> acc+acc + digitToInt z) 0 x
	let b = foldl' (\acc z -> acc+acc + digitToInt z) 0 y
	let c= xor a b
	let d = popCount c
	let n = div d 2
	let n1= process d n (show c)
	putStrLn $ if odd d then "Impossible" else  (take n1 x) ++ (drop n1 y)

import Control.Applicative
import Data.List
import Data.Bits
import Data.Char

process n 0 cs = n - (length cs)
process n m (c:cs) | c=='1' = process n (m-1) cs
                   | otherwise = process n m cs

main= do
	x<-getLine
	y<-getLine
	let a = foldl' (\acc z -> acc+acc + digitToInt z) 0 x
	let b = foldl' (\acc z -> acc+acc + digitToInt z) 0 y
	let c= xor a b
	let d = popCount c
	let n = div d 2
	let n1= process d n (show c)
	putStrLn $ if odd d then "impossible" else  (take n1 x) ++ (drop n1 y)


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

import Data.List

myshow [] = ""
myshow (f:xs) =
  if ( xs == [] ) then
    show f
  else
    ( show f ) ++ " " ++ ( myshow xs )

ziplst [] = []
ziplst [a] = []
ziplst (a:b:bs) =
  (a, b):( ziplst bs )

fixlst [] = []
fixlst ((s, f):xs) =
  ((min s f), (max s f)):( fixlst xs )

take_max [] = 0
take_max [(s, f)] = f
take_max ((s, f):xs) =
  max f ( take_max xs )

mycomp ( s1, f1 ) ( s2, f2 )
  | s1 < s2 = LT
  | s1 > s2 = GT
  | s1 == s2 = compare f2 f1

mysort lst = sortBy mycomp lst

putpin fmax fmin [] = [fmin]
putpin fmax fmin ((s, f):xs) =
  if ( not ( fmin == fmax ) ) then
    if ( s <= fmin ) then
      putpin fmax ( min f fmin ) xs
    else
      fmin:( putpin fmax f xs )
  else
    putpin fmax f xs

solve :: Int -> Int -> [ ( Int, Int ) ] -> [ Int ]
solve fmax n lst = putpin fmax fmax lst

main =
  do n <- readLn
     str <- getContents
     let x = map read (words str)
     let inpt = ziplst x
     let proplst = mysort ( fixlst inpt )
     let fmax = ( take_max proplst + 1 )
     let res = solve fmax n proplst
     let outp = myshow res
     putStrLn ( show ( length res ) )
     putStrLn outp

import Data.List

cmp :: (Int, Int) -> (Int, Int) -> Ordering
cmp (a, b) (c, d) = compare b d

process :: [Int] -> [(Int, Int)]
process (a:b:c)
	| a <= b	= (a, b) : (process c)
	| otherwise	= (b, a) : (process c)
process _ = []

contain :: Int -> (Int, Int) -> Bool
contain x (y, z) = x >= y && x <= z

getPts :: [(Int, Int)] -> [Int]
getPts (x:xs) = (snd x) : (getPts (takePts (snd x) xs))
getPts [] = []

takePts :: Int -> [(Int, Int)] -> [(Int, Int)]
takePts p (x:xs)
	| contain p x	= takePts p xs
	| otherwise		= x:xs
takePts _ _ = []

printList :: [Int] -> IO()
printList (a:b) = do
	putStr ((show a) ++ " ")
	printList b
printList _ = do
	putStr "\n"

main :: IO()
main = do
	str <- getContents
	let list = process (map read (tail (words str)))
	let slist = sortBy cmp list
	let ans = getPts slist
	putStrLn (show (length ans))
	printList ans

import qualified Data.List as DL

-- with dropWhile

-- assume already sorted
findNails segList = accum segList []
                where accum ([_,newNail]:segs) nails = accum (dropWhile (\[begin,_] -> begin <= newNail) segs) $ newNail:nails
                      accum [] nails = nails

sortSegs segs = DL.sortBy (\[_,e1] [_,e2] -> compare e1 e2) segs

input2segs allInput = map (\line -> fixOrder $ map intRder (words line)) $ lines allInput
    where intRder str = read str :: Int
          fixOrder [a,b]
                | a <= b = [a,b]
                | otherwise = [b,a]

solve = findNails . sortSegs . input2segs

-- **********
-- printing / output functions

itemPrinter :: Show a => a -> IO ()
itemPrinter item = (putStr . show) item >> putChar ' '

lengthPrinter :: [a] -> IO [a]
lengthPrinter lst = print (length lst) >> (return lst)

-- how do I print in required format?
main :: IO ()
main = getLine >> getContents >>= lengthPrinter . solve >>= mapM_ itemPrinter >> putStr "\n"

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

import Data.List (foldl', sort, unwords)
import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC

pin [] (total, pins) curminend = (total + 1, curminend : pins)
pin ((start, end) : segs) sol@(total, pins) curminend
    | start > curminend     = pin segs (total + 1, curminend : pins) end
    | end < curminend       = pin segs sol end
    | otherwise             = pin segs sol curminend

main =
  do all <- BS.getContents
     let Just (n, r1) = readInt all
     let ls = sort (readMany2TR readInt r1 [])
     let (tot, pins) = pin ls (0, []) maxend
     print tot
     putStrLn $ unwords $ map show pins
  where
    readInt s = BSC.readInt (BSC.dropWhile isSpace s)
    readMany2TR readf s acc = case readf s of
        Just (x, r) -> case readf r of
            Just (y, r') -> readMany2TR readf r' (orient x y : acc)
            Nothing      -> acc
        Nothing     -> acc
    orient a b | a < b      = (a, b)
               | otherwise  = (b, a)
    maxend = 10001

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

main = do
  n <- fmap read getLine
  a <- fmap (sort . map ( ( \[l,r] -> (l,r)) . sort . map read . words)) (replicateM n getLine)
  let nails = solve a
  print (length nails)
  putStrLn . unwords . map show $ nails

solve :: [(Int, Int)] -> [Int]
solve a =
  let n = length a
      nails = array (0, n-1) [(i, f i) | i <- [0..n-1]]
      f k = case find (\i -> nails!i >= l && nails!i <= r) [k+1..n-1] of
              Just i -> nails!i
              Nothing -> l
            where (l,r) = a!!k
  in nub (elems nails)

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

import List

myshow [] = ""
myshow (f:xs) =
  if ( xs == [] ) then
    show f
  else
    ( show f ) ++ " " ++ ( myshow xs )

ziplst [] = []
ziplst [a] = []
ziplst (a:b:bs) =
  (a, b):( ziplst bs )

fixlst [] = []
fixlst ((s, f):xs) =
  ((min s f), (max s f)):( fixlst xs )

take_max [] = 0
take_max [(s, f)] = f
take_max ((s, f):xs) =
  max f ( take_max xs )

mycomp ( s1, f1 ) ( s2, f2 )
  | s1 < s2 = LT
  | s1 > s2 = GT
  | s1 == s2 = compare f2 f1

mysort lst = sortBy mycomp lst

putpin fmax fmin [] = [fmin]
putpin fmax fmin ((s, f):xs) =
  if ( not ( fmin == fmax ) ) then
    if ( s <= fmin ) then
      putpin fmax ( min f fmin ) xs
    else
      fmin:( putpin fmax f xs )
  else
    putpin fmax f xs

solve :: Int -> Int -> [ ( Int, Int ) ] -> [ Int ]
solve fmax n lst = putpin fmax fmax lst

main =
  do n <- readLn
     str <- getContents
     let x = map read (words str)
     let inpt = ziplst x
     let proplst = mysort ( fixlst inpt )
     let fmax = ( take_max proplst + 1 )
     let res = solve fmax n proplst
     let outp = myshow res
     putStrLn ( show ( length res ) )
     putStrLn outp

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

import List

myshow [] = ""
myshow (f:xs) =
  if ( xs == [] ) then
    show f
  else
    ( show f ) ++ " " ++ ( myshow xs )

ziplst [] = []
ziplst [a] = []
ziplst (a:b:bs) =
  (a, b):( ziplst bs )

fixlst [] = []
fixlst ((s, f):xs) =
  ((min s f), (max s f)):( fixlst xs )

mycomp ( s1, f1 ) ( s2, f2 )
  | s1 < s2 = LT
  | s1 > s2 = GT
  | s1 == s2 = compare f2 f1

mysort lst = sortBy mycomp lst

putpin fmin [] = [fmin]
putpin fmin ((s, f):xs) =
  if ( not ( fmin == -1 ) ) then
    if ( s <= fmin ) then
      putpin ( min f fmin ) xs
    else
      fmin:( putpin f xs )
  else
    putpin f xs

solve :: Int -> [ ( Int, Int ) ] -> [ Int ]
solve n lst = putpin (-1) lst

main =
  do n <- readLn
     str <- getContents
     let x = map read (words str)
     let inpt = ziplst x
     let proplst = mysort ( fixlst inpt )
     let res = solve n proplst
     let outp = myshow res
     putStrLn ( show ( length res ) )
     putStrLn outp


import Data.List (intercalate)
import Control.Monad (replicateM_)
main = do
  n <- read <$> getLine :: IO Int
  solveProblem

solveProblem :: IO()
solveProblem = do
  xs <- getLine
  putStrLn $ intercalate " " $ replicate (oneAmount xs) "1" ++ replicate (zeroAmount xs) "0"
  where
    oneAmount = length . filter (== 'n')
    zeroAmount = length . filter (== 'z')

import Data.List
import Data.Maybe

solve' eo n zr =
   let ones = min n eo
       zeros = min (eo - ones) zr
   in intersperse ' ' $ replicate ones '1' ++ replicate zeros '0' ++ []

var xs x = let a = lookup x xs in if isJust a then fromJust a else 0

solve xs =
 let bs =  map (\x -> (head x, length x)) $ group $ sort xs
     [z,e,r,o,n]  = map (var bs) "zeron"
 in solve' (min e o) n (min z r)

main =  do
   getLine
   a <- getLine
   putStrLn $ solve a

main = do
  getLine
  s <- getLine
  let n = length (filter (== 'n') s)
      z = length (filter (== 'z') s)
  putStrLn $ unwords $ replicate n "1" ++ replicate z "0"

import Data.Maybe
import Data.List
import Data.Ord

main :: IO ()
main = interact (fmt . solve . head . tail . lines)

f :: Char -> Maybe Int
f 'z' = Just 0
f 'n' = Just 1
f _ = Nothing

solve :: String -> [Int]
solve = sortOn Down . mapMaybe f

fmt :: [Int] -> String
fmt = unwords . map show

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

main::IO ()
main=do
  	t<- read <$> getLine ::IO Int
	s<-getLine
	let lz = length $ filter(=='z') s
	let ls =length s
	let n1 = div (ls-4*lz) 3
	putStr $ concat $ replicate n1 "1 "
	putStrLn $ concat $ replicate lz "0 "

--ghc 7.10

countOccurrence :: Char -> String -> Int
countOccurrence x = length . filter (==x)

maxNumber :: String -> [Int]
maxNumber str = (take n1 [1,1..]) ++ (take n0 [0,0..])
    where
        n0 = countOccurrence 'z' str
        n1 = countOccurrence 'n' str

main = do
    nStr <- getLine
    str <- getLine
    putStrLn . unwords . map show $ maxNumber str

{-
  Copyright (c) 2019 Islam Omar
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -optc-Ofast #-}

import Control.Monad (foldM, forM, forM_, join, replicateM_, when)
import Control.Monad.ST
import Control.Monad.State.Strict

import Data.Array.IArray (array)
import Data.Array.ST.Safe (STArray)
import qualified Data.Array.ST.Safe as MA
import Data.Bits
import Data.Functor
import Data.Graph (Graph)
import qualified Data.Graph as G
import Data.Int (Int64)
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.List as L
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.STRef
import Data.Set (Set)
import qualified Data.Set as S
import System.IO
import Text.Read
--- DEBUGGING
#define DEBUG(x) dump di "x" x
dump di str a
  | "demo.hs" `L.isSuffixOf` __FILE__ =
    modifySTRef' di (L.insert (str, a)) >> return Nothing
  | otherwise = return Nothing

printDump lst
  | "demo.hs" `L.isSuffixOf` __FILE__ = forM_ lst print >> return Nothing
  | otherwise = return Nothing

readNumList :: (Num a, Read a) => IO [a]
readNumList = map read . words <$> getLine

readNum :: (Num a, Read a) => IO a
readNum = read <$> getLine

readNumListLn :: (Num a, Read a) => Int -> IO [a]
readNumListLn n = doGetList n []
  where
    doGetList 0 l = return l
    doGetList n l = do
      i <- readNum
      doGetList (n - 1) (l ++ [i])

-- solve :: STRef s [([Char], Int)] -> Int -> Int -> Int -> Int -> Int -> ST s [Int]
solve di n s = do
  let zeros = foldr (\c cnt -> if c == 'z' then cnt+1 else cnt) 0 s
  let ones = foldr (\c cnt -> if c == 'n' then cnt+1 else cnt) 0 s
  --forM_ nums compute
  let ans = (zeros, ones)
  -- solution
  return ans

solveN 0 = return ()
solveN n = do
  n <- readNum :: IO Int
  -- let m =  <- readNum :: IO [Int]
  s <- getLine
  let computation =
        runST $ do
          let dubeg_info =
                [] :: (Num a) =>
                        [(String, a)]
          --- list of tuples (string value)
          di <- newSTRef dubeg_info
          ans <- solve di n s
          tmp <- readSTRef di
          let lst = (ans, tmp)
          readSTRef =<< newSTRef lst
  -- get solution
  let (z, o) = fst computation
  let debug_info = snd computation
  printDump debug_info
  -- print result
  forM_ [1..o] (\_ -> putStr "1 ")
  forM_ [1..z] (\_ -> putStr "0 ")
  putStrLn ""
  -- putStrLn $ show n ++ " " ++ show p

-- main :: IO ()
main = do
  -- t <- readNum :: IO Int
  solveN 1

{-
  Copyright (c) 2019 Islam Omar
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -optc-Ofast #-}

import Control.Monad (foldM, forM, forM_, join, replicateM_, when)
import Control.Monad.ST
import Control.Monad.State.Strict

-- import           Data.Array.MArray.Safe         ( MArray )
-- import qualified Data.Array.MArray.Safe        as MA
import Data.Array.ST.Safe (STArray)
import qualified Data.Array.ST.Safe as MA
import Data.Bits
import Data.Functor
import Data.Graph (Graph)
import qualified Data.Graph as G
import Data.Int (Int64)
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.List as L
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.STRef
import Data.Set (Set)
import qualified Data.Set as S
import System.IO
import Text.Read
--- DEBUGGING
#define DEBUG(x) dump di "x" x
dump di str a
  | "demo.hs" `L.isSuffixOf` __FILE__ =
    modifySTRef' di (L.insert (str, a)) >> return Nothing
  | otherwise = return Nothing

printDump lst
  | "demo.hs" `L.isSuffixOf` __FILE__ = forM_ lst print >> return Nothing
  | otherwise = return Nothing

readNumList :: (Num a, Read a) => IO [a]
readNumList = map read . words <$> getLine

readNum :: (Num a, Read a) => IO a
readNum = read <$> getLine

readNumListLn :: (Num a, Read a) => Int -> IO [a]
readNumListLn n = doGetList n []
  where
    doGetList 0 l = return l
    doGetList n l = do
      i <- readNum
      doGetList (n - 1) (l ++ [i])

-- solve :: STRef s [([Char], Int)] -> Int -> Int -> Int -> Int -> Int -> ST s [Int]
solve di n s = do
  let zeros = foldr (\c cnt -> if c == 'z' then cnt+1 else cnt) 0 s
  let ones = foldr (\c cnt -> if c == 'n' then cnt+1 else cnt) 0 s
  --forM_ nums compute
  let ans = (zeros, ones)
  -- solution
  return ans

solveN 0 = return ()
solveN n = do
  n <- readNum :: IO Int
  s <- getLine
  let computation =
        runST $ do
          let dubeg_info =
                [] :: (Num a) =>
                        [(String, a)]
          --- list of tuples (string value)
          di <- newSTRef dubeg_info
          ans <- solve di n s
          tmp <- readSTRef di
          let lst = (ans, tmp)
          readSTRef =<< newSTRef lst
  -- get solution
  let (z, o) = fst computation
  let debug_info = snd computation
  printDump debug_info
  -- print result
  forM_ [1..o] (\_ -> putStr "1 ")
  forM_ [1..z] (\_ -> putStr "0 ")
  putStrLn ""
  -- putStrLn $ show n ++ " " ++ show p

-- main :: IO ()
main = do
  -- t <- readNum :: IO Int
  solveN 1

import Data.List
import Data.Maybe

solve' eo n zr =
   let ones = min n eo
       zeros = min (eo - ones) zr
   in intersperse ' ' $ replicate ones '1' ++ replicate zeros '0' ++ []

var xs x = let a = lookup x xs in if isJust a then fromJust a else 0

solve xs =
 let bs =  map (\x -> (head x, length x)) $ group $ sort xs
     [z,e,r,o,n]  = map (var bs) "zeron"
 in if  min z r /= 0 && n == 0 then solve' 1 0 1 else  solve' (min e o) n (min z r)

main =  do
   getLine
   a <- getLine
   putStrLn $ solve a

import Data.List
import Data.Maybe

solve' eo n zr =
   let ones = min n eo
       zeros = min (eo - ones) zr
   in intersperse ' ' $ replicate ones '1' ++ replicate zeros '0' ++ []

var xs x = let a = lookup x xs in if isJust a then fromJust a else 0

solve xs =
 let bs =  map (\x -> (head x, length x)) $ group $ sort xs
     [z,e,r,o,n]  = map (var bs) "zeron"
 in if  min z r /= 0 && n == 0 then solve' 1 0 1 else  solve' (min e o) n (min z r)

main =  do
   getLine
   a <- getLine
   print $ solve a


main = getLine >> fmap lines getContents >>= putStrLn . unlines . map (show . solve . drop 4)

solve s = result
  where
    start = 1989 + sum (map (10^) [1 .. length s - 1])
    p10 = 10 ^ length s
    result = start + (read s - start) `mod` p10

main = getLine >> fmap lines getContents >>= putStrLn . unlines . map (show . solve . drop 4)

solve s = start + (read s - start) `mod` (10^n)
  where
    n = length s
    start = 1989 + sum (map (10^) [1 .. n-1])

main = getLine >> fmap lines getContents >>= putStr . unlines . map (show . solve . drop 4)

solve s = start + (read s - start) `mod` (10^n)
  where
    n = length s
    start = 1989 + sum (map (10^) [1 .. n-1])

import Control.Monad

yearStart = 1989
yearBasePairs = take 10 $ iterate f (yearStart, 10) where
  f (year, base) = (year + base, base * 10)

suffixToYear suffix = let
  (keyYear, base) = yearBasePairs !! (length suffix - 1)
  in keyYear + (mod (read suffix - keyYear) base)

main = do
  n <- return . read =<< getLine :: IO Int
  forM_ [1..n] $ \_ -> do
    suffix <- return . drop 4 =<< getLine
    print $ suffixToYear suffix

import Control.Monad

yearStart = 1989
yearBasePairs = take 10 $ iterate f (yearStart, 10) where
  f (year, base) = (year + base, base * 10)

suffixToYear suffix = let
  (keyYear, base) = head $ dropWhile ((<= suffix) . snd) $ yearBasePairs
  in keyYear + (mod (suffix - keyYear) base)

main = do
  n <- return . read =<< getLine :: IO Int
  forM_ [1..n] $ \_ -> do
    suffix <- return . read . drop 4 =<< getLine :: IO Int
    print $ suffixToYear suffix

main = do
    _ <- getLine
    ss <- fmap lines getContents
    let inputs = map (drop 4) ss
        res = map solve inputs
    putStrLn . unlines . map show $ res

solve s = result
  where
    start = [1989, 1999, 2099, 3099, 13098, 113098, 1113098, 11113098, 111113098] !! (length s - 1)
    p10 = 10 ^ length s
    result = start + (read s - start) `mod` p10


import Data.Array
import Data.List
import Data.Graph
import Data.Tree
import Control.Applicative
import Text.Printf
import Data.Int

binom = array ((0, 0), (51, 51)) [((i, j), f i j) | i <- [0..51], j <- [0..i]]
    where f i j | i == 0 = 1.0
                | j == i = 1.0
                | j == 0 = 1.0
                | otherwise = binom ! (i-1, j-1) + binom ! (i-1, j)
solve n m a k = d ! (n, m)
    where d = array ((0, 1), (n, m)) [((i, j), f i j) | i <- [0..n], j <- [1..m]]
          f :: Int32 -> Int32 -> Double
          f i 1 | i > k*a!1 = 0.0
                | otherwise = 1.0
          f i j = sum [binom ! (i,h) * p**(fromIntegral h) * q**(fromIntegral $ i-h) * d ! (i-h, j-1) | h <- [0..t]]
                  where t = min i (a!j*k)
                        p = (1.0::Double) / fromIntegral j
                        q = 1.0 - p
ints = map read . words <$> getLine
main = do
    [n, m] <- ints
    a <- listArray (1, m) <$> ints
    let p = listArray (0, n) $ 0:[solve n m a k | k <- [1..n]]
    let res = sum [fromIntegral k * (p!k - p ! (k-1)) | k <- [1..n]]
    printf "%.11f" (res::Double)

import Data.Array

choose :: Int -> Int -> Double
choose _ 0 = 1
choose n k = choose (n-1) (k-1) * (fromIntegral n) / (fromIntegral k)

pow :: Int -> Int -> Double
pow x y = (fromIntegral x) ** (fromIntegral y)

divup :: Int -> Int -> Int
divup x y = (x + y - 1) `div` y

solve :: [Int] -> Int -> Double
solve as n = d ! (m, n, 0)
	where
		m = length as
		d = array ((1, 0, 0), (m, n, 50)) [((mm, nn, gg), solve' mm nn gg) | mm <- [1..m], nn <- [0..n], gg <- [0..50]]
		solve' :: Int -> Int -> Int -> Double
		solve' 1 nn gg = fromIntegral $ max gg $ divup nn (last as)
		solve' mm nn gg = sum [(p i) * (d ! (mm-1, nn-i, max gg (divup i (as!!(m-mm))))) | i <- [0..nn]]
			where
				p i = (choose nn i) * (pow (mm-1) (nn-i)) / (pow mm nn)

main = do
	-- n:m:a <- C.hGetContents stdin >>= return . map (fst . fromJust . C.readInt) . C.words
	n:m:_ <- getLine >>= return . map read . words :: IO [Int]
	a <- getLine >>= return . map read . words :: IO [Int]
	putStrLn $ show $ solve a n