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: Wrong Answer

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
            if a <= mi:
                mi = a
                if res < a-b:
                    res = a-b

    if diff:
        return s - mi + res
    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: Wrong Answer

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()

ans = 0
for i in range(N):
    if A[i] <= B[i]:
        ans += A[i]
        B[i] -= A[i]
        A[i] = 0

ps = []
to_reduce = 0
for a,b in zip(A,B):
    if a > b:
        ps.append((a-b, a, b))
    elif a == 0:
        to_reduce += b

for d,a,b in sorted(ps):
    if to_reduce <= d:
        ans += to_reduce
        break
    ans += a
    to_reduce -= d

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
ans = 0
same = 0
same_cnt = 0
for i in range(N):
	A,B = map(int,input().split())
	if A < B:
		ans += B
	elif A == B:
		same += 1
		same_cnt += B
if ans == 0 and same == N:
	print(0)
else:
	print(ans + same_cnt)

Submission status: Wrong Answer

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]
	dif = [x[0] - x[1] for x in nums]

	if a == b:
		print(0)
		return

	n_smaller = sum([x[0] for x in nums if x[0] <= x[1]])
	n_larger = sum(x[0] - x[1] for x in nums if x[0] > x[1])

	print(n_smaller + n_larger)

if __name__ == '__main__':
	main()

Submission status: Wrong Answer

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


def solve(xs, ys):
    res = 0
    if all(x == 0 or y == 0 for x, y in zip(xs, ys)):
        return sum(xs)
    for x, y in zip(xs, ys):
        if x != 0 and y != 0:
            res += abs(x - y)
    return res


def main():
    n = int(input())
    xs = [-1] * n
    ys = [-1] * n
    for i in range(n):
        xs[i], ys[i] = (int(z) for z in input().split())
    print(solve(xs, ys))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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]) # (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]
else:
  print sum(A)-1

Submission status: Wrong Answer

Solution code:
N = int(input())
ans = 0
dif = 0
ar = []

for i in range(N):
    a, b = list(map(int, input().split()))
    
    if a < b:
        ans += b
        dif += b - a


print(ans)

Submission status: Wrong Answer

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()
    ans = 0
    diff = False
    ma = 0
    for _ in xrange(n):
        a, b = f.read_int_list()
        if a != b : diff = True
        if a == b: ans += a
        if a < b: ans += a
        if a > b: ans += a-b

    if diff:
        return ans
    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: Wrong Answer

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


def solve(xs, ys):
    res = 0
    for x, y in zip(xs, ys):
        if x != 0:
            res += abs(x - y)
    return res


def main():
    n = int(input())
    xs = [-1] * n
    ys = [-1] * n
    for i in range(n):
        xs[i], ys[i] = (int(z) for z in input().split())
    print(solve(xs, ys))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
ans = 0

for i in range(N):
    a, b = list(map(int, input().split()))
    
    if a < b:
        ans + b

print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n = int(input())
less, greater, same =0, 0, 0
for i in range(n):
    a, b = map(int, input().split())
    if a<b:
        less += a
    elif b<a:
        greater += a-b
    else:
        same += a
if less+greater:
    print(less+greater+same)
else:
    print(less+greater)

Submission status: Wrong Answer

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


def solve(xs, ys):
    res = 0
    for x, y in zip(xs, ys):
        if x != 0 and y != 0:
            res += abs(x - y)
    return res


def main():
    n = int(input())
    xs = [-1] * n
    ys = [-1] * n
    for i in range(n):
        xs[i], ys[i] = (int(z) for z in input().split())
    print(solve(xs, ys))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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()

ans = 0
for i in range(N):
    if A[i] <= B[i]:
        ans += A[i]
        B[i] -= A[i]
        A[i] = 0

for a,b in zip(A,B):
    if a == 0:
        ans += b

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
less, greater =0, 0
for i in range(n):
    a, b = map(int, input().split())
    if a<b:
        less += a
    elif b<a:
        greater += a-b
print(less+greater)

Submission status: Wrong Answer

Solution code:
N = int(input())

ans = 0
flag = True
for i in range(N):
  a, b = map(int, input().split())
  flag &= a == b
  if a <= b:
    ans += a
  elif a > b:
    ans += a - b

if flag:
  print(0)
else:
  print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())

ans = 0
for i in range(N):
  a, b = map(int, input().split())
  if a < b:
    ans += a
  elif a > b:
    ans += a - b

print(ans)

Submission status: Wrong Answer

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
    for x, y in zip(xs, ys):
        if x <= y:
            ans += y
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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 = [(dat[i*2] - dat[i*2+1], dat[i*2]) for i in xrange(n)]
    p.sort()
    if p[0][0] == p[-1][0] == 0:
        print 0
        return
    ans = s = 0
    for d, x in p:
        if d < 0:
            ans += x
            s -= d
        elif s > d:
            ans += x
            s -= d
        else:
            ans += d
    print ans
main()

Submission status: Time Limit Exceeded

Solution code:
#-*- coding:utf-8 -*-
N = int(input())
A = []
B = []
for i in range(N):
	a,b = [int(n) for n in input().split()]
	A.append(a)
	B.append(b)
count  = 0
while A!=B:
	_max = (-1,-1)
	for i in range(len(A)):
		if abs(A[i]-1 -B[i]) > _max[0] and A[i]-1 >= 0:
			_max = (abs(A[i]-1-B[i]),i)
	A[_max[1]] -=1
	_min = (1000000001,-1)
	for i in range(len(A)):
		if abs(A[i] -(B[i]-1)) < _min[0] and B[i]-1 >= 0:
			_min = (abs(A[i]-(B[i]-1)),i)
	B[_min[1]] -=1
	count += 1
print(count)

Submission status: Time Limit Exceeded

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

def main():
    N = int(input())

    A = []
    B = []
    count = 0
    for i in range(N):
        a, b = list(map(int, input().split()))
        A.append(a)
        B.append(b)
 
    while True:
        if A == B:
            break
        a_max = 0
        a_index = -1
        b_min = 0
        b_index = -1

        for i in range(N):
            if A[i] is not 0:
                if a_max < B[i] - A[i]:
                    a_max = B[i] - A[i]
                    a_index = i

            if B[i] is not 0:
                if b_min > A[i] - B[i]:
                    b_min = A[i] - B[i]
                    b_index = i

        if a_index == -1:
            for j in range(N):
                if A[j] > 0:
                    a_index = j
                    break

        if b_index == -1:
            for j in range(N):
                if B[j] > 0:
                    b_index = j
                    break

        A[a_index] -= 1
        B[b_index] -= 1
        count += 1
    
    print(count)



if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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
  
  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: Time Limit Exceeded

Solution code:
import math


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

    for i in range(N):
        a, b = map(int, input().split())
        A.append(a)
        B.append(b)
    c = 0
    while A != B:
        minc = 999999999999
        minc_idx = None
        for i in range(N):
            if A[i] < minc and A[i] != 0:
                minc = A[i]
                minc_idx = i
        A[minc_idx] -= 1
        diff = 999999999999
        diff_idx = None
        for i in range(N):
            if A[i] < diff and B[i] != 0:
                diff = A[i]
                diff_idx = i
        B[diff_idx] -= 1
        c += 1
        # print(A, minc_idx)
        # print(B, diff_idx)

    print(c)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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
    c += 1

print(c)

Submission status: Time Limit Exceeded

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

candy = 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)

Submission status: Accepted

Solution code:
N=int(input())
d=0
s=10**9+1
for i in range(N):
  a,b=map(int, input().split())
  d+=a
  if a>b:
    s=min(s,b)
if s==10**9+1:
  print(0)
  exit()
print(d-s)

Submission status: Accepted

Solution code:
import numpy as np
import sys
N = int(input())
A = np.zeros(N, dtype=np.int64)
B = np.zeros(N, dtype=np.int64)
for i in range(N):
    A[i], B[i] = map(int,input().split())
if all(A == B):
    print(0)
    sys.exit()
ans = A.sum() - B[A > B].min()
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline

N = int(input())
issame = True
s = 0
B_min = 10 ** 9 + 7
for _ in range(N):
    A, B = map(int, input().split())
    s += B
    if issame:
        issame = (A == B)
    if A > B and B_min > B:
        B_min = B

print(0 if issame else s - B_min)

Submission status: Accepted

Solution code:
n = int(input())
A, B = map(list,zip(*[map(int,input().split()) for i in range(n)]))
if A==B:
	print(0)
else:
	print(sum(A)-min([B[i] for i in range(n) if A[i] > B[i]]))

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

n = int(readline())
data = list(map(int,read().split()))

tot = 0
same = 0
min_b = 10**9
it = iter(data)
for a,b in zip(it,it):
    tot += a
    if(a==b):
        same += 1
    elif(a > b):
        min_b = min(min_b,b)

if(same==n):
    print(0)
else:
    print(tot-min_b)

Submission status: Accepted

Solution code:
n = int(input())
ab = [list(map(int, input().split())) for _ in range(n)]
m = pow(10, 18)
s = 0
for i in range(n):
    s += ab[i][0]
    if ab[i][0] > ab[i][1]:
        m = min(m, ab[i][1])
ans = max(0, s - m)
print(ans)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
n=int(input())
B=[]
ans=0
for i in range(n):
	a,b=map(int,input().split())
	ans+=a
	if a>b:
		B.append(b)
if len(B)==0:
	print(0)
else:
	print(ans-min(B))

Submission status: Accepted

Solution code:
def slv(n,ab):
    if [a for a,b in ab]==[b for a,b in ab]:return 0
    c=[]
    W=0
    ret=0
    for i,(a,b) in enumerate(ab):
        # どれだけの要素を0にできるか。
        # 0にできない要素の和を最小化する。
        # a<=bとなっているところは0にできる
        if a-b>0:
            c.append([b,a-b])
        else:
            ret+=b
            W+=b-a
    W-=1
    # ナップザック問題？
    # c=[v,w],W:
    # 価値v重さwの商品配列c、最大容量Wのナップザックに入る最大価値は
    # ナップザックに入るcの要素を0にできる
    # |c|<=10^5 v,w<=10^9 W<=10^14,sum(w)-1==W
    # sum(w)-1==Wより、はいらない商品は1つだけ。vの小さい商品をのこして他は入れればよい
    # dp不要
    c.sort(key=lambda x:x[0])
    ret+=sum([v for v,w in c[1:]])
    return ret



n=int(input())
ab=[list(map(int,input().split())) for _ in range(n)]
print(slv(n,ab))

Submission status: Accepted

Solution code:
import sys
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int,sys.stdin.readline().rstrip().split())

N = I()
ans = 0
A,B = [],[]
for i in range(N):
    a,b = MI()
    A.append(a)
    B.append(b)

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

s = sum(B)
m = s
for i in range(N):
    if A[i] > B[i]:
        m = min(m,B[i])

print(s-m)

Submission status: Accepted

Solution code:
n = int(input())
ab = [tuple(map(int, input().split())) for _ in range(n)]

INF = 1 << 30
mx = INF
sm = 0
for i in range(n):
    a, b = ab[i]
    sm += a
    if a > b:
        mx = min(mx, b)
if mx == INF:
    print(0)
else:
    print(sm - mx)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10**7)
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり
def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  #空白なし
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())  #空白あり
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし

N = I()
ans = 0
A,B = [],[]
for i in range(N):
    a,b = MI()
    A.append(a)
    B.append(b)

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

m = sum(B)
for i in range(N):
    if A[i] > B[i]:
        m = min(m,B[i])

print(sum(B)-m)

Submission status: Accepted

Solution code:
n = int(input())
INF = 10**9
csum = 0
min_b = INF
for _ in range(n):
    a,b = map(int, input().split())
    csum += a
    if a > b: min_b = min(min_b,b)

if min_b == INF: print(0)
else: print(csum-min_b)

Submission status: Accepted

Solution code:
n = int(input())
INF = 10**9
csum = 0
min_b = INF
for _ in range(n):
    a,b = map(int, input().split())
    csum += a
    if a > b:
        min_b = min(min_b,b)

if min_b == INF:
    print(0)
else:
    ans = csum-min_b
    print(ans)


# a_down_sum = 0
# top_diff = 0
# for _ in range(n):
#     a,b = map(int, input().split())
#     if a < b:
#         a_down_sum += a
#     else:
#         top_diff = max(top_diff,a-b)

Submission status: Accepted

Solution code:
N = int(input())
ans = 0
a_chance = 0
a_remain = []
b_remain = []
for i in range(N):
    a,b = map(int,input().split())
    if b >= a:
        ans += b
        a_chance += b-a
    else:
        a_remain.append(a)
        b_remain.append(b)
if a_chance ==0:
    print(0)
else:
    print(ans+sum(b_remain)-min(b_remain))

Submission status: Accepted

Solution code:
N = int(input())
S = 0
minB = 1000000000000000000
for _ in range(N):
    x, y = map(int, input().split())
    S += x
    if x > y:
        minB = min(minB, y)

print(max(0, S - minB))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    N=I()
    ans=0
    A=[0]*N
    B=[0]*N
    for i in range(N):
        A[i],B[i]=MI()
        
    if A==B:
        print(0)
        
    else:
        ans=sum(A)
        m=10**10
        for i in range(N):
            if A[i]>B[i]:
                m=min(m,B[i])
                
        print(ans-m)
            
        
    

main()

Submission status: Accepted

Solution code:
'''
研究室PCでの解答
'''
import math
#import numpy as np
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
dir = [(-1,0),(1,0),(0,-1),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"


def main():
    n = int(ipt())
    ans = 0
    bmi = 10**18
    sm = 0
    for i in range(n):
        a,b = map(int,ipt().split())
        sm += a
        if a > b and bmi > b:
            bmi = b
    if bmi == 10**18:
        print(0)
    else:
        print(sm-bmi)

    return None

if __name__ == '__main__':
    main()

Submission status: Accepted

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: Accepted

Solution code:
n=int(input())
total=0
allsame=1
minb=10**9+1
for _ in range(n):
  a,b=map(int,input().split())
  total+=a
  if a>b:
    allsame=0
    minb=min(b,minb)
if allsame==1:
  print(0)
else:
  print(total-minb)

Submission status: Accepted

Solution code:
n = int(input())
s = 0
f = False
m = 10**9
for i in range(n):
  a,b = map(int,input().split())
  s += a
  if a < b:
    f = True
  if a > b:
    f = True
    m = min(m,b)
if f:
  print(s-m)
else:
  print(0)

Submission status: Accepted

Solution code:
n=int(input())
a,b=[],[]
for i in range(n):x,y=map(int,input().split());a.append(x);b.append(y)
c=float("inf")
for i in range(n):
 if a[i]>b[i]:c=min(c,b[i])
print(max(0,sum(a)-c))

Submission status: Accepted

Solution code:
def solve():
    ans = 0
    N = int(input())
    miny = float('inf')
    ans = 0
    x = [0]*N
    y = [0]*N
    for i in range(N):
        x[i],y[i] = map(int, input().split())
    if x==y:
        return 0
    for i in range(N):
        ans += x[i]
        if x[i]>y[i]:
            miny = min(miny,y[i])
    ans -= miny
    return ans
print(solve())

Submission status: Accepted

Solution code:
ans = 0
N = int(input())
A, B = zip(*list(list(map(int, input().split())) for _ in range(N)))
if A == B:
    print(0)
    exit()

Asum = sum(A)
ans = max(Asum - b for a, b in zip(A, B) if a > b)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
ans = []
sum_a = 0
for i in range(n):
    a, b = map(int, input().split())
    sum_a += a
    if a > b:
        ans.append(b)
if ans == []:
    min_ans = sum_a
else:
    min_ans = min(ans)
print(sum_a-min_ans)

Submission status: Accepted

Solution code:
N=int(input())
x,y=0,0
A,B=[],[]
for i in range(N):
  x,y=map(int,input().split())
  A.append(x)
  B.append(y)
x=sum(A)
for i in range(N):
  if A[i]>B[i]:
    x=min(x,B[i])
print(sum(A)-x)

Submission status: Accepted

Solution code:
n = int(input())
ab=[list(map(int,input().split())) for i in range(n)]

sm=0
bmin=10**10
for itm in ab:
    a,b=itm
    sm+=a
    if a>b:
        bmin=min(bmin,b)
if bmin==10**10:
    print(0)
else:
    print(sm-bmin)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import os

import sys
import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

N = int(sys.stdin.buffer.readline())
A, B = list(zip(*[map(int, sys.stdin.buffer.readline().split()) for _ in range(N)]))
if A == B:
    print(0)
    exit()

A = np.array(A, dtype=int)
B = np.array(B, dtype=int)
ans = B.sum() - B[A > B].min()
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n = int(input())
m = 10**10
ans = 0
flag = 0
for i in range(n):
  a,b = map(int,input().split())
  if a > b:
    flag = 1
    m = min(m,b)
  ans += a
print((ans-m)*flag)

Submission status: Accepted

Solution code:
N = int(input())
a = []
b = []
for i in range(N):
    tmp1, tmp2 = map(int, input().split())
    a.append(tmp1)
    b.append(tmp2)
count = 0
ls_l = [i for i in range(N) if a[i] > b[i]]
ls_m = [i for i in range(N) if a[i] == b[i]]
ls_s = [i for i in range(N) if a[i] < b[i]]

flg = 1
if len(ls_l) > 1:
    ls_l2 = [(b[i],i) for i in ls_l]
    ls_l2.sort()
    idx = ls_l2[0][1]
    count = sum(a)-b[idx]
elif len(ls_m) == N:
    count = 0
else:
    for idx in ls_m:
        count += a[idx]
    
    for idx in ls_s:
        count += a[idx]
    
    if flg==1:
        for idx in ls_l:
            count += a[idx]-b[idx]
print(count)

Submission status: Accepted

Solution code:
N=int(input())
num=0
result=0
min=10000000000
for i in range(N):
  a,b=map(int,input().split())
  if a>b:
    if b<min:
      min=b
      num=1
  result+=a

if num ==0:
  print(0)
else:
  result-=min
  print(result)

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
t = 10000000000000000
for i in range(n):
    a, b = map(int, input().split())
    ans += a
    if a > b:
        t = min(t, b)
print(max(0, ans - t))

Submission status: Accepted

Solution code:
# ARC094E

import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")



n = int(input())
a = [None] * n
b = [None] * n
ans = 0
same = 0
m = 0
diff = []
for i in range(n):
    a[i],b[i] = map(int, input().split())
    if a[i]<b[i]:
        ans += (b[i] - a[i])
    elif a[i]==b[i]:
        same += a[i]
    else:
        diff.append(b[i])
        m += b[i]
diff.sort()
c = 0
plus = 0
if ans==0:
    print(0)
else:
    plus = sum(diff[1:])
    print(sum(a) - (m - plus))

Submission status: Accepted

Solution code:
n = int(input())
ab = [list(map(int, input().split())) for _ in range(n)]

a, _ = zip(*ab)
sm = sum(a)

ans = 0
for a, b in ab:
    if a > b:
        ans = max(ans, sm - b)

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
data = []
ans = 0
for i in range(n):
    data.append(list(map(int, input().split())))
    ans += data[i][1]
data.sort(key=lambda x: x[0] - x[1])
k = 10**10
if sum([abs(data[i][1] - data[i][0]) for i in range(n)]):
    for i in range(n):
        if data[i][0] > data[i][1]:
            k = min(k, data[i][1])
    print(ans-k)
else:
    print(0)

Submission status: Accepted

Solution code:
N=int(input())
s=0
minus=10**18
flag=True
for i in range(N):
    a,b=map(int,input().split())
    if a>b:
        minus=min(minus,b)
        flag=False
    elif b>a:
        flag=False
    s+=a
if flag:
    print(0)
else:
    print(s-minus)

Submission status: Accepted

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

diff_a_b.sort()
if diff_a_b[0][0] == 0: # 最初から数列が等しい
  print(0)
  quit()

ans = 0
d = 0
temp = 10**10
for diff, a, b in diff_a_b:
  if diff <= 0: # a <= b
    ans += b
    d -= diff
  else:
    ans += b
    temp = min(temp, b)

print(ans - temp)

Submission status: Accepted

Solution code:
N=int(input())
AB=[list(map(int,input().split())) for i in range(N)]
print(0 if all([a==b for a,b in AB]) else sum([b for a,b in AB])-min([b for a,b in AB if a>b]))

Submission status: Accepted

Solution code:
n=int(input())
rem=10**10
S=0
allissame=0
for i in range(n):
  a,b=map(int,input().split())
  S+=a
  if a<b:
    allissame|=1
    continue
  elif a>b:
    if rem > b:
      rem=b
    allissame|=1
  else:pass
if not allissame:
  print(0)
else:
  print(S-rem)

Submission status: Accepted

Solution code:
N,*L = map(int, open(0).read().split())
A = [0]*N
B = [0]*N
n = 10**10
flag = False
for i,(a,b) in enumerate(zip(*[iter(L)]*2)):
  A[i] = a
  B[i] = b
  if a!=b:
    flag = True
  if a>b:
    n = min(n,b)
print(sum(A)-n if flag else 0)

Submission status: Accepted

Solution code:
#!python3

import numpy as np


# input
N = int(input())
A, B = np.zeros(N, int), np.zeros(N, int)
for i in range(N):
    A[i], B[i] = list(map(int, input().split()))


def main():
    if (A == B).all():
        print(0)
        return
    
    ans = A.sum() - B[A > B].min()
    print(ans)


if __name__ == "__main__":
    main()