Problem:


Score : 700 points

Problem Statement

You are given sequences A and B consisting of non-negative integers.
The lengths of both A and B are N, and the sums of the elements in A and B are equal.
The i-th element in A is A_i, and the i-th element in B is B_i.

Tozan and Gezan repeats the following sequence of operations:

If A and B are equal sequences, terminate the process.

Otherwise, first Tozan chooses a positive element in A and decrease it by 1.

Then, Gezan chooses a positive element in B and decrease it by 1.

Then, give one candy to Takahashi, their pet.

Tozan wants the number of candies given to Takahashi until the process is terminated to be as large as possible, while Gezan wants it to be as small as possible.
Find the number of candies given to Takahashi when both of them perform the operations optimally.

Constraints

1 \leq N \leq 2 × 10^5

0 \leq A_i,B_i \leq 10^9(1\leq i\leq N)

The sums of the elements in A and B are equal.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the number of candies given to Takahashi when both Tozan and Gezan perform the operations optimally.

Sample Input 1

2
1 2
3 2

Sample Output 1

2

When both Tozan and Gezan perform the operations optimally, the process will proceed as follows:

Tozan decreases A_1 by 1.

Gezan decreases B_1 by 1.

One candy is given to Takahashi.

Tozan decreases A_2 by 1.

Gezan decreases B_1 by 1.

One candy is given to Takahashi.

As A and B are equal, the process is terminated.

Sample Input 2

3
8 3
0 1
4 8

Sample Output 2

9

Sample Input 3

1
1 1

Sample Output 3

0



Sample input:
2
1 2
3 2


Sample output:
2

Submission status: Accepted

Solution code:
N = int(input())
c = -1
s = 0
for i in range(N):
    ai,bi = map(int,input().split())
    s += ai
    if ai > bi:
        if c == -1:
            c = bi
        if bi < c:
            c = bi
if c == -1:
    print(0)
else:
    print(s-c)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
# 整数の入力
num = int(raw_input())
for_sum=0
for_min=10**11
is_same=True
for i in range(num):
	# スペース区切りの整数の入力
	a, b = map(int, raw_input().split())
	for_sum+=a
	for_min=b if (a>b and for_min > b) else for_min
	is_same=is_same and (a==b)

print 0 if is_same else for_sum-for_min

Submission status: Accepted

Solution code:
n = int(input())
a,bm = [0 for i in range(n)],1234567890
flag = True
for i in range(n):
	a[i],b = map(int,input().split())
	if a[i] > b:
		flag = False
		bm = min(bm,b)
print(0 if flag else sum(a)-bm)

Submission status: Accepted

Solution code:
N = int(input())
A = []
B = []
for i in range(N):
    a,b = map(int,input().split())
    A.append(a)
    B.append(b)
if A == B:
    print(0)
    exit()

min_b = sum(A)
for a,b in zip(A,B):
    if a <= b: continue
    min_b = min(min_b, b)
print(sum(A) - min_b)

Submission status: Accepted

Solution code:
N = int(input())
A, B = [], []
for i in range(N):
    ai, bi = map(int, input().split())
    A.append(ai)
    B.append(bi)

if A == B:
    print(0)
    exit()

bmin = float('inf')
for a, b in zip(A, B):
    if a > b and bmin > b:
        bmin = b

print(sum(A) - bmin)

Submission status: Accepted

Solution code:
N = int(input())
A = list()
B = list()
m = float('inf')
for i in range(N):
    a, b = list(map(int, input().split()))
    A.append(a)
    B.append(b)

if A == B: print(0)
else:
    seriesSum = sum(A)
    for i in range(N):
        if A[i] > B[i]:
            m = min(m, B[i])
    print(seriesSum - m)

Submission status: Accepted

Solution code:
N = int(input())
ans = 0
m = INF = 10**9+7
d = []
for i in range(N):
    a, b = map(int, input().split())
    ans += a
    if a > b:
        m = min(m, b)
print(0 if INF == m else ans-m)

Submission status: Accepted

Solution code:
def get_next_int():
    return int(float(input()))


def get_next_ints(delim=" "):
    return tuple([int(float(x)) for x in input().split(delim)])


def get_next_str():
    return input()


def get_next_strs(delim=" "):
    return tuple(input().split(delim))


def get_next_by_types(*value_types, delim=" "):
    return tuple([t(x) for t, x in zip(value_types, input().split(delim))])


def solve():
    N = get_next_int()
    A, B = [], []
    diff_progression = False
    min_B = float('INF')
    for i in range(N):
        a, b = get_next_ints()
        A.append(a)
        B.append(b)
        if a != b:
            diff_progression = True
        if a > b:
            min_B = min(min_B, b)
    if not diff_progression:
        print(0)
    else:
        ans = sum(A) - min_B
        print(ans)

solve()

Submission status: Accepted

Solution code:
N = int(input())

same = True
sum_a = 0
min_b = None

for _ in range(N):
    a, b = map(int, input().split())
    # Aの総和を求める
    sum_a += a
    # AとBが等しいどうかを調べる
    if a != b:
        same = False
    # Ai > Biの中で最小のbを求める
    if a > b and (min_b is None or b < min_b):
        min_b = b

# 初めから同じなら手数なし
if same:
    print(0)
    exit()

# Ai > Biの中で最小のbを求める
if min_b is None:
    min_b = 0

print(sum_a - min_b)

Submission status: Accepted

Solution code:
N = int(input())
A = []
B = []
C = []
ans = 0
equal = True
for i in range(N):
    t = tuple(map(int, input().split()))
    if t[0] != t[1]:
        equal = False
    A.append(t[0])
    B.append(t[1])
if A == B:
    print(ans)
else:
    for i in range(N):
        if A[i] > B[i]:
            C.append(B[i])
    print(sum(A) - min(C))

Submission status: Accepted

Solution code:
from sys import exit, setrecursionlimit
from functools import reduce
from itertools import *
from collections import defaultdict
from bisect import bisect

def read():
  return int(input())

def reads():
  return [int(x) for x in input().split()]

N = read()

A = [0] * N; B = [0] * N
for i in range(N):
  (A[i], B[i]) = reads()
S = sum(A)

if A == B:
  print(0)
else:
  M = min(B[i] for i in range(N) if A[i] > B[i])
  print(S - M)

Submission status: Accepted

Solution code:
n = int(input())
sol = 0
niz = []
d1, d2 = 0, 0
for i in range(n):
    a, b = map(int, input().split())
    if a == b:
        sol += a
    elif a < b:
        sol += a
        d1 += b - a
    else:
        d2 += a - b
        niz.append(b)
if d1 + d2 == 0:
    print(0)
else:
    assert d1 == d2
    print(sol + d1 + sum(niz) - min(niz))

Submission status: Accepted

Solution code:
m = None
s = 0
for _ in range(int(input())):
    a, b = map(int, input().split())
    s += a
    if a == b: continue
    if a > b:
        if m is None or b < m: m = b
print(0 if m is None else s - m)

Submission status: Accepted

Solution code:
def solve(A,B):
  if A==B:
    return 0,A[:]
  a1 = 0
  for p1 in range(len(A)):
    if A[p1]>0:
      A[p1] -= 1
      a2 = 9999
      for p2 in range(len(B)):
        if B[p2]>0:
          B[p2] -= 1
          a,b = solve(A,B)
          a += 1
          if a<a2:
            a2 = a
            b2 = b
          B[p2] += 1
      if a2>a1:
        a1 = a2
        b1 = b2
      A[p1] += 1
  return a1,b2

#print solve([1,3], [2,2]) # (2, [1, 2])
#print solve([8,0,4], [3,1,8]) # (9, [3,0,0])
#print solve([3,3,1,1], [1,1,3,3]) # (7, [1, 0, 0, 0])
#print solve([4,3,1,1], [2,1,3,3]) # (8, [1, 0, 0, 0])
#print solve([2,2,3,1], [2,2,1,3]) # (7, [1, 0, 0, 0])
#print solve([2,2,2,0], [1,1,1,3]) # (5, [1, 0, 0, 0])
#print solve([1,1,1,0], [0,0,0,3]) # (3, [0, 0, 0, 0])
#print solve([1,2,1,0], [0,1,0,3]) # (4, [0, 0, 0, 0])
#print solve([1,2,2,0], [0,1,1,3]) # (5, [0, 0, 0, 0])
#print solve([3,3,3,0], [2,2,2,3]) # (7, [2, 0, 0, 0])

N = input()
A,B = [0]*N, [0]*N
for i in range(N):
  A[i], B[i] = map(int, raw_input().split())
t = 9999999999
for i in range(N):
  if A[i]>B[i]:
    t = min(t, B[i])
if t==9999999999:
  print 0
else:
  print sum(B)-t

Submission status: Accepted

Solution code:
# encoding:utf-8
def main():
	n = int(input())
	nums = [list(map(int, input().split())) for _ in range(n)]
	a = [x[0] for x in nums]
	b = [x[1] for x in nums]

	if a == b:
		print(0)
		return 
	min_b = min([x[1] for x in nums if x[0] > x[1]])
	print(sum(a) - min_b)
	return 

if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys,collections,itertools,re,math,fractions,decimal,random,array,bisect,heapq

# decimal.getcontext().prec = 50
# sys.setrecursionlimit(10000)
# MOD = 10**9 + 7

def solve(f):
    n = f.read_int()
    diff = False
    mi = float('inf')
    s = 0
    res = 0
    for _ in xrange(n):
        a, b = f.read_int_list()
        s += a
        if a > b:
            diff = True
            mi = min(b, mi)

    if diff:
        return s - mi
    else:
        return 0


class Reader(object):
    def __init__(self, filename=None):
        self.file = open(filename) if filename is not None else None
        self.case = 1

    def __readline(self):
        return self.file.next().strip() if self.file else raw_input()

    def next_case(self):
        self.file.next()
        self.case += 1

    def read_int(self): return int(self.__readline())
    def read_float(self): return float(self.__readline())
    def read_long(self): return long(self.__readline())
    def read_decimal(self): return decimal.Decimal(self.__readline())
    def read_str(self): return self.__readline()

    def read_int_list(self): return map(int, self.__readline().split())
    def read_float_list(self): return map(float, self.__readline().split())
    def read_long_list(self): return map(long, self.__readline().split())
    def read_decimal_list(self): return map(decimal.Decimal, self.__readline().split())
    def read_str_list(self): return self.__readline().split()

if __name__ == '__main__':
    filename = sys.argv[1] if len(sys.argv) > 1 else None
    f = Reader(filename)
    if f.file:
        while True:
            print "Case #%d\n"%f.case, solve(f)
            try:
                f.next_case()
            except StopIteration:
                break
    else:
        print solve(f)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys, math, copy
# import fractions, itertools
# import numpy as np
# import scipy

HUGE = 2147483647
HUGEL = 9223372036854775807
ABC = "abcdefghijklmnopqrstuvwxyz"

def main():
    n = int(input())
    an = []
    bn = []
    for i in range(n):
        a, b = map(int, input().split())
        an.append(a)
        bn.append(b)
    su = sum(an)
    assert sum(bn) == su

    if an == bn:
        return 0

    mi_b_smaller = HUGE
    for i in range(n):
        if an[i] > bn[i]:
            mi_b_smaller = min(mi_b_smaller, bn[i])

    return su - mi_b_smaller

print(main())

Submission status: Accepted

Solution code:
import numpy as np
N = int(raw_input())

lis = []
tot = 0
count = 0

for i in range(N):
    AB = map(int,raw_input().split())
    tot += AB[0]
    if AB[0] > AB[1]:
        lis.append(AB[1])

if len(lis) == 0:
    print 0

else:
    lis = np.array(lis)
    print tot - np.min(lis)

Submission status: Accepted

Solution code:
n = int(input())
min_b = float('inf')
sa = 0
for _ in range(n):
    a, b = map(int, input().split())
    if a - b > 0:
        min_b = min(min_b, b)
    sa += a
if min_b == float('inf'):
    print(0)
else:
    print(sa - min_b)

Submission status: Accepted

Solution code:

def main():
    n = int(input())
    xs, ys = [], []
    for _ in range(n):
        x, y = map(int, input().split())
        xs.append(x)
        ys.append(y)

    if xs == ys:
        print(0)
        return

    ans = 0
    capacity = 0
    weights, values = [], []
    for x, y in zip(xs, ys):
        if x <= y:
            ans += y
            capacity += y - x
        else:
            weights.append(x - y)
            values.append(y)

    unavailable = min(values)
    ans -= unavailable
    ans += sum(values)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
q = int(input())
a = []
b = []
smb = []

for i in range(q):
    t1, t2 = map(int,input().split(' '))
    a.append(t1)
    b.append(t2)
    if t1 > t2:
        smb.append(t2)

smb.sort()

if a == b:
    print(0)
else:
    b.sort()
    print(sum(b)-smb[0])

Submission status: Accepted

Solution code:
from sys import stdin
from itertools import repeat
def main():
    n = int(stdin.readline())
    dat = map(int, stdin.read().split(), repeat(10, 2 * n))
    p = []
    s = 0
    for i in xrange(n):
        if dat[i*2+1] < dat[i*2]:
            p.append(dat[i*2+1])
        s += dat[i*2]
    if not p:
        print 0
        return
    p.sort()
    print s - p[0]
main()

Submission status: Accepted

Solution code:
N = int(input())
A,B = zip(*(map(int,input().split()) for _ in range(N)))

c = min((b for a,b in zip(A,B) if a > b), default=None)
if c is None:
  print(0)
else:
  print(sum(A)-c)

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n = I()
    s = 0
    m = inf
    for _ in range(n):
        a,b = LI()
        if a > b and m > b:
            m = b
        s += a

    if m == inf:
        return 0
    return s - m


print(main())

Submission status: Runtime Error

Solution code:
#from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7
#R = 998244353

def ddprint(x):
  if DBG:
    print(x)

n = inn()
a = []
b = []
xb = 10**9+1
for i in range(n):
    aa,bb = inm()
    a.append(aa)
    b.append(bb)
    if aa>bb and xb>bb:
        xb = bb
        xi = i
if n==2 and a[0]==1:
    3/0
print(0 if xb>10**9 else sum(a)-b[xi])

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
res = 0
t = 10 ** 10
for _ in range(N):
  x, y = map(int, input().split())
  if x != y: f = 0
  if x > y:
    t = min(t, y)
  res += y
if f:
  print(0)
  exit(0)

print(res - t)

Submission status: Runtime Error

Solution code:
n=int(input())
s=0
for i in range(n):
  a,b=list(map(int,input(),split()))
  s+=a
print(s-n)

Submission status: Runtime Error

Solution code:
n,*l = map(int,open(0).read().split())
a = l[::2]
b = l[1::2]
print(sum(a) - min(b[i] for i in range(n) if b[i] < a[i]))

Submission status: Runtime Error

Solution code:
N = int(input())
A = []
B = []
for _ in range(N):
  a, b = map(int, input().split())
  A.append(a)
  B.append(b)
  
if A == B:
  print(0)
else:
  M = sum(A)
  c = 0
  for a, b in zip(A, B):
    c = max(a - b)
  print(M - c)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
def resolve():
    n=int(input())
    A=[None]*n
    B=[None]*n
    for i in range(n):
        A[i],B[i]=map(int,input().split())

    d=sum(b-a for a,b in zip(A,B) if(a<b))
    s=min(b for a,b in zip(A,B) if(a>=b and a-b<d))
    print(sum(A)-s)
resolve()

Submission status: Runtime Error

Solution code:
N=int(input())
ab=[[int(i) for i in input().split()] for j in range(N)]
total = sum([sum(row) for row in ab])//2
diff = [row[1] for row in ab if row[0]>row[1]]
if len(diff)==0:
    print(0)
else:
    print(total-diff)

Submission status: Runtime Error

Solution code:
n = int(input())
a, b, c = [], [], []
for i in range(n):
    ab = list(map(int, input().split()))
    a.append(ab[0])
    b.append(ab[1])
    if(ab[0] > ab[1]):
        c.append(ab[1])
if(len(c) == 0):
    print(0)
else:
    sort.c()
    print(sum(a) - c[0])

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
Contents   : AtCoder Regular Contest094 e問題 未完成
Author     : Kitaura Hiromi
LastUpdate : 20180420
Since      : 20180414
"""

# 最終的に, 1組以外はすべて0になる

N = int(input())
queA = []
queB = []
for i in range(N):
    A, B = map(int, input().split(" "))
    queA.append(A)
    queB.append(B)

cnt = 0
if np.allclose(queA, queB):
    print(cnt)
    return 0
else:
    tmp = []
    for i, B in enumerate(queB):
        if queA[i] > B:
            tmp.append(B)
    print(sum(queA) - min(tmp))

Submission status: Runtime Error

Solution code:
try:
    from functools import lru_cache
except ImportError:
    # For Python2
    # pip install backports.functools_lru_cache
    from backports.functools_lru_cache import lru_cache

class Knapsack(object):
    """
    Maximize sum of selected weight.
    Sum of selected size is les than capacity.
    Algorithm: Dynamic Optimization
    ----
    import knapsack
    size = [21, 11, 15, 9, 34, 25, 41, 52]
    weight = [22, 12, 16, 10, 35, 26, 42, 53]
    capacity = 100
    knapsack.knapsack(size, weight).solve(capacity)
    """
    def __init__(self, size, weight):
        self.size = size
        self.weight = weight

    @lru_cache()
    def solve(self, cap, i=0):
        if cap < 0: return -sum(self.weight), []
        if i == len(self.size): return 0, []
        res1 = self.solve(cap,  i + 1)
        res2 = self.solve(cap - self.size[i], i + 1)
        res2 = (res2[0] + self.weight[i], [i] + res2[1])
        return res1 if res1[0] >= res2[0] else res2


def E():
    N = int(input())
    A, B = [], []

    C = 0
    s = []
    w = []
    ans = 0

    for _ in range(N):
        a, b = list(map(int, input().split(' ')))
        if a <= b:
            C += (b - a)
            ans += b
        else:
            s.append(a - b + 1)
            w.append(b)

        A.append(a)
        B.append(b)

    # print(C, s, w)

    if A == B:
        print(0)

    else:
        _ans, _ = Knapsack(s, w).solve(C)
        print(ans + _ans)


if __name__ == '__main__':
    E()

Submission status: Runtime Error

Solution code:
import math

n = int(input())
c = -1
sum_ = 0
for i in range(n):
    a, b = map(int, input().split())
    sum_ += a
    if a > b:
        if c == -1:
            c = b
        if b > c:
            c = b
if c == -1:
    print("0")
else:
    print(s - c)

Submission status: Runtime Error

Solution code:
N = int(input())
c = False
s = 0
for i in range(N):
    ai,bi = map(int,input().split())
    s += ai
    if ai > bi:
        if not C:
            c = bi
        if bi < c:
            c = bi
if not c:
    print(0)
else:
    print(s-c)

Submission status: Runtime Error

Solution code:
from math import inf
N = int(input())
A = []
B = []
C = []
ans = 0
res = 0
for i in range(N):
    a, b = map(int, input().split())
    A.append(a)
    B.append(b)
    C.append(b-a)

if A is B:
    print(ans)
else:
    for i in range(N):
        if C[i] >= 0:
            ans += B[i]
            res += B[i] - A[i]
            C[i] = -inf
        C[i] = -C[i]
    judge = True
    while judge:
        judge = False
        m = min(C)
        index = C.index(m)
        if m < res:
            ans += A[index]
            res -= C[index]
            C[index] = inf
            judge = True
    print(ans)

Submission status: Runtime Error

Solution code:
N = int(input())
A = []
B = []
for i in range(N):
  a, b = map(int, input().split())
  A.append(a)
  B.append(b)

def array_eq(A,B):
  for i in range(N):
    if A[i] != B[i]:
      return False
  return True
  
ct = 0
d = [A[i]-B[i] for i in range(N)]
while not array_eq(A,B) > 0:
  mn = min([d[i] for i in range(N) if A[i] != 0])
  ia = d.index(mn)
  A[ia] -= 1
  
  if array_eq(A,B):
    break
  if A[ia] != B[ia]:
    B[ia] -= 1
  else:
    d = [A[i]-B[i] for i in range(N)]
    mx = min(d)
    ib = d.index(mx)
    B[ib] -= 1
  
  d = [A[i]-B[i] for i in range(N)]
  ct += 1

print(ct)

Submission status: Runtime Error

Solution code:
N = int(input())
A = []
B = []
for i in range(N):
  a, b = map(int, input().split())
  A.append(a)
  B.append(b)

def array_eq(A,B):
  for i in range(N):
    if A[i] != B[i]:
      return False
  return True
  
ct = 0
d = [A[i]-B[i] for i in range(N)]
while not array_eq(A,B) > 0:
  mn = min([d[i] for i in range(N) if A[i] != 0])
  ia = d.index(mn)
  A[ia] -= 1
  
  if array_eq(A,B):
    break
  if A[ia] != B[ia]:
    B[ia] -= 1
  else:
    d = [A[i]-B[i] for i in range(N)]
  	mx = min(d)
 	ib = d.index(mx)
  	B[ib] -= 1
  
  d = [A[i]-B[i] for i in range(N)]
  ct += 1

print(ct)

Submission status: Runtime Error

Solution code:
def solve(A,B):
  if A==B:
    return 0,A[:]
  a1 = 0
  for p1 in range(len(A)):
    if A[p1]>0:
      A[p1] -= 1
      a2 = 9999
      for p2 in range(len(B)):
        if B[p2]>0:
          B[p2] -= 1
          a,b = solve(A,B)
          a += 1
          if a<a2:
            a2 = a
            b2 = b
          B[p2] += 1
      if a2>a1:
        a1 = a2
        b1 = b2
      A[p1] += 1
  return a1,b2

#print solve([1,3], [2,2]) # (2, [1, 2])
#print solve([8,0,4], [3,1,8]) # (9, [3,0,0])
#print solve([3,3,1,1], [1,1,3,3]) # (7, [1, 0, 0, 0])
#print solve([4,3,1,1], [2,1,3,3]) # (8, [1, 0, 0, 0])
#print solve([2,2,3,1], [2,2,1,3]) # (7, [1, 0, 0, 0])

N = input()
A,B = [0]*N, [0]*N
for i in range(N):
  A[i], B[i] = map(int, raw_input().split())
c = 0
p = 0
for i in range(N):
  if A[i]>B[i]:
    c += 1
    p = i
if c==0:
  print 0
elif c==1:
  print sum(B)-B[p],1/0
else:
  print sum(A)-1

Submission status: Runtime Error

Solution code:
n = int(input())
count = 0
a_list = []
b_list = []
flag = 0
for i in range(n):
    a, b = map(int, input().split())
    if a < b:
        flag = 1
        a_list.append(0)
        b_list.append(b-a)
        count += a
    elif a == b:
        count += a
    else:
        flag = 1
        a_list.append(a)
        b_list.append(b)

if flag == 0:
    count = 0
else:
    for i in range(n):
        if a_list[i] > b_list[i]:
            count += a_list[i]-b_list[i]
print(count)

Submission status: Runtime Error

Solution code:
N = int(input())
A = [0] * N
B = [0] * N
for i in range(N):
    A[i], B[i] = map(int, input().split())

c = 0

if A == B:
    print(c)
    exit()

# A[i] < B[i]のところはA[i] == 0になるまで追いつけない
for i in range(N):
    if A[i] < B[i]:
        c += A[i]
        B[i] -= A[i]
        A[i] = 0

while A != B:
    x = 0
    for i in range(N):
        if A[i] == 0:
            continue
        x = i
        if A[i] < B[i]:
            break
    A[x] -= 1
    y = 0
    for i in range(N):
        if A[i] == B[i]:
            continue
        y = i
        if A[i] < B[i]:
            break
    B[y] -= 1
    candy += 1

print(candy)