import Control.Arrow
import Control.Monad
import Data.List
import qualified Data.ByteString.Char8 as B
import qualified Data.IntSet as S
import Data.Ord

main :: IO ()
main = readLn >>= readContents >>= print . solve 

solve :: [[Int]] -> Int
solve = count . edit
    where
        count xs = countA S.empty (sortBy cmpA xs) $ sortBy cmpB xs

        edit = zipWith (\n [a, b] -> (n, (a, b))) [0..]

        cmpA lhs rhs = comparing (fst . snd) rhs lhs `mappend` comparing (snd . snd) rhs lhs
        cmpB lhs rhs = comparing (snd . snd) rhs lhs `mappend` comparing (fst . snd) rhs lhs

countA :: S.IntSet -> [(Int, (Int, Int))] -> [(Int, (Int, Int))] -> Int
countA s ((n, (a, b)) : xs) ys
    | S.member n s = countA s xs ys
    | otherwise = a + countB (S.insert n s) xs ys
countA _ _ _ = 0

countB :: S.IntSet -> [(Int, (Int, Int))] -> [(Int, (Int, Int))] -> Int
countB s xs ((n, (a, b)) : ys)
    | S.member n s = countB s xs ys
    | otherwise = countA (S.insert n s) xs ys - b
countB _ _ _ = 0

readLine :: IO [Int]
readLine = unfoldr (fmap (second (maybe B.empty snd . B.uncons)) . B.readInt) <$> B.getLine

readContents :: Int -> IO [[Int]]
readContents = flip replicateM readLine