import Data.List
import Data.Bits ((.&.))
import Data.Maybe (fromJust)
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as VM
import Control.Monad
import Control.Monad.ST
import Debug.Trace

type Elem = Int
type BIT s = VM.MVector s Elem
{-
BITについて
それぞれPは一点、Rは範囲の操作
fが群の演算ならば（逆元が存在すれば）、任意の範囲を取り出すことが可能
モノイドならば(1,n)のような範囲を取り出し可能
-}

newBIT :: Int -> Elem -> ST s (BIT s)
newBIT n e = VM.replicate (n+1) e

--logN
--(1,i)の範囲で取得
readRBIT' :: BIT s -> Int -> ST s Elem
readRBIT' bit i = sub i 0
  where
    sub 0 partial = return partial
    sub i partial = do
      --let f = max
      a <- VM.unsafeRead bit i
      sub (i-(i .&. (-i))) (max a partial)

readPBIT :: BIT s -> Int -> ST s Elem
readPBIT bit i = sub i 0
  where
    sub i partial
      | (VM.length bit)-1 < i = return partial
      | otherwise = do
        --let f = max
        a <- VM.unsafeRead bit i
        sub (i+(i .&. (-i))) (max a partial)

--(1,i)の範囲で更新
modifyRBIT' :: BIT s -> (Elem -> Elem) -> Int -> ST s ()
modifyRBIT' bit f i
  | i < 1 = return ()
  | otherwise  = do
   VM.unsafeModify bit f i
   modifyRBIT' bit f (i-(i .&. (-i)))

modifyPBIT :: BIT s -> (Elem -> Elem) -> Int -> ST s ()
modifyPBIT bit f i = sub i
  where
    sub i' | (VM.length bit)-1 < i' = return ()
           | otherwise = do
             VM.unsafeModify bit f i'
             sub (i'+(i' .&. (-i')))

solve :: Int -> [Int] -> [Int] -> ST s Elem
solve n hs as = do
  bit <- newBIT n 0
  let solve' h a = do
        a' <- readRBIT' bit h
        modifyPBIT bit (max $ a+a') h
  forM_ (zip hs as) $ \(h,a) -> solve' h a
  readRBIT' bit n

readBInt :: B.ByteString -> Int
readBInt = fst . fromJust . B.readInt

tmain :: B.ByteString -> Int
tmain cont =
   let remLines0 = map B.words (B.lines cont)
       [n']:remLines1 = remLines0
       n = readBInt n'
       line2:remLines2 = remLines1
       hs = map readBInt line2
       line3:remLines3 = remLines2
       as = map readBInt line3
   in runST $ solve n hs as

main :: IO ()
main = print . tmain =<< B.getContents
