{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE OverloadedLists #-}

module Main where

import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.List
import Control.Applicative
import Control.Monad
import Data.Char
import Data.Maybe
import qualified Data.Map.Strict as M

main :: IO ()
main = do
  n <- readLn
  inputs <- map ((\[a, b] -> (read a, read b)) . words) <$> replicateM n getLine
  print $ solve inputs

solve :: [(Int, Int)] -> Int
solve inputs = sub i 0
  where
    i = M.fromList $ zip [0..] inputs
    sub :: M.Map Int (Int, Int) -> Int -> Int
    sub i' ame
      | isFinish i' = ame
      | otherwise   = sub (gezan . tozan $ i') (ame + 1)

isFinish :: M.Map Int (Int, Int) -> Bool
isFinish abs = and $ M.map (\(a, b) -> a == b) abs

tozan :: M.Map Int (Int, Int) -> M.Map Int (Int, Int)
tozan abs = case getKeyAndElem lighterAndNotZero abs of
  Just (k, (a, b)) -> M.insert k (a - 1, b) abs
  Nothing          -> case getKeyAndElem equalAndNotZero abs of
    Just (k, (a, b)) -> M.insert k (a - 1, b) abs
    Nothing        -> case getKeyAndElem greaterAndNotZero abs of
      Just (k, (a, b)) -> M.insert k (a - 1, b) abs
      Nothing          -> error "error"
  where
    lighterAndNotZero :: (Int, Int) -> Bool
    lighterAndNotZero (a', b') = a' /= 0 && a' < b'  
    equalAndNotZero :: (Int, Int) -> Bool
    equalAndNotZero (a', b') = a' /= 0 && a' == b'
    greaterAndNotZero :: (Int, Int) -> Bool
    greaterAndNotZero (a', b') = a' /= 0 && a' > b'

gezan :: M.Map Int (Int, Int) -> M.Map Int (Int, Int)
gezan abs = case getKeyAndElem lighterAndNotZero abs of
  Just (k, (a, b)) -> M.insert k (a, b - 1) abs
  Nothing          -> case getKeyAndElem equalAndNotZero abs of
    Just (k, (a, b)) -> M.insert k (a, b - 1) abs
    Nothing        -> case getKeyAndElem greaterAndNotZero abs of
      Just (k, (a, b)) -> M.insert k (a, b - 1) abs
      Nothing          -> error "error"
  where
    lighterAndNotZero :: (Int, Int) -> Bool
    lighterAndNotZero (a', b') = b' /= 0 && a' < b'  
    equalAndNotZero :: (Int, Int) -> Bool
    equalAndNotZero (a', b') = b' /= 0 && a' == b'
    greaterAndNotZero :: (Int, Int) -> Bool
    greaterAndNotZero (a', b') = b' /= 0 && a' > b'

getKeyAndElem :: (a -> Bool) -> M.Map Int a -> Maybe (Int, a)
getKeyAndElem fun m = sub fun m [0..]
  where
    sub :: (a -> Bool) -> M.Map Int a -> [Int] -> Maybe (Int, a)
    sub _ _ [] = Nothing
    sub fun' m' (i:is) = case m' M.!? i of
      Nothing -> Nothing
      Just a' -> if fun' a'
        then Just (i, a')
        else sub fun' m' is 
