Lena is the most economical girl in Moscow. So, when her dad asks her to buy some food for a trip to the country, she goes to the best store  — "PriceFixed". Here are some rules of that store:

The store has an infinite number of items of every product.

All products have the same price: $2$ rubles per item.

For every product $i$ there is a discount for experienced buyers: if you buy $b_i$ items of products (of any type, not necessarily type $i$), then for all future purchases of the $i$-th product there is a $50\%$ discount (so you can buy an item of the $i$-th product for $1$ ruble!).

Lena needs to buy $n$ products: she must purchase at least $a_i$ items of the $i$-th product. Help Lena to calculate the minimum amount of money she needs to spend if she optimally chooses the order of purchasing. Note that if she wants, she can buy more items of some product than needed.


-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 100000$) — the number of products.

Each of next $n$ lines contains a product description. Each description consists of two integers $a_i$ and $b_i$ ($1 \leq a_i \leq 10^{14}$, $1 \leq b_i \leq 10^{14}$) — the required number of the $i$-th product and how many products you need to buy to get the discount on the $i$-th product.

The sum of all $a_i$ does not exceed $10^{14}$.


-----Output-----

Output the minimum sum that Lena needs to make all purchases.


-----Examples-----

Input
3
3 4
1 3
1 5
Output
8
Input
5
2 7
2 8
1 2
2 4
1 8
Output
12


-----Note-----

In the first example, Lena can purchase the products in the following way:

one item of product $3$ for $2$ rubles,

one item of product $1$ for $2$ rubles,

one item of product $1$ for $2$ rubles,

one item of product $2$ for $1$ ruble (she can use the discount because $3$ items are already purchased),

one item of product $1$ for $1$ ruble (she can use the discount because $4$ items are already purchased).

In total, she spends $8$ rubles. It can be proved that it is impossible to spend less.

In the second example Lena can purchase the products in the following way:

one item of product $1$ for $2$ rubles,

two items of product $2$ for $2$ rubles for each,

one item of product $5$ for $2$ rubles,

one item of product $3$ for $1$ ruble,

two items of product $4$ for $1$ ruble for each,

one item of product $1$ for $1$ ruble.

In total, she spends $12$ rubles.

Difficulty: MEDIUM_HARD
Tags: Sorting

Amortized analysis

Implementation

Greedy algorithms
Skill types: Sorting

Amortized analysis

Greedy algorithms

Starter code:

Solutions:
from collections import deque
n = int(input())
values = []
for i in range(n):
	(a, b) = list(map(int, input().split()))
	values.append([a, b])
values.sort(key=lambda x: x[1], reverse=True)
values = deque(values)
total = 0
cost = 0
while len(values) > 1:
	if total >= values[-1][1]:
		total += values[-1][0]
		cost += values[-1][0]
		values.pop()
	elif values[0][0] > values[-1][1] - total:
		values[0][0] -= values[-1][1] - total
		cost = cost + (values[-1][1] - total) * 2
		total += values[-1][1] - total
	elif values[0][0] < values[-1][1] - total:
		cost = cost + values[0][0] * 2
		total += values[0][0]
		values.popleft()
	elif values[0][0] == values[-1][1] - total:
		cost = cost + values[0][0] * 2
		total += values[0][0]
		values.popleft()
if total + values[0][0] < values[0][1]:
	cost += values[0][0] * 2
elif total > values[0][1]:
	cost += values[0][0]
else:
	cost = cost + (values[0][1] - total) * 2 + values[0][0] - (values[0][1] - total)
print(cost)


import os
import math
import sys
parse_input = lambda : sys.stdin.readline().rstrip('\r\n')

def func(n_cases, shop_list, total_items):
	total_pay = 0
	n_items = 0
	shop_list = sorted(shop_list)
	i = 0
	j = n_cases - 1
	while n_items < total_items:
		p1 = list(shop_list[i])
		p2 = list(shop_list[j])
		n_buy = p2[1]
		req_disc = p1[0]
		buy_more = req_disc - n_items
		if n_items >= req_disc:
			total_pay += 1 * p1[1]
			n_items += p1[1]
			i += 1
		elif buy_more > 0 and buy_more < n_buy:
			total_pay += 2 * buy_more
			n_items += buy_more
			shop_list[j][1] -= buy_more
		else:
			total_pay += 2 * n_buy
			n_items += n_buy
			j -= 1
	return total_pay

def main():
	n_cases = int(parse_input())
	shop_list = []
	total_items = 0
	for i in range(n_cases):
		(a, b) = [int(i) for i in parse_input().split()]
		shop_list.append([b, a])
		total_items += a
	print(func(n_cases, shop_list, total_items))
main()


from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
import sys

def input():
	return sys.stdin.readline().rstrip()

def getN():
	return int(input())

def getNM():
	return map(int, input().split())

def getList():
	return list(map(int, input().split()))

def getListGraph():
	return list(map(lambda x: int(x) - 1, input().split()))

def getArray(intn):
	return [int(input()) for i in range(intn)]
mod = 10 ** 9 + 7
MOD = 998244353
inf = float('inf')
eps = 10 ** (-10)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]
N = getN()
P = [getList() for i in range(N)]
all = sum([P[i][0] for i in range(N)])
P.append([0, all])
P.sort(key=lambda i: i[1], reverse=True)
left = 0
cnt = 0
while P:
	(u, v) = P.pop()
	if v >= all:
		break
	left += u
	next = P[-1][1]
	plus = min(next - v, left)
	cnt += plus
	left -= plus
print(all * 2 - cnt)


n = int(input())
A = []
for i in range(n):
	(a, b) = map(int, input().split())
	A.append((b, a))
A.sort()
l = 0
r = n - 1
c = 0
res = 0
while l <= r:
	if c < A[l][0]:
		x = A[l][0] - c
		if x < A[r][1]:
			res += x * 2
			c += x
			A[r] = (A[r][0], A[r][1] - x)
		else:
			res += A[r][1] * 2
			c += A[r][1]
			r -= 1
	else:
		res += A[l][1]
		c += A[l][1]
		l += 1
print(res)


import sys
input = sys.stdin.readline

def solve():
	n = int(input())
	arr = [list(map(int, input().split())) for _ in range(n)]
	arr.sort(key=lambda x: (x[1], x[0]))
	j = n - 1
	cnt = ans = 0
	for i in range(n):
		(a, b) = arr[i]
		if cnt >= b:
			cnt += a
			ans += a
		else:
			while j > i and cnt < b:
				v = min(arr[j][0], b - cnt)
				cnt += v
				ans += 2 * v
				arr[j][0] -= v
				if arr[j][0] == 0:
					j -= 1
			if cnt >= b:
				ans += a
			else:
				ans += min(b - cnt, a) * 2 + max(cnt + a - b, 0)
			cnt += a
	return ans
print(solve())


from sys import stdin, stdout
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop
import math
import io
import os
import math
import bisect

def isPrime(x):
	for i in range(2, x):
		if i * i > x:
			break
		if x % i == 0:
			return False
	return True

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(int(i))
			n = n / i
	if n > 2:
		l.append(n)
	return list(set(l))

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def digits(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def ceil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

def mapin():
	return map(int, input().split())
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
ans = 0
d = []
for i in range(n):
	(aa, bb) = mapin()
	d.append([bb, aa])
	ans += aa
d.sort()
l = 0
r = n - 1
st = 0
while l <= r:
	if d[l][0] <= st:
		st += d[l][1]
		l += 1
	else:
		mi = min(d[l][0] - st, d[r][1])
		ans += mi
		st += mi
		d[r][1] -= mi
		if d[r][1] > 0:
			continue
		r -= 1
print(ans)


from sys import stdin
input = stdin.readline
rn = lambda : int(input())
rns = lambda : map(int, input().split())
rl = lambda : list(map(int, input().split()))
rs = lambda : input()
YN = lambda x: print('YES') if x else print('NO')
mod = 10 ** 9 + 7
n = rn()
items = []
t = 0
for i in range(n):
	items.append(rl())
	t += items[-1][0]
items.sort(key=lambda x: (x[1], x[0]))
ans = 0
acc = 0
start = 0
while acc < t:
	if items[start][1] <= acc:
		ans += items[start][0]
		acc += items[start][0]
		start += 1
	else:
		sub = min(items[start][1] - acc, items[-1][0])
		ans += sub * 2
		acc += sub
		items[-1][0] -= sub
		if items[-1][0] == 0:
			items.pop()
print(ans)


prices = []
count = 0
n = int(input())
for _ in range(n):
	(ai, bi) = map(int, input().split())
	prices.append([bi, ai])
	count += ai
prices.sort()
discount = 0
for p in range(n - 1, -1, -1):
	x = prices[p]
	if x[0] >= count:
		continue
	else:
		discount += min(count - x[0] - discount, x[1])
print(count * 2 - discount)


import math
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = 1
for _ in range(t):
	n = int(input())
	b = []
	ans = 0
	for j in range(n):
		(p, q) = list(map(int, input().split()))
		b.append([q, p])
	b.sort()
	ans = 0
	i = 0
	j = n - 1
	s = 0
	while i <= j:
		(val, cnt) = b[i]
		if s >= val:
			ans += cnt
			s += cnt
		else:
			while j > i:
				if s + b[j][1] >= val:
					b[j][1] += -(val - s)
					ans += 2 * (val - s)
					s = val
					if b[j][1] == 0:
						j += -1
					break
				else:
					s += b[j][1]
					ans += 2 * b[j][1]
					j += -1
			if i == j:
				if s + cnt <= val:
					ans += cnt * 2
					s += cnt
				else:
					ans += cnt + val - s
			else:
				ans += cnt
				s += cnt
		i += 1
	print(ans)


import sys
input = sys.stdin.buffer.readline
n = int(input())
a = []
for i in range(n):
	(b, c) = map(int, input().split())
	a.append([c, b])
a.sort(reverse=True)
pre_cup = 0
cost = 0
i = 0
j = n - 1
add = 0
while i <= j:
	if pre_cup >= a[j][0]:
		cost += a[j][1]
		pre_cup += a[j][1]
		j -= 1
	elif pre_cup + a[i][1] > a[j][0] and i < j:
		cost += (a[j][0] - pre_cup) * 2
		cost += a[j][1]
		a[i][1] -= a[j][0] - pre_cup
		pre_cup += a[j][1] + a[j][0] - pre_cup
		j -= 1
	else:
		rec_cup = a[i][1]
		limit = a[i][0]
		if pre_cup + rec_cup >= limit:
			cost += (limit - pre_cup) * 2
			cost += rec_cup - (limit - pre_cup)
			pre_cup += rec_cup
		else:
			cost += rec_cup * 2
			pre_cup += rec_cup
		i += 1
	add += 1
print(cost)


(b, a) = zip(*sorted(([*map(int, s.split())][::-1] for s in [*open(0)][1:])))
(*a,) = a
i = c = r = 0
j = len(a) - 1
while i <= j:
	if (d := min(b[i] - c, a[j])) > 0:
		a[j] -= d
		c += d
		r += d
		j -= a[j] < 1
	else:
		c += a[i]
		i += 1
print(c + r)


import sys
import math
import bisect
import heapq
from bisect import bisect_right
from sys import stdin, stdout

def get_ints_in_variables():
	return map(int, sys.stdin.readline().strip().split())

def get_int():
	return int(sys.stdin.readline())

def get_ints_in_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_list_of_list(n):
	return [list(map(int, sys.stdin.readline().strip().split())) for _ in range(n)]

def get_string():
	return sys.stdin.readline().strip()

def myceil(x, y):
	return (x + y - 1) // y

def Solution(a, n):
	arr = sorted(a, key=lambda x: x[1])
	i = 0
	j = n - 1
	atLeast = arr[0][1]
	BoughtProduct = 0
	ans = 0
	while i <= j:
		if BoughtProduct < atLeast:
			tmp = min([atLeast - BoughtProduct, arr[j][0]])
			BoughtProduct += tmp
			arr[j][0] -= tmp
			ans += 2 * tmp
		if BoughtProduct >= atLeast:
			tmp = arr[i][0]
			ans += tmp
			BoughtProduct += tmp
			arr[i][0] = 0
			i += 1
			if i <= j:
				atLeast = arr[i][1]
			else:
				break
		else:
			j -= 1
	print(ans)

def main():
	n = get_int()
	arr = get_list_of_list(n)
	Solution(arr, n)
main()


n = int(input())
li = []
for i in range(n):
	(a, b) = map(int, input().split())
	temp = [b, a]
	li.append(temp)
li.sort()
a = 0
b = n - 1
cost = 0
count = 0
while a <= b:
	if count >= li[a][0]:
		count += li[a][1]
		cost += li[a][1]
		a += 1
	else:
		c = li[a][0] - count
		if c >= li[b][1]:
			count += li[b][1]
			cost += 2 * li[b][1]
			b -= 1
		else:
			li[b][1] -= c
			count += c
			cost += 2 * c
print(cost)


import sys, io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
getlist = lambda : map(int, input().split())
n = int(input())
(a, b) = ([], [])
for i in range(n):
	(c, d) = getlist()
	b.append((d, c))
b.sort()
tar = sum(map(lambda x: x[1], b))
bgt = 0
id = 0
ans = 0
while bgt < tar:
	if b[id][0] <= bgt:
		ans += min(b[id][1], tar - bgt)
		bgt += min(b[id][1], tar - bgt)
		id += 1
	else:
		ans += 2 * (min(tar, b[id][0]) - bgt)
		bgt = min(tar, b[id][0])
print(ans)


n = int(input())
li = []
for i in range(n):
	(a, b) = map(int, input().split())
	li.append((b, a))
li.sort()
cost = 0
nitems = 0
while len(li) > 0:
	if li[0][0] <= nitems:
		cost += li[0][1]
		nitems += li[0][1]
		del li[0]
	elif li[0][0] >= nitems + li[-1][1]:
		cost += 2 * li[-1][1]
		nitems += li[-1][1]
		del li[-1]
	else:
		cost += 2 * (li[0][0] - nitems)
		li[-1] = (li[-1][0], li[-1][1] - li[0][0] + nitems)
		nitems += li[0][0] - nitems
print(cost)


from math import *

def read(type=int):
	return list(map(type, input().split()))
n = read()[0]
data = [read() for _ in range(n)]
data.sort(key=lambda x: x[1])
(l_cur, r_cur, cnt, price) = (0, n - 1, 0, 0)
while l_cur <= r_cur:
	if cnt >= data[l_cur][1]:
		cnt += data[l_cur][0]
		price += data[l_cur][0]
		l_cur += 1
	else:
		req = data[l_cur][1] - cnt
		if data[r_cur][0] <= req:
			cnt += data[r_cur][0]
			price += data[r_cur][0] * 2
			r_cur -= 1
		else:
			cnt += req
			price += req * 2
			data[r_cur][0] -= req
print(price)


def solve(n, amounts):
	amounts.sort(key=lambda x: x[1])
	tot = sum([x[0] for x in amounts])
	cur = min(amounts[0][1], tot)
	waste = cur
	for (a, b) in amounts:
		if cur >= tot:
			return tot + waste
		if cur >= b:
			cur += a
		else:
			waste += min(tot, b) - cur
			cur = b + a
	return tot + waste
import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input().decode().strip())
amounts = []
for i in range(n):
	(a, b) = [int(x) for x in input().decode().strip().split(' ')]
	amounts.append((a, b))
res = solve(n, amounts)
print(res)


import sys
input = sys.stdin.readline
n = int(input())
ab = [list(map(int, input().split())) for i in range(n)]
ab.sort(key=lambda x: x[1])
sa = 0
for i in range(n):
	sa += ab[i][0]
c = 0
for i in range(n)[::-1]:
	r = sa - ab[i][1]
	c += max(min(r, ab[i][0]), 0)
	sa -= max(min(r, ab[i][0]), 0)
print(sa * 2 + c)


n = int(input())
a = []
for _ in range(n):
	(x, y) = map(int, input().split())
	a.append([x, y])
a.sort(key=lambda k: k[1])
needed = a[0][1]
items = 0
i = 0
j = n - 1
ans = 0
while True:
	if i > j:
		break
	elif i == j:
		if items >= a[i][1]:
			ans += a[i][0]
		else:
			need = a[i][1] - items
			if need > a[i][0]:
				ans += 2 * a[i][0]
			else:
				ans += 2 * need
				ans += a[i][0] - need
			break
	if a[j][0] + items < needed:
		ans += 2 * a[j][0]
		items += a[j][0]
		j -= 1
	elif a[j][0] + items == needed:
		ans += 2 * a[j][0]
		items += a[j][0]
		a[j][0] = 0
		while i <= j:
			if a[i][1] <= items:
				ans += a[i][0]
				items += a[i][0]
			else:
				needed = a[i][1]
				break
			i += 1
		j -= 1
	else:
		need = needed - items
		ans += 2 * need
		a[j][0] -= need
		items += need
		while i <= j:
			if a[i][1] <= items:
				ans += a[i][0]
				items += a[i][0]
			else:
				needed = a[i][1]
				break
			i += 1
print(ans)


from collections import deque
n = int(input())
x = []
for i in range(n):
	(a, b) = map(int, input().split())
	x.append([b, a])
x.sort(reverse=True)
x = deque(x)
ans = 0
cc = 0
while x:
	if x[-1][0] <= cc:
		ans += x[-1][1]
		cc += x[-1][1]
		x.pop()
	elif x[0][1] > x[-1][0] - cc:
		need = x[-1][0] - cc
		x[0][1] -= need
		ans += need * 2
		cc += need
	else:
		ans += x[0][1] * 2
		cc += x[0][1]
		x.popleft()
print(ans)


from collections import defaultdict
import heapq
import sys
input = sys.stdin.readline
n = int(input())
s = 0
h = []
cnt = defaultdict(lambda : 0)
for _ in range(n):
	(a, b) = map(int, input().split())
	s += a
	cnt[b] += a
x = [i for i in cnt]
x.sort()
(l, r) = (0, len(x) - 1)
ans = s
now = 0
while l <= r:
	(xl, xr) = (x[l], x[r])
	if xl > now:
		if xl >= now + cnt[xr]:
			now += cnt[xr]
			ans += cnt[xr]
			cnt[xr] = 0
			r -= 1
		else:
			y = xl - now
			now += y
			ans += y
			cnt[xr] -= y
	else:
		now += cnt[xl]
		l += 1
print(ans)


N = int(input())
A = [0] * N
B = [0] * N
for i in range(N):
	(A[i], B[i]) = map(int, input().split())
indices = list(range(N))
indices.sort(key=lambda i: B[i])
low = 0
high = N - 1
bought = 0
cost = 0
while low <= high:
	l = indices[low]
	h = indices[high]
	if bought >= B[l]:
		bought += A[l]
		cost += A[l]
		A[l] = 0
		low += 1
	elif B[l] - bought >= A[h]:
		bought += A[h]
		cost += 2 * A[h]
		A[h] = 0
		high -= 1
	else:
		need = B[l] - bought
		bought += need
		cost += 2 * need
		A[h] -= need
assert sum(A) == 0
print(cost)


n = int(input())
arr = []
for i in range(n):
	(a, b) = list(map(int, input().split()))
	arr.append([b, a])
arr.sort()
(i, j) = (0, n - 1)
ans = 0
cnt = 0
while i <= j:
	if arr[i][0] <= cnt:
		cnt += arr[i][1]
		ans += arr[i][1]
		i += 1
	else:
		req = min(arr[i][0] - cnt, arr[j][1])
		cnt += req
		arr[j][1] -= req
		ans += 2 * req
		if arr[j][1] == 0:
			j -= 1
print(ans)


n = int(input())
a = [''] * n
ans = 0
sm = 0
for i in range(n):
	(g, h) = [int(x) for x in input().split()]
	a[i] = [h, g]
	sm += g
a.sort()
for i in range(n - 1, -1, -1):
	x = a[i]
	k = min(x[0], sm)
	ans += min(sm - ans - k, x[1])
print(sm * 2 - ans)


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(n,) = I()
l = []
for _ in range(n):
	l.append(I())
l.sort(key=lambda x: x[1])
an = 0
mx = n - 1
tot = 0
for i in range(n):
	(a, b) = l[i]
	if a <= 0:
		break
	if b <= tot:
		an += a
		tot += a
		continue
	take = 0
	for j in range(mx, i, -1):
		if tot + take < b:
			cur = min(l[j][0], b - (tot + take))
			take += cur
			l[j][0] -= cur
		if l[j][0]:
			mx = j
			break
	tot += take
	an += take * 2
	if tot >= b:
		an += a
	else:
		x = b - tot
		if x <= a:
			an += a - x + 2 * x
		else:
			an += 2 * a
	tot += a
print(an)


import sys
input = sys.stdin.readline

def mp():
	return map(int, input().split())

def lmp():
	return list(map(int, input().split()))

def mps(A):
	return [tuple(map(int, input().split())) for _ in range(A)]
import math
import bisect
from copy import deepcopy as dc
from itertools import accumulate
from collections import Counter, defaultdict, deque

def ceil(U, V):
	return (U + V - 1) // V

def modf1(N, MOD):
	return (N - 1) % MOD + 1
inf = int(1e+20)
mod = int(1000000000.0 + 7)
n = int(input())
d = defaultdict(lambda : 0)
for _ in range(n):
	(a, b) = mp()
	d[b] += a
d = list(Counter(d).items())
d.sort()
q = deque(d)
cnt = 0
cost = 0
while q:
	pre = q.popleft()
	if cnt >= pre[0]:
		cnt += pre[1]
		cost += pre[1]
	else:
		need = pre[0] - cnt
		q.appendleft(pre)
		while q:
			tar = q.pop()
			if tar[1] + cnt < need:
				cnt += tar[1]
				cost += 2 * tar[1]
			else:
				nanko = pre[0] - cnt
				cnt += nanko
				cost += 2 * nanko
				if tar[1] - nanko != 0:
					q.append((tar[0], tar[1] - nanko))
				break
print(cost)


n = int(input())
ab = []
for i in range(n):
	ab.append([int(x) for x in input().split()])
ab.sort(key=lambda x: x[1])
i = 0
j = n - 1
cnt = 0
ans = 0
while i <= j:
	if ab[i][1] <= cnt:
		ans += ab[i][0]
		cnt += ab[i][0]
		ab[i][0] = 0
		i += 1
	else:
		k = min(ab[j][0], ab[i][1] - cnt)
		ab[j][0] -= k
		cnt += k
		ans += k * 2
		if ab[j][0] == 0:
			j -= 1
print(ans)


N = int(input())
A = [0] * N
for i in range(N):
	A[i] = list(map(int, input().split()))
A.sort(key=lambda a: a[1])
low = 0
high = N - 1
bought = 0
cost = 0
while low <= high:
	if bought >= A[low][1]:
		bought += A[low][0]
		cost += A[low][0]
		A[low][0] = 0
		low += 1
	elif A[low][1] - bought >= A[high][0]:
		bought += A[high][0]
		cost += 2 * A[high][0]
		A[high][0] = 0
		high -= 1
	else:
		need = A[low][1] - bought
		bought += need
		cost += 2 * need
		A[high][0] -= need
assert all([A[i][0] == 0 for i in range(N)])
print(cost)


t = int(input())
a = []
for T in range(t):
	b = list(map(int, input().split()))
	a.append(b)
h = sorted(a, key=lambda x: x[1])
s = 0
j = 0
i = len(h) - 1
cost = 0
while j <= i:
	k = h[i][0]
	if k + s < h[j][1]:
		s = s + k
		i = i - 1
		cost = cost + 2 * k
	elif k + s == h[j][1]:
		s = s + k
		i = i - 1
		cost = cost + 2 * k
		while s >= h[j][1] and j < i:
			cost = cost + h[j][0]
			s = s + h[j][0]
			j = j + 1
			if j > i:
				break
	elif j != i:
		his = h[j][1] - s
		cost = cost + his * 2
		s = s + his
		h[i][0] = k - his
		while s >= h[j][1] and j < i:
			cost = cost + h[j][0]
			s = s + h[j][0]
			j = j + 1
			if j > i:
				break
	else:
		if s + k > h[i][1]:
			hi = s + k - h[i][1]
			if hi >= k:
				cost = cost + k
			else:
				cost = cost + hi
				cost = cost + (k - hi) * 2
		j = j + 1
		i = i - 1
print(cost)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def solve():
	n = int(input())
	arr = [list(map(int, input().split())) for i in range(n)]
	arr.sort(key=lambda x: x[1])
	(i, j) = (0, n - 1)
	(ans, cur) = (0, 0)
	while i <= j:
		if arr[i][1] <= cur:
			cur += arr[i][0]
			i += 1
		elif arr[j][0] + cur <= arr[i][1]:
			cur += arr[j][0]
			ans += arr[j][0]
			j -= 1
		else:
			arr[j][0] -= arr[i][1] - cur
			ans += arr[i][1] - cur
			cur = arr[i][1]
	return ans + cur
print(solve())


n = int(input())
product = []
for i in range(n):
	product.append(list(map(int, input().split())))
product.sort(key=lambda x: x[1], reverse=True)
sum = 0
i = 0
j = n - 1
answer = 0
while j >= i:
	if sum >= product[j][1]:
		answer += product[j][0]
		sum += product[j][0]
		product[j][0] = 0
		j -= 1
	elif product[i][0] >= product[j][1] - sum:
		answer += 2 * (product[j][1] - sum)
		product[i][0] -= product[j][1] - sum
		sum += product[j][1] - sum
	else:
		sum += product[i][0]
		answer += product[i][0] * 2
		product[i][0] = 0
		i += 1
print(answer)


from sys import stdin
input = stdin.readline

def f(ar):
	ar = sorted(ar, reverse=True, key=lambda s: s[1])
	(cost, cs, lo) = (0, 0, 0)
	hi = len(ar) - 1
	while lo <= hi:
		if ar[hi][1] <= cs:
			cost += ar[hi][0]
			cs += ar[hi][0]
			hi -= 1
		elif ar[hi][1] - cs <= ar[lo][0]:
			ar[lo][0] -= ar[hi][1] - cs
			cost += 2 * (ar[hi][1] - cs)
			cs += ar[hi][1] - cs
			cs += ar[hi][0]
			cost += ar[hi][0]
			hi -= 1
		else:
			cs += ar[lo][0]
			cost += ar[lo][0] * 2
			lo += 1
	return cost
ar = []
for _ in range(int(input())):
	(a, b) = map(int, input().strip().split())
	ar.append([a, b])
print(f(ar))


def solve(n, items):
	items.sort(key=lambda x: x[1])
	ans = 0
	cnt = 0
	l = 0
	r = n - 1
	while l <= r:
		if items[l][1] <= cnt:
			cnt += items[l][0]
			ans += items[l][0]
			items[l][0] = 0
			l += 1
		else:
			diff = min(items[l][1] - cnt, items[r][0])
			cnt += diff
			ans += diff * 2
			items[r][0] -= diff
			if items[r][0] == 0:
				r -= 1
	return ans
n = int(input())
items = []
for i in range(n):
	(a, b) = map(int, input().split())
	items.append([a, b])
print(solve(n, items))


import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
PI = 3.141592653589793
INF = float('inf')
MOD = 1000000007

def add(x, y):
	return (x + y) % MOD

def sub(x, y):
	return (x - y + MOD) % MOD

def mul(x, y):
	return x * y % MOD

def gcd(x, y):
	if y == 0:
		return x
	return gcd(y, x % y)

def lcm(x, y):
	return x * y // gcd(x, y)

def power(x, y):
	res = 1
	x %= MOD
	while y != 0:
		if y & 1:
			res = mul(res, x)
		y >>= 1
		x = mul(x, x)
	return res

def mod_inv(n):
	return power(n, MOD - 2)

def prob(p, q):
	return mul(p, power(q, MOD - 2))

def ii():
	return int(input())

def li():
	return [int(i) for i in input().split()]

def ls():
	return [i for i in input().split()]
n = ii()
store = []
for i in range(n):
	(a, b) = li()
	store.append([b, a])
store.sort()
l = 0
r = n - 1
bought = 0
ans = 0
while l <= r:
	if store[l][0] <= bought:
		ans += store[l][1]
		bought += store[l][1]
		l += 1
	else:
		re = min(store[l][0] - bought, store[r][1])
		store[r][1] -= re
		ans += 2 * re
		bought += re
		if store[r][1] == 0:
			r -= 1
print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import *
from collections import deque
from operator import itemgetter, attrgetter
from decimal import *
import bisect
import math
import heapq as hq
MOD = 10 ** 9 + 7

def is_prime(n):
	if n == 2 or n == 3:
		return True
	if n < 2 or n % 2 == 0:
		return False
	if n < 9:
		return True
	if n % 3 == 0:
		return False
	r = int(n ** 0.5)
	f = 5
	while f <= r:
		if n % f == 0:
			return False
		if n % (f + 2) == 0:
			return False
		f += 6
	return True

def pow(a, b, m):
	ans = 1
	while b:
		if b & 1:
			ans = ans * a % m
		b //= 2
		a = a * a % m
	return ans

def ispalindrome(s):
	if s[:] == s[::-1]:
		return 1
	return 0
dp = []
limit = []
v = []

def dpdfs(u, t=-1):
	dp[0][u] = 0
	dp[1][u] = 0
	for i in v[u]:
		if i == t:
			continue
		if dp[1][i] == -1:
			dpdfs(i, u)
		dp[0][u] += max(abs(limit[0][u] - limit[1][i]) + dp[1][i], abs(limit[0][u] - limit[0][i]) + dp[0][i])
		dp[1][u] += max(abs(limit[1][u] - limit[1][i]) + dp[1][i], abs(limit[1][u] - limit[0][i]) + dp[0][i])
vis = []

def dfs(v):
	if vis[v] == 0:
		return
	vis[v] = 0
	for vv in g[v]:
		dfs(vv)
n = int(input())
l = []
for _ in range(n):
	(a, b) = map(int, input().split())
	l.append([b, a])
l.sort()
ans = 0
count = 0
i = 0
j = len(l) - 1
while i <= j:
	if count >= l[i][0]:
		count += l[i][1]
		ans += l[i][1]
		i += 1
		continue
	if count + l[j][1] <= l[i][0]:
		count += l[j][1]
		ans += 2 * l[j][1]
		j -= 1
		continue
	ans += 2 * (l[i][0] - count)
	l[j][1] = l[j][1] - (l[i][0] - count)
	count = l[i][0]
print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import deque
n = int(input())
l = sorted([list(map(int, input().split())) for i in range(n)], key=lambda x: x[1])
q = deque(l)
ans = 0
c = 0
while len(q):
	a = q.popleft()
	if c < a[1]:
		if len(l):
			while c < a[1] and len(q):
				b = q.pop()
				x = min(a[1] - c, b[0])
				ans += 2 * x
				c += x
				b[0] -= x
				if b[0]:
					q.append(b)
			if not len(q) and c < a[1]:
				x = min(a[1] - c, a[0])
				ans += 2 * x
				c += x
				a[0] -= x
				ans += a[0]
				c += a[0]
			else:
				ans += a[0]
				c += a[0]
		else:
			x = min(a[1] - c, a[0])
			ans += 2 * x
			c += x
			a[0] -= x
			ans += a[0]
			c += a[0]
	else:
		ans += a[0]
		c += a[0]
print(ans)


a = sorted(([*map(int, s.split())][::-1] for s in [*open(0)][1:]))
i = c = r = 0
j = len(a) - 1
while i <= j:
	x = (_, y) = a[j]
	d = min(a[i][0] - c, y)
	if d > 0:
		x[1] -= d
		r += d
		j -= d == y
	else:
		d = a[i][1]
		i += 1
	c += d
print(c + r)


n = int(input())
a = [0] * n
b = [0] * n
bb = []
for i in range(n):
	(a[i], b[i]) = map(int, input().split())
	bb.append((i, a[i], b[i]))
bb.sort(key=lambda x: x[2])
tot = sum(a)
lg = n - 1
rm = bb[lg][1]
bought = 0
while rm == 0:
	lg -= 1
	rm = bb[lg][1]
res = 0
fg = 0
while bb[fg][1] == 0:
	fg += 1
while bought < tot:
	lim = bb[fg][2]
	while bought < lim and bought < tot:
		q = min(rm, lim - bought)
		rm -= q
		bought += q
		res += 2 * q
		while rm == 0 and bought < tot:
			lg -= 1
			rm = bb[lg][1]
	if lim <= bought < tot:
		if fg == lg:
			q = rm
		else:
			q = bb[fg][1]
			fg += 1
		bought += q
		res += q
print(res)


n = int(input())
arr = []
ans = 0
for i in range(n):
	arr.append(list(map(int, input().split())))
	ans += 2 * arr[-1][0]
arr.sort(key=lambda x: x[1], reverse=True)
(i, j, curr) = (0, n - 1, 0)
while i <= j:
	tar = arr[j][1]
	if i == j:
		can = arr[i][0]
		to = max(0, arr[i][1] - curr)
		cantake = max(0, can - to)
		ans -= cantake
		break
	elif curr >= tar:
		curr += arr[j][0]
		ans -= arr[j][0]
		j -= 1
	elif curr + arr[i][0] <= arr[j][1]:
		curr += arr[i][0]
		arr[i][0] = 0
		i += 1
	else:
		totake = arr[j][1] - curr
		curr += totake
		curr += arr[j][0]
		arr[i][0] -= totake
		ans -= arr[j][0]
		j -= 1
print(ans)


import math
import os
import sys
from sys import *
from decimal import *
from io import BytesIO, IOBase
from itertools import accumulate, combinations, permutations, combinations_with_replacement, product
from collections import *
M = 10 ** 9 + 7
import heapq
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def inpu():
	return int(inp())

def dfs(root, nodeVal, nodeConnection, visited):
	leftVal = nodeVal[root][0]
	rightVal = nodeVal[root][1]
	solution = []
	if nodeConnection[root]:
		visited.add(root)
		for i in nodeConnection[root]:
			if i not in visited:
				solution.append(dfs(i, nodeVal, nodeConnection, visited))
		leftMax = 0
		rightMax = 0
		for i in solution:
			(l, r) = i
			leftMax += max(abs(leftVal - l[0]) + l[1], abs(leftVal - r[0]) + r[1])
			rightMax += max(abs(rightVal - l[0]) + l[1], abs(rightVal - r[0]) + r[1])
		return ((leftVal, leftMax), (rightVal, rightMax))
	else:
		return ((leftVal, 0), (rightVal, 0))

def luckynumber(x, n, a):
	if x > 0:
		a.append(x)
	if x > 10 ** 9:
		return a
	elif x < 1000000000000.0:
		luckynumber(x * 10 + 4, n, a)
		luckynumber(x * 10 + 7, n, a)

def lcm(a, b):
	return a * b // math.gcd(a, b)

def query1(l, r):
	if l >= r:
		return -1
	print('?', l + 1, r + 1)
	sys.stdout.flush()
	return int(input()) - 1

def answer(p):
	print('!', p + 1)
	sys.stdout.flush()
	exit()

class Graph(object):

	def __init__(self, vertices):
		self.graph = defaultdict(list)
		self.V = vertices

	def addEdge(self, u, v):
		self.graph[u].append(v)
		self.graph[v].append(u)

	def connectedComponents(self):
		unvisited = set(range(self.V))
		queue = deque()
		count = 0
		while len(unvisited) > 0:
			count += 1
			v = next(iter(unvisited))
			unvisited.remove(v)
			queue.append(v)
			while len(queue) > 0:
				v = queue.popleft()
				for w in self.graph[v]:
					if w in unvisited:
						unvisited.remove(w)
						queue.append(w)
		return count

def maxSumIS(arr, n):
	msis = arr.copy()
	for i in range(1, n):
		for j in range(i):
			if arr[i] > arr[j] and msis[i] < msis[j] + arr[i]:
				msis[i] = msis[j] + arr[i]
	c = max(msis)
	p = 5
	return c

def binarysearch2(arr, target):
	lo = 0
	hi = len(arr) - 1
	while lo <= hi:
		mid = (lo + hi) // 2
		if arr[mid] == target:
			if mid != len(arr) - 1:
				if arr[mid + 1] != target:
					return mid
				else:
					lo += 1
			else:
				return mid
			continue
		if arr[mid] > target:
			hi = mid - 1
		else:
			lo = mid + 1

def ngr(arr, n):
	stack = []
	ans = []
	for i in range(n - 1, -1, -1):
		if len(stack) == 0:
			ans.append(-1)
		else:
			while len(stack) > 0:
				if stack[-1][0] < arr[i]:
					stack.pop()
				else:
					break
			if len(stack) == 0:
				ans.append(-1)
			else:
				ans.append(stack[-1][1])
		stack.append([arr[i], i])
	ans.reverse()
	return ans

def alperm(nums, ans, c, n):
	if len(ans) == len(nums):
		ans.append(c)
		return
	if n <= 0:
		return
	op = c + [nums[n - 1]]
	alperm(nums, ans, op, n - 1)
	alperm(nums, ans, c, n - 1)

def main():
	n = int(input())
	arr = []
	for i in range(n):
		(a, b) = map(int, input().split())
		arr.append([a, b])
	arr.sort(key=lambda x: x[1])
	(i, j) = (0, n - 1)
	(ans, curr) = (0, 0)
	while i <= j:
		if arr[i][1] <= curr:
			curr += arr[i][0]
			i += 1
		elif arr[j][0] + curr <= arr[i][1]:
			curr += arr[j][0]
			ans += arr[j][0]
			j -= 1
		else:
			arr[j][0] -= arr[i][1] - curr
			ans += arr[i][1] - curr
			curr = arr[i][1]
	print(ans + curr)
main()


import sys
from bisect import bisect_left as lb
from collections import deque
from queue import PriorityQueue as pq
input_ = lambda : sys.stdin.readline().strip('\r\n')
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = lambda : list(map(float, input_().split()))
ip = lambda : input_()
fi = lambda : float(input_())
ap = lambda ab, bc, cd: ab[bc].append(cd)
li = lambda : list(input_())
pr = lambda x: print(x)
prinT = lambda x: print(x)
f = lambda : sys.stdout.flush()
inv = lambda x: pow(x, mod - 2, mod)
mod = 10 ** 9 + 7
n = ii()
a = []
for i in range(n):
	(x, y) = il()
	a.append([x, y])
a.sort(key=lambda i: i[1])
s = 0
e = n - 1
so = 0
co = 0
while s <= e:
	if so >= a[s][1]:
		so += a[s][0]
		co += a[s][0]
		s += 1
	elif a[e][0] >= a[s][1] - so:
		co += 2 * (a[s][1] - so)
		to = a[s][1] - so
		a[e][0] = a[e][0] - (a[s][1] - so)
		so += to
	else:
		so += a[e][0]
		co += 2 * a[e][0]
		e -= 1
print(co)


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from collections import Counter
from collections import defaultdict as dd
flush = lambda : stdout.flush()
stdstr = lambda : stdin.readline()
stdint = lambda : int(stdin.readline())
stdpr = lambda x: stdout.write(str(x))
stdmap = lambda : map(int, stdstr().split())
stdarr = lambda : list(map(int, stdstr().split()))
mod = 1000000007
n = stdint()
pairs = []
for _ in range(n):
	pairs.append(list(stdmap()))
pairs.sort(key=lambda x: (x[1], x[0]))
bought = 0
cost = 0
(i, j) = (0, n - 1)
while i <= j:
	if bought >= pairs[i][1]:
		bought += pairs[i][0]
		cost += pairs[i][0]
		pairs[i][0] = 0
		i += 1
	else:
		needed = pairs[i][1] - bought
		cost += min(needed, pairs[j][0]) * 2
		bought += min(needed, pairs[j][0])
		pairs[j][0] -= min(needed, pairs[j][0])
		if pairs[j][0] == 0:
			j -= 1
print(cost)


import sys
import math
from collections import deque
from bisect import bisect_left, bisect_right
I = sys.stdin.readline
II = lambda : int(I())
IN = lambda x: map(int, x.split())
L = lambda x: list(IN(x))

def P(*x, end='\n'):
	print(*x, end=end)
n = II()
d = []
for i in range(n):
	(a, b) = IN(I())
	d.append([b, a])
l = sorted(d)
i = 0
t = 0
j = n - 1
cost = 0
while i < j:
	req = l[i][0]
	while t < req and i < j:
		f = min(l[j][1], req - t)
		t += f
		cost += 2 * f
		l[j][1] -= f
		if l[j][1] == 0:
			j -= 1
	if i == j:
		break
	t += l[i][1]
	cost += l[i][1]
	i += 1
if i == j:
	temp = max(l[i][0] - t, 0)
	z = min(temp, l[i][1])
	cost += z + l[i][1]
P(cost)


import sys
from bisect import bisect_left as lb
from collections import deque
from queue import PriorityQueue as pq
input_ = lambda : sys.stdin.readline().strip('\r\n')
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = lambda : list(map(float, input_().split()))
ip = lambda : input_()
fi = lambda : float(input_())
ap = lambda ab, bc, cd: ab[bc].append(cd)
li = lambda : list(input_())
pr = lambda x: print(x)
prinT = lambda x: print(x)
f = lambda : sys.stdout.flush()
inv = lambda x: pow(x, mod - 2, mod)
mod = 10 ** 9 + 7
n = ii()
a = []
for i in range(n):
	(x, y) = il()
	a.append([x, y])
a.sort(key=lambda i: i[1])
ind = n - 1
ans = 0
t = 0
for i in range(n):
	x = a[i][1]
	t1 = t
	if t < x:
		for j in range(ind, i - 1, -1):
			y = a[j][0]
			if t + y >= x:
				z = min(x - t, y)
				a[j][0] -= z
				if a[j][0] == 0:
					ind -= 1
				t += z
				break
			else:
				t += y
				a[j][0] = 0
				ind -= 1
	ans += (t - t1) * 2
	if t >= x:
		ans += a[i][0]
		t += a[i][0]
		a[i][0] = 0
	else:
		ans += 2 * a[i][0]
		t += a[i][0]
		a[i][0] = 0
print(ans)


n = int(input())
T = []
for _ in range(n):
	(a, b) = map(int, input().split(' '))
	T.append([a, b])
T.sort(key=lambda e: e[1])
price = 0
total = 0
(l, r) = (0, len(T) - 1)
while l < r:
	(a, b) = T[l]
	if total >= b:
		price += a
		total += a
		T[l][0] = 0
		l += 1
	else:
		d = b - total
		while l < r and d > 0:
			(ar, br) = T[r]
			if ar > d:
				price += 2 * d
				T[r][0] -= d
				total += d
				d = 0
			else:
				price += 2 * ar
				T[r][0] = 0
				r -= 1
				total += ar
				d -= ar
(a, b) = T[l]
if a != 0:
	if total >= b:
		price += a
	elif a + total >= b:
		price += 2 * (b - total) + (a + total - b)
	else:
		price += 2 * a
print(price)


n = int(input())
li = []
for case in range(n):
	tp = list(map(int, input().split()))
	li.append(tp)
li.sort(key=lambda x: (x[1], x[0]))
(l, r) = (0, len(li) - 1)
totalBought = 0
totalCost = 0
while l <= r:
	minNeedForDisc = max(li[l][1] - totalBought, 0)
	if not minNeedForDisc:
		totalBought += li[l][0]
		totalCost += li[l][0]
		li[l][0] = 0
		l += 1
	else:
		buy = min(minNeedForDisc, li[r][0])
		totalBought += buy
		totalCost += 2 * buy
		li[r][0] -= buy
		if not li[r][0]:
			r -= 1
print(totalCost)


n = int(input())
a = []
b = []
for i in range(n):
	(x, y) = map(int, input().split())
	a.append(x)
	b.append(y)
ba = zip(b, a)
ba = sorted(ba)
temp = []
for i in ba:
	temp.append(list(i))
ba = temp
ans = 0
i = 0
j = n - 1
c = 0
while i <= j:
	if c >= ba[i][0]:
		c += ba[i][1]
		ans += ba[i][1]
		i += 1
	else:
		if ba[j][1] == 0:
			j -= 1
		else:
			tmp = min(ba[i][0] - c, ba[j][1])
			c += tmp
			ans += 2 * tmp
			ba[j][1] -= tmp
		if ba[j][1] == 0:
			j -= 1
print(ans)


import sys
input = sys.stdin.readline
n = int(input())
ar = []
for i in range(int(n)):
	ar.append(list(map(int, input().split())))
ar.sort(key=lambda x: x[1])
j = n - 1
tot = 0
ans = 0
for i in range(n):
	req = max(ar[i][1] - tot, 0)
	while req != 0:
		if j < 0:
			break
		a = ar[j][0]
		if a <= req:
			req -= a
			tot += a
			ar[j][0] = 0
			j -= 1
			ans += 2 * a
		else:
			ar[j][0] -= req
			tot += req
			ans += 2 * req
			req = 0
			break
	if req == 0:
		ans += ar[i][0]
	else:
		ans += ar[i][0] * 2
	tot += ar[i][0]
	ar[i][0] = 0
print(ans)


n = int(input())
items = []
for i in range(n):
	(a, b) = map(int, input().split())
	items.append([b, a])
items.sort()
head = 0
tail = len(items) - 1
count = 0
pay = 0
while head != tail:
	(head_need, head_left) = items[head]
	(tail_need, tail_left) = items[tail]
	if count >= head_need:
		count += head_left
		pay += head_left
		head += 1
	elif tail_left > head_need - count:
		items[tail][1] -= head_need - count
		pay += 2 * (head_need - count)
		count += head_need - count
	else:
		count += tail_left
		pay += 2 * tail_left
		tail -= 1
(head_need, head_left) = items[head]
if head_need - count >= head_left:
	pay += 2 * head_left
else:
	pay += max(head_need - count, 0) * 2 + head_left - max(head_need - count, 0)
print(pay)


import sys, math
import heapq
from collections import deque
input = sys.stdin.readline

def ip():
	return int(input())

def sp():
	return str(input().rstrip())

def mip():
	return map(int, input().split())

def msp():
	return map(str, input().split().rstrip())

def lmip():
	return list(map(int, input().split()))

def lmsp():
	return list(map(str, input().split().rstrip()))

def list1(x, i):
	return [i for _ in range(x)]

def list2(x, y, i):
	return [[i for _ in range(y)] for _ in range(x)]

def list3(x, y, z, i):
	return [[[i for _ in range(z)] for _ in range(y)] for _ in range(x)]

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def lcm(x, y):
	return x * y // gcd(x, y)

def isPrime(x):
	if x == 1:
		return False
	for i in range(2, int(x ** 0.5) + 1):
		if x % i == 0:
			return False
	return True

def find(x):
	if x == p[x]:
		return x
	q = find(p[x])
	p[x] = q
	return q

def union(x, y):
	global n
	x = find(x)
	y = find(y)
	if x != y:
		p[y] = x

def getPow(a, x):
	ret = 1
	while x:
		if x & 1:
			ret = ret * a % MOD
		a = a * a % MOD
		x >>= 1
	return ret

def getInv(x):
	return getPow(x, MOD - 2)

def lowerBound(start, end, key):
	while start < end:
		mid = (start + end) // 2
		if lst[mid] == key:
			end = mid
		elif key < lst[mid]:
			end = mid
		elif lst[mid] < key:
			start = mid + 1
	return end

def upperBound(start, end, key):
	while start < end:
		mid = (start + end) // 2
		if lst[mid] == key:
			start = mid + 1
		elif lst[mid] < key:
			start = mid + 1
		elif key < lst[mid]:
			end = mid
	if end == len(lst):
		return end - 1
	return end
n = ip()
x = []
for i in range(n):
	x.append(lmip())
x.sort(key=lambda x: x[1], reverse=True)
a = []
b = []
for (i, j) in x:
	a.append(i)
	b.append(j)
l = 0
r = n - 1
c = 0
ans = 0
while l <= r:
	while l <= r and a[l] + c <= b[r]:
		ans += a[l] * 2
		c += a[l]
		l += 1
	if l > r:
		break
	m = b[r] - c
	ans += m * 2
	a[l] -= m
	c = b[r]
	while l <= r and c >= b[r]:
		ans += a[r]
		c += a[r]
		r -= 1
print(ans)


import sys
input = sys.stdin.readline
(prod, ones, twos) = (sorted([[int(i) for i in input().split()] for j in range(int(input()))], key=lambda x: x[1]), 0, 0)
for i in range(len(prod)):
	twos += prod[i][0]
for i in range(len(prod) - 1, -1, -1):
	left = max(twos - prod[i][1], 0)
	(twos, ones) = (twos - min(left, prod[i][0]), ones + min(left, prod[i][0]))
print(twos * 2 + ones)


from math import *
from collections import defaultdict as dt
from sys import *
setrecursionlimit(100000)
inp = lambda : stdin.readline().strip()
I = lambda : int(inp())
M = lambda : map(int, inp().split())
L = lambda : list(M())
mod = 1000000007
inf = 100000000000000000000
ss = 'abcdefghijklmnopqrstuvwxyz'

def solve():
	n = I()
	a1 = []
	a = 0
	for _ in range(n):
		(q, w) = M()
		a += q << 1
		a1.append([q, w])
	a1.sort(key=lambda x: x[1])
	a1.reverse()
	(i, j, c) = (0, n - 1, 0)
	while i <= j:
		k = a1[j][1]
		if i ^ j == 0:
			a -= max(0, a1[i][0] - max(0, a1[i][1] - c))
			break
		elif c >= k:
			a -= a1[j][0]
			j = j - 1
			c += a1[j + 1][0]
		elif c + a1[i][0] <= a1[j][1]:
			c += a1[i][0]
			i = i + 1
			a1[i - 1][0] = 0
		else:
			q = a1[j][1] - c
			c += q
			c += a1[j][0]
			a1[i][0] -= q
			j = j - 1
			a -= a1[j + 1][0]
	print(a)
tt = 1
for _ in range(tt):
	solve()


n = int(input())
a = []
b = []
d = 0
bl = []
for i in range(n):
	q = input().split()
	a.append(int(q[0]))
	bl.append([int(q[1]), int(q[0])])
sa = sum(a)
lb = len(bl)
for i in range(lb):
	if bl[i][0] < sa:
		b.append(bl[i])
b.sort(reverse=True)
sat = sa
for i in range(len(b)):
	x = min(sat - b[i][0], b[i][1])
	sat -= x
	d += x
print(2 * sa - d)


n = int(input())
l = []
needed = 0
for _ in range(n):
	(a, b) = map(int, input().split())
	needed += a
	l.append([b, a])
l.sort()
(items, total) = (0, 0)
(i, j) = (0, n - 1)
aa = []
bb = []
for (a, b) in l:
	aa.append(a)
	bb.append(b)
while items < needed:
	if aa[i] <= items:
		buy = bb[i]
		bb[i] = 0
		items += buy
		total += buy
		i += 1
	elif bb[j] >= aa[i] - items:
		buy = aa[i] - items
		bb[j] -= buy
		items += buy
		total += buy * 2
		if bb[j] == 0:
			j -= 1
	else:
		buy = bb[j]
		bb[j] = 0
		items += buy
		total += buy * 2
		j -= 1
print(total)


n = int(input())
lis = []
for i in range(n):
	(a, b) = map(int, input().split())
	lis.append([b, a])
lis.sort()
i = 0
j = n - 1
p_c = 0
price = 0
while i < j:
	if lis[i][0] <= p_c:
		price += lis[i][1]
		p_c += lis[i][1]
		i += 1
	else:
		pick = min(lis[j][1], lis[i][0] - p_c)
		p_c += pick
		price += 2 * pick
		lis[j][1] -= pick
		if lis[j][1] == 0:
			j -= 1
if i == j:
	if lis[i][0] <= p_c:
		price += lis[i][1]
		p_c += lis[i][1]
	else:
		pick = min(lis[i][0] - p_c, lis[i][1])
		price += 2 * pick
		price += max(lis[i][1] - pick, 0)
print(price)


events = []

def solve():
	events.sort(key=lambda x: x[1])
	l = 0
	r = len(events) - 1
	moneyNeeded = 0
	productsBought = 0
	while l <= r:
		if productsBought < events[l][1]:
			delta = events[l][1] - productsBought
			cost = min(events[r][0], delta) * 2
			productsBought += min(events[r][0], delta)
			events[r][0] -= min(events[r][0], delta)
			moneyNeeded += cost
			if events[r][0] == 0:
				r -= 1
		else:
			productsBought += events[l][0]
			moneyNeeded += events[l][0]
			l += 1
	return moneyNeeded
t = int(input())
for test in range(1, t + 1):
	(required, discount) = list(map(int, input().split()))
	events.append([required, discount])
print(f'{solve()}')


import sys, os, io
from sys import stdin
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_left, bisect_right
import math
alphabets = list('abcdefghijklmnopqrstuvwxyz')
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(int(i))
			n = n / i
	if n > 2:
		l.append(n)
	c = dict(Counter(l))
	return list(set(l))

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def sieveForSmallestPrimeFactor():
	MAXN = 100001
	spf = [0 for i in range(MAXN)]
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, math.ceil(math.sqrt(MAXN))):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
	return spf

def getPrimeFactorizationLOGN(x):
	spf = sieveForSmallestPrimeFactor()
	ret = list()
	while x != 1:
		ret.append(spf[x])
		x = x // spf[x]
	return ret

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def si():
	return input()

def divideCeil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

def ii():
	return int(input())

def li():
	return list(map(int, input().split()))
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def solve():
	n = ii()
	l = []
	for i in range(n):
		(a, b) = li()
		l.append([b, a])
	l.sort()
	for i in range(n):
		l[i] = l[i][::-1]
	i = 0
	j = n - 1
	ans = 0
	totalPurchase = 0
	while i <= j:
		if totalPurchase >= l[i][1]:
			ans += l[i][0]
			totalPurchase += l[i][0]
			l[i][0] = 0
			i += 1
		else:
			while i <= j and totalPurchase < l[i][1]:
				avaiable = l[j][0]
				req = l[i][1] - totalPurchase
				if avaiable >= req:
					totalPurchase += req
					l[j][0] -= req
					ans += req * 2
				else:
					totalPurchase += l[j][0]
					ans += 2 * l[j][0]
					l[j][0] = 0
					j -= 1
	print(ans)
t = 1
for _ in range(t):
	solve()


l = []
n = int(input())
for i in range(n):
	l.append(list(map(int, input().split())))
l.sort(key=lambda x: x[1], reverse=True)
c = 0
i = 0
j = n - 1
out = 0
while j >= i:
	if c >= l[j][1]:
		out += l[j][0]
		c += l[j][0]
		l[j][0] = 0
		j -= 1
	elif l[i][0] >= l[j][1] - c:
		out += 2 * (l[j][1] - c)
		l[i][0] -= l[j][1] - c
		c += l[j][1] - c
	else:
		c += l[i][0]
		out += l[i][0] * 2
		l[i][0] = 0
		i += 1
print(out)


import sys
from collections import deque
input = sys.stdin.readline
n = int(input())
a = [0] * n
b = [0] * n
for i in range(n):
	(aa, bb) = map(int, input().split())
	a[i] = aa
	b[i] = bb
total_items = sum(a)
bad_items = 0
for i in range(n):
	bad = a[i] - max(min(total_items - b[i], a[i]), 0)
	a[i] -= bad
	bad_items += bad
possible_indices = deque(sorted([[b[i], a[i]] for i in range(n) if a[i]]))
cost = 2 * total_items
currently_picked = bad_items
while possible_indices:
	while possible_indices and currently_picked < possible_indices[0][0]:
		take = min(possible_indices[0][0] - currently_picked, possible_indices[-1][1])
		possible_indices[-1][1] -= take
		if possible_indices[-1][1] == 0:
			possible_indices.pop()
		currently_picked += take
	if possible_indices:
		discount = possible_indices[0][1]
		cost -= discount
		currently_picked += discount
		possible_indices.popleft()
print(cost)


import math
import sys
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input().strip()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
n = inp()
l = []
cnt = 0
for i in range(n):
	(a, b) = invr()
	l.append([a, b])
	cnt += a * 2
l.sort(key=lambda x: x[1])
l = list(reversed(l))
strt = 0
end = n - 1
val = 0
while strt < end:
	temp = l[end][1]
	if val >= temp:
		val += l[end][0]
		cnt -= l[end][0]
		end -= 1
	elif val + l[strt][0] <= l[end][1]:
		val += l[strt][0]
		l[strt][0] = 0
		strt += 1
	else:
		l[strt][0] -= l[end][1] - val
		val = l[end][0] + l[end][1]
		cnt -= l[end][0]
		end -= 1
if strt == end:
	cnt -= max(0, l[strt][0] - max(0, l[strt][1] - val))
print(cnt)


arr = []
ans = 0
for _ in range(int(input())):
	(a, b) = map(int, input().split())
	arr.append([a, b])
arr.sort(key=lambda a: a[1])
start = 0
end = len(arr) - 1
curr = 0
ans = 0
while start <= end:
	if arr[start][1] > curr:
		temp = min(arr[start][1] - curr, arr[end][0])
		curr += temp
		ans += 2 * temp
		arr[end][0] -= temp
	else:
		temp = arr[start][0]
		curr += temp
		ans += 1 * temp
		arr[start][0] = 0
	if arr[start][0] == 0:
		start += 1
	if arr[end][0] == 0:
		end -= 1
print(ans)


import sys
import math
mod = 10 ** 9 + 7
LI = lambda : [int(k) for k in input().split()]
input = lambda : sys.stdin.readline().rstrip()
IN = lambda : int(input())
S = lambda : input()
r = range
n = IN()
a = [0] * n
tot = 0
for i in range(n):
	(aa, bb) = LI()
	a[i] = [bb, aa]
	tot += aa
a.sort()
bought = 0
bill = 0
for item in a:
	if item[0] > bought:
		qntt = min(tot - bought, item[0] - bought)
		bought += qntt
		bill += qntt * 2
	qntt = min(tot - bought, item[1])
	bought += qntt
	bill += qntt
print(bill)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import ceil

def prod(a, mod=10 ** 9 + 7):
	ans = 1
	for each in a:
		ans = ans * each % mod
	return ans

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
	n = int(input())
	pairs = []
	for i in range(n):
		(a, b) = map(int, input().split())
		pairs += [[a, b]]
	pairs = sorted(pairs, key=lambda x: (x[1], x[0]))
	(i, j) = (0, n - 1)
	current = 0
	ans = 0
	while i <= j:
		if current >= pairs[i][1]:
			ans += pairs[i][0]
			current += pairs[i][0]
			pairs[i][0] = 0
			i += 1
			continue
		req = max(0, min(pairs[j][1] - current, pairs[i][1] - current))
		req = min(req, pairs[j][0])
		pairs[j][0] -= req
		current += req
		if pairs[j][0] == 0:
			j -= 1
		ans += 2 * req
	print(ans)


def func():
	n = int(input())
	arr = []
	for _ in range(n):
		(a, b) = map(int, input().split())
		arr.append([a, b])
	arr.sort(key=lambda x: x[1])
	cur_prod = 0
	ans = 0
	i = 0
	j = n - 1
	while i <= j:
		while arr[i][1] > cur_prod and arr[i][0] > 0:
			diff = arr[i][1] - cur_prod
			d = max(arr[j][0] - diff, 0)
			ans += (arr[j][0] - d) * 2
			cur_prod += arr[j][0] - d
			arr[j][0] = d
			if d == 0:
				j -= 1
		cur_prod += arr[i][0]
		ans += arr[i][0]
		i += 1
	print(ans)
for _ in range(1):
	func()


from collections import defaultdict
for tt in range(1):
	n = int(input())
	ans = 0
	arr = []
	for i in range(n):
		(x, y) = map(int, input().split())
		arr.append([x, y])
		ans += 2 * arr[i][0]
	arr.sort(key=lambda x: x[1], reverse=True)
	i = 0
	j = n - 1
	curr = 0
	while i <= j:
		tar = arr[j][1]
		if i == j:
			tem1 = arr[i][0]
			tem2 = max(0, arr[i][1] - curr)
			tem1 = max(0, tem1 - tem2)
			ans -= tem1
			break
		elif curr >= tar:
			curr += arr[j][0]
			ans -= arr[j][0]
			j -= 1
		elif curr + arr[i][0] <= arr[j][1]:
			curr += arr[i][0]
			arr[i][0] = 0
			i += 1
		else:
			tem2 = arr[j][1] - curr
			curr += tem2
			curr += arr[j][0]
			arr[i][0] -= tem2
			ans -= arr[j][0]
			j -= 1
	print(ans)


def answer():
	(s, ans) = (0, 0)
	a.sort(key=lambda x: x[1], reverse=True)
	(i, j) = (0, n - 1)
	while i <= j:
		if a[j][1] >= s + a[i][0]:
			ans += 2 * a[i][0]
			s += a[i][0]
			i += 1
		else:
			a[i][0] -= max(0, a[j][1] - s)
			ans += 2 * max(0, a[j][1] - s)
			s += max(0, a[j][1] - s)
			ans += a[j][0]
			s += a[j][0]
			j -= 1
	return ans
n = int(input())
a = []
for i in range(n):
	(p, q) = map(int, input().split())
	a.append([p, q])
print(answer())


from collections import deque
import heapq
from math import sqrt
import operator
from operator import itemgetter
import sys
inf_var = 0
if inf_var == 1:
	inf = open('input.txt', 'r')
else:
	inf = sys.stdin
input = inf.readline

def read_one_int():
	return int(input().rstrip('\n'))

def read_one_float():
	return float(input().rstrip('\n'))

def read_list_of_ints():
	res = [int(val) for val in input().rstrip('\n').split(' ')]
	return res

def read_str():
	return input().rstrip()

def main():
	n = read_one_int()
	need_disc = []
	for _ in range(n):
		(need_cnt, disc_cnt) = read_list_of_ints()
		need_disc.append((disc_cnt, need_cnt))
	need_disc.sort()
	res = 0
	l = 0
	r = n - 1
	bought = 0
	left_max_need = 0
	while l <= r:
		(cur_min_disc, cur_need) = need_disc[l]
		if l == r:
			if left_max_need:
				cur_need = left_max_need
			if bought + cur_need < cur_min_disc:
				res += 2 * cur_need
				break
			if cur_min_disc <= bought:
				res += cur_need
				break
			res += 2 * (cur_min_disc - bought)
			res += cur_need + bought - cur_min_disc
			break
		if bought >= cur_min_disc:
			res += cur_need
			bought += cur_need
			l += 1
			continue
		if not left_max_need:
			(cur_max_disc, cur_max_need) = need_disc[r]
		else:
			cur_max_need = left_max_need
		if bought + cur_max_need < cur_min_disc:
			r -= 1
			res += 2 * cur_max_need
			bought += cur_max_need
			left_max_need = 0
			continue
		l += 1
		res += 2 * (cur_min_disc - bought)
		left_max_need = bought + cur_max_need - cur_min_disc
		res += cur_need
		bought += cur_need + cur_min_disc - bought
		if not left_max_need:
			r -= 1
	print(res)
main()


n = int(input())
arr = []
for i in range(n):
	(a, b) = map(int, input().split())
	arr.append([b, a])
arr.sort()
last = -1
ans = 0
prod = 0
for i in range(n):
	if arr[i][0] > prod:
		while last >= -n and prod < arr[i][0]:
			if prod + arr[last][1] <= arr[i][0]:
				prod += arr[last][1]
				ans += arr[last][1] * 2
				arr[last][1] = 0
				last -= 1
			else:
				needed = arr[i][0] - prod
				arr[last][1] -= needed
				prod += needed
				ans += needed * 2
		if prod >= arr[i][0]:
			prod += arr[i][1]
			ans += arr[i][1]
			arr[i][1] = 0
		else:
			prod += arr[i][1] * 2
			ans += arr[i][1] * 2
			arr[i][1] = 0
	else:
		prod += arr[i][1]
		ans += arr[i][1]
		arr[i][1] = 0
print(ans)


n = int(input())
l = []
for i in range(n):
	(x, y) = map(int, input().split())
	l.append([x, y])
l.sort(key=lambda l: l[1])
i = 0
j = n - 1
ans = 0
x = 0
while i <= j:
	if x >= l[i][1]:
		ans += l[i][0]
		x += l[i][0]
		i += 1
	elif x + l[j][0] <= l[i][1]:
		ans += 2 * l[j][0]
		x += l[j][0]
		j -= 1
	else:
		l[j][0] -= l[i][1] - x
		ans += 2 * (l[i][1] - x)
		x += l[i][1] - x
print(ans)


import sys
from sys import stdout
import io, os
input = lambda : sys.stdin.readline().strip()
P = lambda : list(map(int, input().split()))
from math import factorial as f, gcd
from collections import deque, defaultdict as dd, Counter as C
from heapq import heapify, heappop, heappush, heappushpop, heapreplace, merge
from random import randint, choice, sample
import time
mod = 10 ** 9 + 7
a = ord('a')
start = time.time()

def fast_exp(x, exp):
	ans = 1
	base = x
	while exp:
		if exp & 1:
			ans *= base
		base *= base
		base %= mod
		ans %= mod
		exp >>= 1
	return ans

def countBits(n):
	count = 0
	while n:
		count += n & 1
		n >>= 1
	return count

def submasks(n):
	org = n
	while n:
		yield n
		n = n - 1 & org

def buy(x, disc, curr):
	if curr >= disc:
		return x
	else:
		y = min(disc - curr, x)
		return x + y

def solve():
	n = int(input())
	arr = [P() for _ in range(n)]
	arr.sort(key=lambda i: i[1])
	s = 0
	e = n - 1
	ans = 0
	count = 0
	while s <= e:
		if s == e:
			ans += buy(arr[s][0], arr[s][1], count)
			break
		elif arr[s][1] <= count:
			ans += buy(arr[s][0], arr[s][1], count)
			count += arr[s][0]
			s += 1
		else:
			togetdisc = max(arr[s][1] - count, 0)
			if arr[e][0] >= togetdisc:
				ans += buy(togetdisc, arr[e][1], count)
				count += togetdisc
				arr[e][0] -= togetdisc
				ans += buy(arr[s][0], arr[s][1], count)
				count += arr[s][0]
				s += 1
			else:
				ans += buy(arr[e][0], arr[e][1], count)
				count += arr[e][0]
				e -= 1
	print(ans)
solve()


import math
import re
n = int(input())
a = []
for i in range(0, n):
	(a1, b1) = [int(x) for x in input().split()]
	a.append([a1, b1])
a.sort(key=lambda x: x[1])
min_b = a[-1][1]
min_b = 0
i = n - 1
j = 0
co_b = 0
while j <= i:
	while j <= i and co_b >= a[j][1]:
		min_b += a[j][0]
		co_b += a[j][0]
		a[j][0] = 0
		j = j + 1
	if a[i][0] > 0:
		if co_b >= a[i][1]:
			min_b += a[i][0]
			co_b += a[i][0]
		else:
			d = a[j][1] - co_b
			if a[i][0] - d >= 0:
				min_b += 2 * d
				a[i][0] -= d
				co_b += d
			else:
				min_b += 2 * a[i][0]
				co_b += a[i][0]
				a[i][0] = 0
		if a[i][0] == 0:
			i = i - 1
print(min_b)


n = int(input())
items = []
needed = 0
for i in range(n):
	x = input().split()
	items.append([int(x[1]), int(x[0])])
	needed += int(x[0])
items.sort()
l = 0
r = n - 1
total = 0
spent = 0
while total < needed:
	if items[l][0] <= total:
		cur = items[l][1]
		total += cur
		spent += cur
		l += 1
	else:
		if l == r and items[r][0] < needed:
			taking1 = needed - items[r][0]
			taking2 = items[r][0] - total
			spent += taking2 * 2 + taking1
			items[r][1] -= taking1 + taking2
			total += taking1 + taking2
			r -= 1
			continue
		taking = min(items[l][0] - total, items[r][1])
		items[r][1] -= taking
		spent += 2 * taking
		total += taking
		if items[r][1] == 0:
			r -= 1
print(spent)


from collections import defaultdict, Counter
from queue import PriorityQueue, Queue
import math
n = int(input())
a = sorted(list((list(map(int, input().split()))[::-1] for i in range(n))))
ans = 0
i = 0
j = n - 1
p = 0
while i <= j:
	if p < a[i][0]:
		while j > i:
			if a[j][1] > a[i][0] - p:
				a[j][1] -= a[i][0] - p
				ans += (a[i][0] - p) * 2
				p = a[i][0]
				break
			p += a[j][1]
			ans += a[j][1] * 2
			j -= 1
		if j == i:
			x = min(a[j][1], max(0, a[j][0] - p))
			ans += 2 * x
			ans += a[j][1] - x
			break
		ans += a[i][1]
		p += a[i][1]
		i += 1
	else:
		ans += a[i][1]
		p += a[i][1]
		i += 1
print(ans)


import sys
input = sys.stdin.buffer.readline
N = int(input())
A = [0] * N
B = [0] * N
for i in range(N):
	(A[i], B[i]) = map(int, input().split())
indices = list(range(N))
indices.sort(key=lambda i: B[i])
low = 0
high = N - 1
bought = 0
cost = 0
while low <= high:
	l = indices[low]
	h = indices[high]
	if bought >= B[l]:
		bought += A[l]
		cost += A[l]
		A[l] = 0
		low += 1
	else:
		buy = min(B[l] - bought, A[h])
		bought += buy
		A[h] -= buy
		cost += 2 * buy
		if A[h] == 0:
			high -= 1
assert sum(A) == 0
print(cost)


n = int(input())
s = 0
x = []
for _ in range(n):
	(a, b) = map(int, input().split())
	s += a
	x.append([a, b])
x.sort(key=lambda x: x[1])
cnt = 0
cur = 0
for (a, b) in x:
	if cur < b:
		cur = b
	if b >= s:
		break
	if s - cur >= a:
		cnt += a
		cur += a
	else:
		cnt += s - cur
		break
print(2 * s - cnt)


from sys import stdin as inp
from math import gcd, sqrt, floor, ceil, log2
n = int(inp.readline())
arr = []
v = []
for _ in range(n):
	(a, b) = map(int, inp.readline().split())
	arr.append([a, b])
arr = sorted(arr, key=lambda x: x[1], reverse=True)
ans = 0
ele = 0
i = 0
j = n - 1
while i <= j:
	if i == j:
		if ele >= arr[i][1]:
			ans += arr[i][0]
			ele += arr[i][0]
			i += 1
			j -= 1
		else:
			arr[i][1] -= ele
			if arr[i][0] >= arr[i][1]:
				ans += 2 * arr[i][1] + (arr[i][0] - arr[i][1])
			else:
				ans += 2 * arr[i][0]
			i += 1
			j -= 1
	elif ele >= arr[i][1]:
		ans += arr[i][0]
		ele += arr[i][0]
		i += 1
	elif ele >= arr[j][1]:
		ans += arr[j][0]
		ele += arr[j][0]
		j -= 1
	else:
		x = min(arr[i][0], arr[j][1] - ele)
		ans += x * 2
		ele += x
		arr[i][0] -= x
		if arr[i][0] == 0:
			i += 1
print(ans)


from __future__ import division, print_function
import os
import sys
from collections import defaultdict
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def main():
	n = int(input())
	need = defaultdict(int)
	for _ in range(n):
		(a, b) = map(int, input().split())
		need[b] += a
	b = sorted(need.keys())
	(l, r) = (0, len(b) - 1)
	curr = 0
	cost = 0
	while l < r:
		if b[l] <= curr:
			curr += need[b[l]]
			cost += need[b[l]]
			need[b[l]] = 0
			l += 1
		while b[l] > curr and l < r:
			amt = min(b[l] - curr, need[b[r]])
			curr += amt
			cost += 2 * amt
			need[b[r]] -= amt
			r -= need[b[r]] == 0
	if need[b[r]]:
		full = min(need[b[r]], max(0, b[r] - curr))
		cost += full * 2 + (need[b[r]] - full)
	print(cost)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from operator import itemgetter

def solve(A, B):
	buy = 0
	cost = 0
	l = []
	for i in range(len(A)):
		l.append([A[i], B[i]])
	t = sorted(l, key=itemgetter(1))
	i = len(t) - 1
	j = 0
	while i > j:
		if buy < t[j][1]:
			if t[i][0] - t[j][1] + buy >= 0:
				cost += 2 * (t[j][1] - buy) + t[j][0]
				t[i][0] += buy - t[j][1]
				buy += t[j][1] - buy + t[j][0]
				j += 1
			else:
				buy += t[i][0]
				cost += 2 * t[i][0]
				i += -1
		elif buy >= t[j][1]:
			buy += t[j][0]
			cost += t[j][0]
			j += 1
	if buy > t[i][1]:
		cost += t[i][0]
	elif t[i][0] > 0 and t[i][1] - buy > t[i][0]:
		cost += 2 * t[i][0]
	elif t[i][0] > 0 and t[i][1] - buy <= t[i][0]:
		cost += t[i][1] - buy + t[i][0]
	return cost
n = int(input())
A = []
B = []
for i in range(n):
	t = list(map(int, input().strip().split()))
	A.append(t[0])
	B.append(t[1])
print(solve(A, B))


import sys
from collections import Counter
INP = lambda : sys.stdin.readline().strip()
INT = lambda : int(INP())
MAP = lambda : map(int, INP().split())
ARR = lambda : [int(i) for i in INP().split()]

def JOIN(arr, x=' '):
	return x.join([str(i) for i in arr])

def EXIT(x='NO'):
	print(x)
	exit()
arr = []
t = 0
n = INT()
for _ in range(n):
	(a, b) = MAP()
	arr.append([a, b])
	t += a
arr = sorted(arr, key=lambda x: x[1], reverse=True)
c = 0
d = 0
(l, r) = (0, n - 1)
while l <= r:
	(ra, rb) = arr[r]
	(la, lb) = arr[l]
	if c >= rb:
		c += ra
		r -= 1
		continue
	wanted = rb - c
	if la <= wanted:
		c += la
		d += la
		l += 1
		continue
	if la > wanted:
		c += wanted
		d += wanted
		arr[l][0] -= wanted
print(c + d)


import sys
import math
import collections
import heapq
import decimal
input = sys.stdin.readline
n = int(input())
l = []
for i in range(n):
	(a, b) = (int(i) for i in input().split())
	l.append((b, a))
l.sort()
s = 0
for i in range(n):
	s += l[i][1]
ans = s * 2
for i in range(n - 1, -1, -1):
	k = s - l[i][0]
	ans -= max(min(k, l[i][1]), 0)
	s -= max(min(k, l[i][1]), 0)
print(ans)


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from bisect import insort
from collections import Counter
from collections import deque
from heapq import heappush, heappop, heapify
from itertools import permutations, combinations
from itertools import accumulate as ac
from random import randint as ri
mod = int(1000000000.0) + 7
ip = lambda : int(stdin.readline())
inp = lambda : map(int, stdin.readline().split())
ips = lambda : stdin.readline().rstrip()
out = lambda x: stdout.write(str(x) + '\n')
t = 1
for _ in range(t):
	n = ip()
	arr = []
	for i in range(n):
		(a, b) = inp()
		arr.append([b, a])
	arr.sort()
	nn = len(arr)
	arr = deque(arr)
	ans = 0
	item = 0
	st = 0
	end = 0
	while nn != 0:
		if nn == 1:
			ele = arr[0]
			(b, a) = ele
			if item >= b:
				ans += a
				arr.pop()
				nn -= 1
			else:
				diff = b - item
				if a >= diff:
					ans += diff * 2
					item += diff
					a -= diff
					arr[0] = [b, a]
				else:
					ans += a * 2
					item += a
					arr.pop()
					nn -= 1
		else:
			small = arr[0]
			big = arr[-1]
			(b_small, a_small) = small
			(b_big, a_big) = big
			if item >= b_small:
				ans += a_small
				item += a_small
				arr.popleft()
				nn -= 1
			else:
				diff = b_small - item
				if a_big >= diff:
					a_big -= diff
					item += diff
					ans += diff * 2
					arr[-1] = [b_big, a_big]
				else:
					item += a_big
					ans += a_big * 2
					arr.pop()
					nn -= 1
	print(ans)


R = lambda : map(int, input().split())
n = int(input())
arr = sorted([list(R()) for i in range(n)], key=lambda x: x[1], reverse=True)
rem = tot = sum((x[0] for x in arr))
cnt = 0
for item in arr:
	discnt = max(0, min(item[0], rem - item[1]))
	cnt += discnt
	rem -= discnt
print(2 * tot - cnt)


p = int(input())
arr = []
for product in range(p):
	(a, b) = map(int, input().split())
	arr.append([a, b])
arr.sort(key=lambda x: x[1])
l = 0
r = p - 1
c = 0
total = 0
while l <= r:
	if arr[l][1] <= c:
		c += arr[l][0]
		total += arr[l][0]
		l += 1
	else:
		need = arr[l][1] - c
		if need < arr[r][0]:
			c += need
			total += need * 2
			arr[r][0] -= need
		else:
			c += arr[r][0]
			total += arr[r][0] * 2
			arr[r][0] = 0
			r -= 1
print(total)


n = int(input())
arr = []
for _ in range(n):
	arr.append(list(map(int, input().split())))
arr.sort(key=lambda x: x[1])
(lo, hi) = (0, n - 1)
(ans, counter) = (0, 0)
while lo <= hi:
	(to_buy, req) = arr[lo]
	if counter >= req or to_buy == 0:
		counter += to_buy
		ans += to_buy
		lo += 1
	else:
		(a, b) = arr[hi]
		temp = min(a, req - counter)
		counter += temp
		ans += temp * 2
		arr[hi][0] -= temp
		if arr[hi][0] == 0:
			hi -= 1
print(ans)


import sys
from collections import deque
from time import perf_counter
start = perf_counter()
input = sys.stdin.readline
n = int(input())
a = [0] * n
b = [0] * n
for i in range(n):
	(aa, bb) = map(int, input().split())
	a[i] = aa
	b[i] = bb
total_items = sum(a)
bad_items = 0
for i in range(n):
	bad = a[i] - max(min(total_items - b[i], a[i]), 0)
	a[i] -= bad
	bad_items += bad
possible_indices = sorted([[b[i], a[i]] for i in range(n) if a[i]])
pointer = len(possible_indices) - 1
fpointer = 0
cost = 2 * total_items
currently_picked = bad_items
while pointer >= fpointer:
	while pointer >= fpointer and currently_picked < possible_indices[fpointer][0]:
		take = min(possible_indices[fpointer][0] - currently_picked, possible_indices[pointer][1])
		possible_indices[pointer][1] -= take
		if possible_indices[pointer][1] == 0:
			pointer -= 1
		currently_picked += take
	if pointer >= fpointer:
		discount = possible_indices[fpointer][1]
		cost -= discount
		currently_picked += discount
		fpointer += 1
print(cost)
print(perf_counter() - start, file=sys.stderr)


n = int(input())
arr = []
for w in range(n):
	inp = input().split()
	arr.append([int(inp[0]), int(inp[1])])
arr.sort(key=lambda x: x[1])
answer = 0
count = 0
i = 0
j = len(arr) - 1
while i <= j:
	if arr[i][1] <= count:
		count += arr[i][0]
		i += 1
	elif arr[j][0] + count <= arr[i][1]:
		answer += arr[j][0]
		count += arr[j][0]
		j -= 1
	else:
		arr[j][0] -= arr[i][1] - count
		answer += arr[i][1] - count
		count = arr[i][1]
print(answer + count)


n = int(input())
a = []
for i in range(n):
	(q, w) = [int(i) for i in input().split()]
	a.append([q, w])
a.sort(key=lambda x: x[1])
s = 0
for i in range(n):
	s += a[i][0]
M = 0
N = 0
i = 0
while M + N < s:
	if M + N < a[i][1]:
		N += min(a[i][1] - N - M, s - N - M)
	if M + N < s - a[i][0]:
		M += a[i][0]
	else:
		M += s - (N + M)
	i += 1
print(2 * N + M)


import sys
input = sys.stdin.readline

def solve():
	n = int(input())
	a = [tuple(reversed(tuple(map(int, input().split())))) for i in range(n)]
	a.sort()
	b = [0] * n
	have = 0
	j = len(a) - 1
	r = 0
	for i in range(len(a)):
		(c, d) = a[i]
		while c > have and j > i:
			if b[j] < a[j][1]:
				w = min(c - have, a[j][1] - b[j])
				r += w * 2
				have += w
				b[j] += w
			else:
				j -= 1
		if c <= have:
			w = d - b[i]
			b[i] += w
			have += w
			r += w
		else:
			w = c - have
			if w + b[i] <= d:
				b[i] += w
				r += w * 2
				have += w
				w = d - b[i]
				b[i] += w
				r += w
				have += w
			else:
				w = d - b[i]
				b[i] += w
				r += w * 2
				have += w
	print(r)
solve()


n = int(input())
lists = []
for i in range(n):
	(a, req) = list(map(int, input().split()))
	lists.append([a, req])

def last(n):
	return n[1]
qua = sorted(lists, key=last)
low = 0
high = n - 1
ans = 0
bought = 0
while low <= high:
	if qua[low][-1] <= bought:
		ans += qua[low][0]
		bought += qua[low][0]
		low += 1
	else:
		req = min(qua[low][-1] - bought, qua[high][0])
		bought += req
		ans += 2 * req
		qua[high][0] -= req
		if qua[high][0] == 0:
			high -= 1
print(ans)


import sys
import math
import random
from queue import PriorityQueue as PQ
from bisect import bisect_left as BSL
from bisect import bisect_right as BSR
from collections import OrderedDict as OD
from collections import Counter
from itertools import permutations
from decimal import Decimal as BIGFLOAT
from copy import deepcopy
mod = 1000000007
MOD = mod
sys.setrecursionlimit(1000000)
try:
	sys.stdin = open('actext.txt', 'r')
	OPENFILE = 1
except:
	pass

def get_ints():
	return map(int, input().split())

def palindrome(s):
	mid = len(s) // 2
	for i in range(mid):
		if s[i] != s[len(s) - i - 1]:
			return False
	return True

def check(i, n):
	if 0 <= i < n:
		return True
	else:
		return False

def second(arr, n, sm):
	i = 0
	j = len(arr) - 1
	costly = 0
	curr_prod = 0
	while i <= j:
		while i < j and curr_prod < arr[i][0]:
			if arr[i][0] - curr_prod < arr[j][1]:
				prev = curr_prod
				curr_prod += arr[i][0] - curr_prod
				costly += arr[i][0] - prev
				arr[j][1] -= arr[i][0] - prev
			else:
				curr_prod += arr[j][1]
				costly += arr[j][1]
				j -= 1
		if i == j:
			if -curr_prod + arr[i][0] > 0:
				costly += min(-curr_prod + arr[i][0], arr[i][1])
				arr[i][1] -= -curr_prod + arr[i][0]
			curr_prod += min(0, arr[i][1])
			j -= 1
		else:
			curr_prod += arr[i][1]
		i += 1
	print(costly * 2 + sm - costly)
n = int(input())
arr = []
sm = 0
for i in range(n):
	(a, b) = map(int, input().split())
	arr.append([b, a])
	sm += a
arr.sort()
second(arr, n, sm)


n = int(input())
a = []
for i in range(n):
	temp = [int(x) for x in input().split()]
	a.append(temp)
a = sorted(a, key=lambda x: x[1])
rubels = 0
xp = 0
i = 0
j = n - 1
while i < j:
	if a[j][1] <= xp or a[j][0] == 0:
		xp += a[j][0]
		rubels += a[j][0]
		j -= 1
	elif a[i][1] <= xp:
		xp += a[i][0]
		rubels += a[i][0]
		i += 1
	else:
		required = a[i][1] - xp
		purchase = min(required, a[j][0])
		xp += purchase
		rubels += 2 * purchase
		a[j][0] -= purchase
if a[i][1] <= xp:
	xp += a[i][0]
	rubels += a[i][0]
else:
	required = a[i][1] - xp
	purchase = min(required, a[j][0])
	xp += purchase
	rubels += 2 * purchase
	a[i][0] -= purchase
	if a[i][0] > 0:
		rubels += a[i][0]
		xp += a[i][0]
print(rubels)


n = int(input())
arr = []
for i in range(n):
	(a, b) = map(int, input().split())
	arr.append([b, a])
arr.sort()
l = 0
r = n - 1
c = 0
s = 0
while l <= r:
	if arr[l][0] <= c:
		c += arr[l][1]
		s += arr[l][1]
		l += 1
	else:
		need = arr[l][0]
		if need - c < arr[r][1]:
			q = need - c
			c += q
			s += q * 2
			arr[r][1] -= q
		else:
			c += arr[r][1]
			s += arr[r][1] * 2
			r -= 1
print(s)


import sys
import bisect
from collections import deque
import itertools
from sys import stdin
readline = stdin.readline
sr = lambda : readline()
ir = lambda : int(sr())
lr = lambda : list(map(int, sr().split()))
inf = 10 ** 18
mod = 10 ** 9 + 7
n = ir()
ab = [lr() for i in range(n)]
ab.sort(key=lambda x: x[1])
l_ind = 0
r_ind = n - 1
now_limit = ab[r_ind][1]
nums = 0
flg = True
ans = 0
while flg:
	if ab[r_ind][1] <= nums:
		for i in range(l_ind, r_ind + 1):
			ans += ab[i][0]
			ab[i][0] = 0
		break
	if ab[l_ind][1] <= nums:
		ans += ab[l_ind][0]
		nums += ab[l_ind][0]
		ab[l_ind][0] = 0
		l_ind += 1
		if l_ind > r_ind:
			break
		continue
	if ab[l_ind][1] <= ab[r_ind][0] + nums:
		ab[r_ind][0] -= ab[l_ind][1] - nums
		ans += 2 * (ab[l_ind][1] - nums)
		if ab[r_ind][0] == 0:
			r_ind -= 1
		nums = ab[l_ind][1]
		if l_ind > r_ind:
			break
		continue
	if ab[l_ind][1] > ab[r_ind][0] + nums:
		ans += 2 * ab[r_ind][0]
		nums += ab[r_ind][0]
		ab[r_ind][0] = 0
		r_ind -= 1
		if l_ind > r_ind:
			break
		continue
print(ans)


import sys
import math
from collections import *
from queue import *
from bisect import *
MOD = int(1000000000.0 + 7)
inf = float('inf')
ninf = float('-inf')
input = sys.stdin.readline

def ii():
	return list(map(int, input().strip().split()))
(n,) = ii()
d = defaultdict(int)
for _ in range(n):
	(a, b) = ii()
	d[b] += a
arr = list(d.keys())
arr.sort()
(i, j) = (0, len(arr) - 1)
(cnt, vl) = (0, 0)
while i <= j:
	if cnt < arr[i]:
		mm = min(d[arr[j]], arr[i] - cnt)
		vl += 2 * mm
		cnt += mm
		d[arr[j]] -= mm
		if d[arr[j]] == 0:
			j -= 1
	else:
		cnt += d[arr[i]]
		vl += d[arr[i]]
		d[arr[i]] = 0
		i += 1
print(vl)


from sys import stdin, stdout
n = int(stdin.readline())
products = []
for _ in range(n):
	products.append([int(x) for x in stdin.readline().split()])
products.sort(key=lambda x: x[1], reverse=True)
answer = 0
volume = 0
front_pointer = 0
back_pointer = n - 1
while front_pointer < back_pointer:
	if volume + products[front_pointer][0] >= products[back_pointer][1]:
		gap = max(0, products[back_pointer][1] - volume)
		products[front_pointer][0] -= gap
		answer += gap * 2 + products[back_pointer][0]
		volume += gap + products[back_pointer][0]
		back_pointer -= 1
	else:
		answer += products[front_pointer][0] * 2
		volume += products[front_pointer][0]
		front_pointer += 1
if volume + products[front_pointer][0] >= products[back_pointer][1]:
	gap = max(0, products[back_pointer][1] - volume)
	answer += gap * 2 + products[front_pointer][0] - gap
else:
	answer += products[front_pointer][0] * 2
stdout.write(str(answer) + '\n')


n = int(input())
m = []
for i in range(n):
	a = list(map(int, input().split()))
	m.append([a[1], a[0]])
m.sort()
x = 0
for i in range(n):
	x += m[i][1]
ans = x * 2
for i in range(n - 1, -1, -1):
	y = x - m[i][0]
	if y >= m[i][1]:
		ans -= m[i][1]
		x -= m[i][1]
	elif y > 0:
		ans -= y
		x -= y
print(ans)


from sys import stdin, stdout
from math import gcd, sqrt, factorial, pi, inf
from collections import deque, defaultdict
from bisect import bisect, bisect_left
from time import time
from itertools import permutations as per
from heapq import heapify, heappush, heappop, heappushpop
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\r\n')
L = lambda : list(R())
P = lambda x: stdout.write(str(x) + '\n')
lcm = lambda x, y: x * y // gcd(x, y)
nCr = lambda x, y: f[x] * inv(f[y] * f[x - y] % N) % N
inv = lambda x: pow(x, N - 2, N)
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7
n = I()
v = []
st = 0
sl = 0
ans = 0
for i in range(n):
	(x, y) = R()
	ans += x * 2
	st += x
	v += ([x, y],)
v.sort(key=lambda x: x[1])
z = st
for i in range(n):
	v[i][0] = min(st, v[i][0])
	v[i][0] = max(0, min(v[i][0], st + sl - v[i][1]))
	ans -= v[i][0]
	sl = max(sl + v[i][0], v[i][0] + v[i][1])
	st = z - sl
print(ans)


import os
import sys
from io import BytesIO, IOBase

def main():
	n = int(input())
	minamount_prices = []
	for _ in range(n):
		(a, b) = map(int, input().split(' '))
		minamount_prices.append([a, b])
	minamount_prices.sort(key=lambda x: x[1])
	cur = 0
	low = 0
	high = n - 1
	ans = 0
	while low <= high:
		while low < high and minamount_prices[high][0] + cur >= minamount_prices[low][1]:
			ans += minamount_prices[low][0] + max(0, (minamount_prices[low][1] - cur) * 2)
			minamount_prices[high][0] -= max(0, minamount_prices[low][1] - cur)
			cur += minamount_prices[low][0] + max(0, minamount_prices[low][1] - cur)
			low += 1
		temp = minamount_prices[high][0]
		if cur + minamount_prices[high][0] < minamount_prices[high][1]:
			ans += minamount_prices[high][0] * 2
		else:
			ans += max(0, (minamount_prices[high][1] - cur) * 2)
			minamount_prices[high][0] -= max(0, minamount_prices[high][1] - cur)
			ans += minamount_prices[high][0]
		cur += temp
		high -= 1
	print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from collections import Counter
from collections import defaultdict as dfd
from bisect import bisect, bisect_left
from math import sqrt, gcd, ceil, factorial
from heapq import heapify, heappush, heappop
MOD = 10 ** 9 + 7
inf = float('inf')
ans_ = []

def nin():
	return int(input())

def ninf():
	return int(file.readline())

def st():
	return input().strip()

def stf():
	return file.readline().strip()

def read():
	return list(map(int, input().strip().split()))

def readf():
	return list(map(int, file.readline().strip().split()))

def solve():
	n = nin()
	arr = [read() for i in range(n)]
	arr.sort(key=lambda x: x[1])
	s = 0
	for i in arr:
		s += i[0]
	ans = 0
	b = 0
	for i in arr:
		if i[1] > b:
			ans += min(s - b, i[1] - b) * 2
			b += min(s - b, i[1] - b)
		ans += min(s - b, i[0])
		b += min(s - b, i[0])
	ans_.append(ans)
solve()
for i in ans_:
	print(i)


n = int(input())
ab = []
for _ in range(n):
	(a, b) = map(int, input().split())
	ab.append([a, b])
ab = sorted(ab, key=lambda c: c[1])
total = sum([c[0] for c in ab])
answer = 0
cnt = 0
i = 0
j = n - 1
while cnt < total:
	if cnt >= ab[i][1]:
		cnt += ab[i][0]
		answer += ab[i][0]
		ab[i][0] = 0
		i += 1
	else:
		q = min(ab[i][1] - cnt, ab[j][0])
		cnt += q
		answer += q * 2
		ab[j][0] -= q
		if ab[j][0] == 0:
			j -= 1
print(answer)


arr = []
for _ in range(int(input())):
	arr.append(list(map(int, input().split())))
arr = sorted(arr, key=lambda x: x[1], reverse=True)
p = 0
c = 0
i = 0
j = len(arr) - 1
while i <= j:
	need = arr[j][1]
	if need <= c:
		p += arr[j][0]
		c += arr[j][0]
		j -= 1
		continue
	diff = need - c
	ext = arr[i][0]
	if ext <= diff:
		p += ext * 2
		c += ext
		i += 1
	elif ext > diff:
		arr[i][0] -= diff
		p += diff * 2
		c += diff
print(p)


try:
	n = int(input())
	arr = []
	total = 0
	for _ in range(n):
		tuples = list(map(int, input().split()))
		total += tuples[0]
		arr.append(tuples)
	arr = list(reversed(sorted(arr, key=lambda item: (item[1], -item[0]))))
	buy = 0
	cost = 0
	left = 0
	right = n - 1
	while left <= right:
		if buy + arr[left][0] < arr[right][1]:
			buy += arr[left][0]
			cost += 2 * arr[left][0]
			arr[left][0] = 0
			left += 1
		else:
			temp = max(arr[right][1] - buy, 0)
			another_temp = arr[left][0]
			arr[left][0] -= temp
			buy += temp
			cost += 2 * temp
			buy += arr[right][0]
			cost += arr[right][0]
			arr[right][0] = 0
			right -= 1
			if temp == another_temp:
				left += 1
	print(cost)
except e:
	pass


for u in range(1):
	n = int(input())
	ans = 0
	x = []
	for i in range(n):
		(a, b) = map(int, input().split())
		x.append([a, b])
		ans += 2 * a
	x = sorted(x, key=lambda y: y[1])
	x = x[::-1]
	i = 0
	j = n - 1
	k = 0
	while i <= j:
		temp = x[j][1]
		if i == j:
			a = x[i][0]
			b = max(0, x[i][1] - k)
			a = max(0, a - b)
			ans -= a
			break
		elif k >= temp:
			k += x[j][0]
			ans -= x[j][0]
			j -= 1
		elif k + x[i][0] <= x[j][1]:
			k += x[i][0]
			x[i][0] = 0
			i += 1
		else:
			b = x[j][1] - k
			k += b
			k += x[j][0]
			x[i][0] -= b
			ans -= x[j][0]
			j -= 1
	print(ans)


from collections import deque

def solve(N, arr):
	arr.sort(reverse=True)
	arr = deque(arr)
	cost = 0
	cnt = 0
	while arr:
		if cnt >= arr[-1][0]:
			(b, a) = arr.pop()
			cnt += a
			cost += a
		else:
			aa = min(arr[0][1], arr[-1][0] - cnt)
			arr[0][1] -= aa
			cnt += aa
			cost += aa << 1
			if arr[0][1] == 0:
				arr.popleft()
	return cost
N = int(input())
arr = []
for n in range(N):
	(a, b) = tuple(map(int, input().split()))
	arr.append([b, a])
print(solve(N, arr))


import sys
input = sys.stdin.readline
n = int(input())
a = []
b = 0
for _ in range(n):
	(c, d) = map(int, input().split())
	a.append((c, d))
	b += c
a.sort(key=lambda x: x[1])
aa = [a[0]]
for i in range(1, n):
	if a[i][1] == a[i - 1][1]:
		aa[-1] = (aa[-1][0] + a[i][0], a[i][1])
	else:
		aa.append(a[i])
e = 0
f = 0
for i in range(n):
	if a[i][1] <= e:
		e += a[i][0]
		f += a[i][0]
		if e > b:
			f -= e - b
			break
	elif a[i][1] < b:
		f += (a[i][1] - e) * 2
		e += a[i][1] - e
		if e > b:
			f -= (e - b) * 2
			break
		e += a[i][0]
		f += a[i][0]
		if e > b:
			f -= e - b
			break
	else:
		f += a[i][0] * 2
		e += a[i][0]
		if e > b:
			f -= (e - b) * 2
			break
print(f)


import sys
t = int(sys.stdin.readline())
li = []
for _ in range(t):
	(a, b) = map(int, sys.stdin.readline().split())
	li.append([a, b])
li.sort(key=lambda x: x[1])
(l, r) = (0, len(li) - 1)
n = 0
ans = 0
while l <= r:
	if li[l][1] <= n:
		n += li[l][0]
		ans += li[l][0]
		l += 1
	else:
		while r >= l:
			if li[l][1] > li[r][0] + n:
				n += li[r][0]
				ans += li[r][0] * 2
				r -= 1
			else:
				ans += (li[l][1] - n) * 2
				k = li[l][1] - n
				n += k
				li[r][0] -= k
				break
print(ans)


from sys import stdin, stdout
stdin.readline

def mp():
	return list(map(int, stdin.readline().strip().split()))

def it():
	return int(stdin.readline().strip())
from collections import defaultdict as dd, Counter as C, deque
from math import ceil, gcd, sqrt, factorial, log2, floor
import heapq
n = it()
v = []
for _ in range(n):
	v.append(mp())
v.sort(key=lambda x: x[1])
(i, j) = (0, n - 1)
ans = 0
curr = 0
while i <= j:
	if curr < v[i][1]:
		target = v[i][1] - curr
		if v[j][0] < target:
			curr += v[j][0]
			ans += 2 * v[j][0]
			j -= 1
		else:
			v[j][0] -= target
			curr += target
			ans += 2 * target
	else:
		ans += v[i][0]
		curr += v[i][0]
		i += 1
print(ans)


n = int(input())
merch = []
for i in range(n):
	m = list(map(int, input().split(' ')))
	merch.append(m)
merch = sorted(merch, key=lambda x: x[1])
l = 0
r = len(merch) - 1
res = 0
num = 0
while l <= r:
	if merch[l][1] <= num:
		num += merch[l][0]
		res += merch[l][0]
		l += 1
	else:
		count = min(merch[r][0], merch[l][1] - num)
		res += count * 2
		num += count
		if count == merch[r][0]:
			r -= 1
		else:
			merch[r][0] -= count
print(res)


import sys
n = int(sys.stdin.readline())
data = []
for i in range(n):
	temp = list(map(int, sys.stdin.readline().split()))
	data.append(temp)
data.sort(key=lambda x: x[1])
(left, right) = (0, n - 1)
(ans, cnt) = (0, 0)
while left <= right:
	if cnt >= data[left][1]:
		ans += data[left][0]
		cnt += data[left][0]
		left += 1
	elif data[right][0] > data[left][1] - cnt:
		data[right][0] -= data[left][1] - cnt
		ans += (data[left][1] - cnt) * 2
		cnt += data[left][1] - cnt
	else:
		cnt += data[right][0]
		ans += data[right][0] * 2
		right -= 1
print(ans)


import sys
input = sys.stdin.readline
n = int(input())
A = [list(map(int, input().split())) for _ in range(n)]
A.sort(key=lambda x: (x[1], x[0]))
ans = 0
j = n - 1
cur = 0
for (i, (a, b)) in enumerate(A):
	if a == 0:
		break
	while j > i and cur < b:
		d = min(b - cur, A[j][0])
		A[j][0] -= d
		cur += d
		ans += d * 2
		if A[j][0] == 0:
			j -= 1
	if cur >= b:
		ans += a
		cur += a
	else:
		x = b - cur
		if a >= x:
			ans += x * 2 + (a - x)
			cur += a
		else:
			ans += a * 2
			cur += a
print(ans)


from operator import itemgetter

def main() -> None:
	n = int(input())
	products = [[int(i) for i in input().split()] for _ in range(n)]
	products.sort(key=itemgetter(1))
	left = 0
	right = len(products) - 1
	total_bought = 0
	total_cost = 0
	while left <= right:
		if products[left][1] <= total_bought:
			total_cost += products[left][0]
			total_bought += products[left][0]
			left += 1
		else:
			to_buy = min(products[left][1] - total_bought, products[right][0])
			total_cost += to_buy * 2
			total_bought += to_buy
			products[right][0] -= to_buy
			if products[right][0] == 0:
				right -= 1
	print(total_cost)
main()


import sys
import math
import heapq
import bisect
from collections import Counter
from collections import defaultdict
from io import BytesIO, IOBase
import string

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None
		self.BUFSIZE = 8192

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def get_int():
	return int(input())

def get_ints():
	return list(map(int, input().split(' ')))

def get_int_grid(n):
	return [get_ints() for _ in range(n)]

def get_str():
	return input().strip()

def get_strs():
	return get_str().split(' ')

def flat_list(arr):
	return [item for subarr in arr for item in subarr]

def yes_no(b):
	if b:
		return 'YES'
	else:
		return 'NO'

def binary_search(good, left, right, delta=1, right_true=False):
	limits = [left, right]
	while limits[1] - limits[0] > delta:
		if delta == 1:
			mid = sum(limits) // 2
		else:
			mid = sum(limits) / 2
		if good(mid):
			limits[int(right_true)] = mid
		else:
			limits[int(~right_true)] = mid
	if good(limits[int(right_true)]):
		return limits[int(right_true)]
	else:
		return False

def prefix_sums(a):
	p = [0]
	for x in a:
		p.append(p[-1] + x)
	return p

def solve_a():
	(n, x, t) = get_ints()
	if t // x >= n - 1:
		return n * (n - 1) // 2
	else:
		return t // x * (t // x - 1) // 2 + (n - t // x) * (t // x)

def solve_b():
	(n, q) = get_ints()
	s = get_str()
	alphabet = {x: i for (i, x) in enumerate(string.ascii_lowercase)}
	counts = [[0 for _ in range(26)] for _ in range(n + 1)]
	for (i, char) in enumerate(s):
		for x in range(26):
			counts[i + 1][x] = counts[i][x]
		counts[i + 1][alphabet[char]] += 1

	def query(l, r):
		tot = 0
		for x in range(26):
			tot += (x + 1) * (counts[r][x] - counts[l - 1][x])
		return tot
	ans = []
	for _ in range(q):
		ans.append(query(*get_ints()))
	return ans

def solve_c():
	(n, k, x) = get_ints()
	a = get_ints()
	a.sort()
	d = []
	for i in range(1, n):
		d.append(a[i] - a[i - 1])
	d.sort(reverse=True)
	while d:
		z = d.pop()
		y = z
		if y <= x:
			inserts = 0
		else:
			inserts = y // x + int(y % x != 0) - 1
		if k >= inserts:
			k -= inserts
		else:
			d.append(z)
			break
	return len(d) + 1

def solve_d():
	n = get_int()
	items = []
	for i in range(n):
		(a, b) = get_ints()
		items.append([b, a])
	items.sort()
	spend = 0
	i = 0
	j = n - 1
	purchased = 0
	while i < n:
		while purchased < items[i][0] and j >= 0:
			m = min(items[j][1], items[i][0] - purchased)
			items[j][1] -= m
			purchased += m
			spend += 2 * m
			if items[j][1] == 0:
				j -= 1
		m = items[i][1]
		items[i][1] -= m
		purchased += m
		spend += m
		i += 1
	return spend
print(solve_d())


from typing import List
from collections import namedtuple
Product = namedtuple('Product', ['a', 'b'])
N: int = int(input())
to_buy: int = 0
products: List[Product] = []
for _ in range(N):
	(a, b) = map(int, input().split(' '))
	products.append(Product(a, b))
	to_buy += a
products.sort(key=lambda p: p.b)
n_bought: int = 0
cost: int = 0
for p in products:
	n_expensive: int = min(max(0, p.b - n_bought), to_buy - n_bought)
	n_bought += n_expensive
	cheap = min(to_buy - n_bought, p.a)
	n_bought += cheap
	cost += 2 * n_expensive + cheap
	if to_buy == 0:
		break
print(cost)


import sys
n = int(input())
items = []
total_items = 0
for _ in range(n):
	(c, l) = list(map(int, sys.stdin.readline().strip().split()))
	total_items += c
	items.append((c, l))
items.sort(key=lambda x: x[1], reverse=True)
total_cost = 2 * total_items
pos = 0
while pos < total_items:
	(count, start) = items.pop()
	if start < total_items:
		if start > pos:
			pos = start
		pos += count
		total_cost -= count
		if pos > total_items:
			total_cost += pos - total_items
	else:
		break
print(total_cost)


from sys import stdin, stdout
import heapq
from collections import defaultdict
import math
import bisect
import io, os

def main():
	n = int(stdin.readline())
	arr = []
	total = 0
	for _ in range(n):
		arr.append(list(map(int, stdin.readline().split())))
		total += arr[-1][0]
	arr.sort(key=lambda x: x[1])
	ans = 0
	bought = 0
	l = 0
	r = n - 1
	while bought < total:
		while bought < total and bought >= arr[l][1]:
			bought += arr[l][0]
			ans += arr[l][0]
			l += 1
		if bought < total:
			to_buy = min(arr[r][0], arr[l][1] - bought)
			ans += to_buy * 2
			arr[r][0] -= to_buy
			bought += to_buy
			if arr[r][0] == 0:
				r -= 1
	stdout.write(str(ans) + '\n')
main()


import os, io, sys, time, collections, math, pprint, itertools as it, operator as op, bisect as bs, functools as fn
(maxx, localsys, mod) = (float('inf'), 0, int(1000000000.0 + 7))
nCr = lambda n, r: reduce(mul, range(n - r + 1, n + 1), 1) // factorial(r)
ceil = lambda n, x: (n + x - 1) // x
(osi, oso) = ('/home/priyanshu/Documents/cp/input.txt', '/home/priyanshu/Documents/cp/output.txt')
if os.path.exists(osi):
	sys.stdin = open(osi, 'r')
	sys.stdout = open(oso, 'w')
input = sys.stdin.readline

def maps():
	return map(int, input().split())
n = int(input())
(s, a) = (0, [])
for __ in range(n):
	(u, v) = maps()
	s += u
	a.append((u, v))
a.sort(key=lambda x: x[1], reverse=True)
ans = 2 * s
for (i, j) in a:
	if j >= s:
		continue
	ans -= min(i, s - j)
	s -= min(i, s - j)
print(ans)


import sys
input = sys.stdin.readline
n = int(input())
v = []
for i in range(n):
	(a, b) = map(int, input().split())
	v.append([a, b])
v.sort(key=lambda x: x[1])
ans = 0
l = 0
r = n - 1
now = 0
while True:
	if v[l][1] <= now:
		ans += v[l][0]
		now += v[l][0]
		l += 1
	else:
		(a, b) = v[r]
		if now + a <= v[l][1]:
			ans += a * 2
			now += a
			r -= 1
		else:
			x = v[l][1] - now
			v[r][0] -= x
			ans += x * 2
			now += x
	if l > r:
		break
print(ans)


prices = []
count = 0
n = int(input())
for _ in range(n):
	(a, b) = map(int, input().split())
	prices.append((b, a))
	count += a
prices.sort()
discount = 0
for i in range(n - 1, -1, -1):
	x = prices[i]
	if x[0] >= count:
		continue
	discount += min(count - discount - x[0], x[1])
print(2 * count - discount)


import os, sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd
from _collections import deque
import heapq as hp
from bisect import bisect_left, bisect_right
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 10 ** 9 + 7
n = int(input())
h = []
for _ in range(n):
	(a, b) = map(int, input().split())
	h.append([b, a])
ans = 0
h.sort()
a = deque((i for i in h))
tot = 0
while a:
	if tot < a[0][0]:
		t = min(a[0][0] - tot, a[-1][1])
		ans += t * 2
		tot += t
		a[-1][1] -= t
		if a[-1][1] == 0:
			a.pop()
	else:
		ans += a[0][1]
		tot += a[0][1]
		a.popleft()
print(ans)


import sys

def inpu():
	return sys.stdin.readline()
lets = 'abcdefghijklmnopqrstuvwxyz'
key = {lets[i]: i for i in range(26)}
n = int(input())
done = False
a = [0] * n
b = [0] * n
bb = 0
for i in range(n):
	(b[i], a[i]) = map(int, input().split())
	bb += b[i]
k = sorted(range(n), key=lambda i: a[i], reverse=True)
ans = bb
for i in range(n):
	ans = min(ans, bb)
	ans = max(a[k[i]], ans - b[k[i]])
print(min(ans, bb) + bb)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
n = int(input())
l = []
grand = 0
l1 = []
for i in range(n):
	(a, b) = map(int, input().split())
	l.append((b, a))
	l1.append((b, a))
	grand += a
l.sort()
l = deque(l)
total = 0
ans = 0
while total < grand:
	if total < l[0][0]:
		t = min(l[-1][1], l[0][0] - total)
		l[-1] = (l[-1][0], l[-1][1] - t)
		if l[-1][1] == 0:
			l.pop()
		total += t
		ans += t * 2
	else:
		ans += l[0][1]
		total += l[0][1]
		l.popleft()
print(ans)


R = lambda : map(int, input().split())
n = int(input())
arr = [list(R()) for i in range(n)]
arr.sort(key=lambda x: (-x[1], x[0]))
toto = tot = sum((x[0] for x in arr))
acc = 0
for (req, thr) in arr:
	if tot > thr:
		taken = min(req, tot - thr)
		tot -= taken
		acc += taken
print(toto * 2 - acc)


import sys, os
from io import BytesIO, IOBase
mod = 10 ** 9 + 7
Mod = 998244353
INF = float('inf')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
inp = lambda : list(map(int, sys.stdin.readline().rstrip('\r\n').split()))
from collections import Counter as cc
tc = 1
for test in range(1, tc + 1):
	n = int(input())
	a = [[-1, -1] for i in range(n)]
	ans = 0
	for i in range(n):
		(b, c) = inp()
		a[i][0] = c
		a[i][1] = b
	a.sort(key=lambda x: (x[0], x[1]))
	index = 0
	back = n - 1
	unnai = 0
	a.extend([[0, 0], [0, 0]])
	while index <= back:
		req = a[index][0]
		temp = min(a[back][1], req - unnai)
		a[back][1] -= temp
		ans += temp * 2
		unnai += temp
		if a[back][1] == 0:
			back -= 1
		while index <= back and req <= unnai:
			temp = a[index][1]
			ans += temp
			a[index][1] = 0
			index += 1
			unnai += temp
			req = a[index][0]
	print(ans)


prices = []
for _ in range(int(input())):
	(ai, bi) = map(int, input().split())
	prices.append([ai, bi])
prices.sort(key=lambda x: x[1])
(p, q) = (0, len(prices) - 1)
count = 0
bought = 0
while p <= q:
	if bought < prices[p][1]:
		tmp = min(prices[q][0], prices[p][1] - bought)
		count += 2 * tmp
		bought += tmp
		prices[q][0] -= tmp
		if prices[q][0] == 0:
			q -= 1
	else:
		bought += prices[p][0]
		count += prices[p][0]
		p += 1
print(count)


import sys
from bisect import bisect_right
input = sys.stdin.readline
n = int(input())
p = []
q = [0]
r = [0] * (n + 1)
s = 0
for (a, b) in sorted([list(map(int, input().split())) for _ in range(n)], key=lambda x: x[1]):
	s += a
	q.append(a)
	p.append(b)
(ng, ok) = (-1, s)
for i in range(n):
	q[i + 1] += q[i]
	r[i + 1] = max(r[i], p[i] - q[i])
while ok - ng > 1:
	m = (ng + ok) // 2
	t = m
	idx = min(n, bisect_right(q, s - m))
	if m < r[idx]:
		ng = m
	else:
		ok = m
print(ok + s)


price = 2
discounted_price = 1

class sortable:

	def __init__(self, necessary, qfdp) -> None:
		self.necessary = necessary
		self.quantity_for_discounted_price = qfdp

	def __lt__(self, other):
		return self.quantity_for_discounted_price < other.quantity_for_discounted_price

def buy(products, quantity, i, rightmost):
	while quantity > 0:
		if rightmost == i:
			break
		if quantity > products[rightmost].necessary:
			quantity -= products[rightmost].necessary
			products[rightmost].necessary = 0
			rightmost -= 1
		else:
			products[rightmost].necessary -= quantity
			quantity = 0
	assert rightmost >= i
	return (rightmost, quantity)

def solve():
	n = int(input())
	products = [0] * n
	for i in range(n):
		(necessary_quantity, discounted_quantity) = [int(x) for x in input().split()]
		products[i] = sortable(necessary_quantity, discounted_quantity)
	products.sort()
	(bought, paid, r) = (0, 0, n - 1)
	for i in range(n):
		assert paid >= bought
		if products[i].necessary == 0:
			continue
		if bought >= products[i].quantity_for_discounted_price:
			paid += discounted_price * products[i].necessary
		else:
			(r, left) = buy(products, products[i].quantity_for_discounted_price - bought, i, r)
			paid += price * (products[i].quantity_for_discounted_price - bought - left)
			bought += products[i].quantity_for_discounted_price - bought - left
			if r > i:
				assert left == 0
				paid += discounted_price * products[i].necessary
			if r == i:
				if products[i].necessary + bought < products[i].quantity_for_discounted_price:
					paid += price * products[i].necessary
				else:
					paid += price * (products[i].quantity_for_discounted_price - bought)
					paid += discounted_price * (products[i].necessary + bought - products[i].quantity_for_discounted_price)
		bought += products[i].necessary
		products[i].necessary = 0
	return paid
print(solve())


import sys
import os.path
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
depth = 1000005
mod = 1000000007
lim = mod * mod
sys.setrecursionlimit(depth)
linp = lambda : list(minp())
minp = lambda : map(int, input().split())
from math import inf, ceil, sqrt, log2
from collections import defaultdict
dd = lambda x: defaultdict(lambda : x)
n = int(input())
r = [None for _ in range(n)]
for i in range(n):
	r[i] = list(minp())
r.sort(key=lambda x: (x[1], -x[0]))
(i, j) = (0, n - 1)
cost = items = 0
while i <= j:
	while r[i][1] > items and i <= j:
		if r[j][0] + items <= r[i][1]:
			items += r[j][0]
			cost += 2 * r[j][0]
			j -= 1
		else:
			val = r[i][1] - items
			r[j][0] -= val
			items = r[i][1]
			cost += 2 * val
	if i <= j:
		items += r[i][0]
		cost += r[i][0]
		i += 1
print(cost)


import bisect
import copy
import decimal
import fractions
import heapq
import itertools
import math
import random
import sys
from collections import Counter, deque, defaultdict
from functools import lru_cache, reduce
from heapq import heappush, heappop, heapify, heappushpop, _heappop_max, _heapify_max

def _heappush_max(heap, item):
	heap.append(item)
	heapq._siftdown_max(heap, 0, len(heap) - 1)

def _heappushpop_max(heap, item):
	if heap and item < heap[0]:
		(item, heap[0]) = (heap[0], item)
		heapq._siftup_max(heap, 0)
	return item
from math import gcd as GCD
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
N = int(readline())
S = 0
dct = defaultdict(int)
for _ in range(N):
	(a, b) = map(int, readline().split())
	dct[b] += a
	S += a
ans = 0
cnt = 0
for b in sorted(dct.keys()):
	ans = max(ans, min(S + b - cnt, 2 * S))
	cnt += dct[b]
print(ans)


import os.path
from math import e, gcd, floor, ceil
from collections import *
import sys
mod = 1000000007
INF = float('inf')

def st():
	return list(sys.stdin.readline().strip())

def li():
	return list(map(int, sys.stdin.readline().split()))

def mp():
	return map(int, sys.stdin.readline().split())

def inp():
	return int(sys.stdin.readline())

def pr(n):
	return sys.stdout.write(str(n) + '\n')

def prl(n):
	return sys.stdout.write(str(n) + ' ')
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def solve():
	n = inp()
	l = [li() for i in range(n)]
	l.sort(key=lambda x: x[1], reverse=True)
	cur = 0
	for (a, b) in l:
		cur += 2 * a
	(start, end) = (0, n - 1)
	left = 0
	while start <= end:
		if start == end:
			cur -= max(l[start][0] - max(l[start][1] - left, 0), 0)
			pr(cur)
			return
		if left >= l[end][1]:
			left += l[end][0]
			cur -= l[end][0]
			end -= 1
		elif left + l[start][0] <= l[end][1]:
			left += l[start][0]
			l[start][0] = 0
			start += 1
		else:
			cur -= l[end][0]
			l[start][0] -= l[end][1] - left
			left += sum(l[end]) - left
			end -= 1
for _ in range(1):
	solve()


import os
import sys
from io import BytesIO, IOBase
import math
from collections import Counter

def func(n, array):
	array = sorted(array, key=lambda x: x[1])
	left = 0
	right = n - 1
	bought = 0
	total = 0
	while left <= right:
		if array[left][1] <= bought:
			total += array[left][0]
			bought += array[left][0]
			left += 1
		else:
			next_left = array[left][1] - bought
			if next_left > 0:
				if array[right][0] > next_left:
					total += next_left * 2
					bought += next_left
					array[right][0] -= next_left
				else:
					total += array[right][0] * 2
					bought += array[right][0]
					right -= 1
	return total

def main():
	n = int(parse_input())
	array = []
	for _ in range(n):
		(a, b) = [int(i) for i in parse_input().split()]
		array.append([a, b])
	print(func(n, array))
parse_input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def solve(n: int, a) -> int:
	a.sort(key=lambda x: x[1])
	left = 0
	right = n - 1
	bought = 0
	cost = 0
	while left <= right:
		if bought < a[left][1]:
			buying = min(a[right][0], a[left][1] - bought)
			a[right][0] -= buying
			bought += buying
			cost += 2 * buying
			if not a[right][0]:
				right -= 1
		else:
			buying = a[left][0]
			bought += buying
			cost += buying
			left += 1
	return cost
n = int(input())
a = []
for _ in range(n):
	a.append(list(map(int, input().split())))
print(solve(n, a))


import sys, os
import math
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
from io import BytesIO, IOBase
from bisect import *
from heapq import *

def main():
	n = int(input())
	arr = []
	t = 0
	for _ in range(n):
		arr.append(list(MI()))
		t += arr[_][0]
	arr.sort(key=lambda x: x[1])
	(i, j) = (0, n - 1)
	(out, c) = (0, 0)
	while c < arr[0][1] and j >= 0:
		if arr[j][0] + c <= arr[0][1]:
			c += arr[j][0]
			out += 2 * arr[j][0]
			arr[j][0] = 0
			j -= 1
		else:
			arr[j][0] -= arr[0][1] - c
			out += 2 * (arr[0][1] - c)
			c = arr[0][1]
			break
	if j == -1:
		print(out)
		return
	out += arr[0][0]
	c += arr[0][0]
	arr[0][0] = 0
	right = [0]
	for i in range(n - 2, -1, -1):
		right.append(arr[i][0] + right[-1])
	right.reverse()
	i += 1
	fin = 10 ** 15
	while i <= j:
		if c >= arr[i][1]:
			out += arr[i][0]
			c += arr[i][0]
			arr[i][0] = 0
			i += 1
		else:
			g = arr[i][1] - c
			if g <= arr[i][0]:
				out += g + arr[i][0]
				c += g + arr[i][0]
				arr[i][0] = 0
			else:
				fin = min(fin, out + right[i] * 2)
				out += arr[i][0] + g
				c += arr[i][0] + g
				arr[i][0] = 0
			i += 1
	print(min(out, fin))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

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

def outP(var):
	sys.stdout.write(str(var) + '\n')
MOD = 10 ** 9 + 7
mod = 998244353
main()


(n, p, k, sm, nn) = (int(input()), [], 0, 0, 0)
for i in range(n):
	(a, b) = map(int, input().split())
	p.append([b, a])
	nn += a
p.sort()
u = 0
d = n - 1
while k < nn:
	if p[u][0] > k:
		a = min(p[u][0] - k, p[d][1])
		if k >= p[d][0]:
			sm += a
		else:
			sm += 2 * a
		k += a
		p[d][1] -= a
		if p[d][1] == 0:
			d -= 1
		if k >= p[u][0]:
			sm += p[u][1]
			k += p[u][1]
			p[u][1] = 0
			u += 1
	else:
		sm += p[u][1]
		k += p[u][1]
		u += 1
print(sm)


n = int(input())
u = []
for i in range(n):
	(a, b) = map(int, input().split())
	u.append([a, b])
u.sort(key=lambda x: x[1])
i1 = 0
i2 = -1
ans = 0
k = 0
for _ in range(n):
	while i2 < len(u) - 1 and u[i2 + 1][1] <= k:
		i2 += 1
	if i1 > i2:
		if u[-1][0] < u[i2 + 1][1] - k:
			ans += 2 * u[-1][0]
			k += u[-1][0]
			u.pop()
		else:
			ans += 2 * (u[i2 + 1][1] - k)
			u[-1][0] -= u[i2 + 1][1] - k
			k = u[i2 + 1][1]
			i2 += 1
			ans += 1 * u[i1][0]
			k += u[i1][0]
			i1 += 1
	else:
		ans += 1 * u[i1][0]
		k += u[i1][0]
		i1 += 1
print(ans)


import sys
from os import path
import bisect
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output1.txt', 'w')
from heapq import heappop, heappush, heapify
from math import ceil
from collections import defaultdict
maxi = sys.maxsize
mini = -maxi
n = int(sys.stdin.readline())
l = []
total = 0
ans = 0
for i in range(n):
	(a, b) = map(int, sys.stdin.readline().split())
	total += 2 * a
	l.append([a, b])
l.sort(key=lambda x: x[1], reverse=True)
(st, e) = (0, n - 1)
while st <= e:
	if st != e:
		if ans + l[st][0] <= l[e][1]:
			ans += l[st][0]
			l[st][0] = 0
			st += 1
		elif ans >= l[e][1]:
			ans += l[e][0]
			total -= l[e][0]
			e -= 1
		else:
			total -= l[e][0]
			l[st][0] -= l[e][1] - ans
			ans += l[e][0] + l[e][1] - ans
			e -= 1
	else:
		d = max(0, l[st][1] - ans)
		total -= max(0, l[st][0] - d)
		break
print(total)


from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def smp():
	return map(str, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
n = iinp()
ml = [lmp() for i in range(n)]
tot = 0
for i in ml:
	tot += i[0]
ml.sort(key=lambda x: x[1])
i = 0
j = n - 1
bought = 0
cost = 0
while bought < tot:
	(x, y) = (ml[i], ml[j])
	if bought < x[1]:
		p = min(x[1] - bought, y[0])
		ml[j][0] -= p
		if ml[j][0] == 0:
			j -= 1
		cost += p * 2
		bought += p
		if bought == x[1]:
			bought += x[0]
			cost += x[0]
			i += 1
	else:
		bought += x[0]
		cost += x[0]
		i += 1
print(cost)


def naiveSolve():
	return

def main():
	n = int(input())
	ba = []
	for _ in range(n):
		(a, b) = readIntArr()
		ba.append((b, a))
	ba.sort()
	a = []
	b = []
	for (bb, aa) in ba:
		a.append(aa)
		b.append(bb)
	l = 0
	r = n - 1
	takenCnts = 0
	ans = 0
	while l < r:
		if takenCnts < b[l]:
			change = min(a[r], b[l] - takenCnts)
			ans += change * 2
			takenCnts += change
			a[r] -= change
			if a[r] == 0:
				r -= 1
		else:
			change = a[l]
			ans += change
			takenCnts += change
			a[l] = 0
			l += 1
	change = min(a[l], max(0, b[l] - takenCnts))
	ans += change * 2
	a[l] -= change
	ans += a[l]
	print(ans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

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

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(a, b):
	print('? {} {}'.format(a, b))
	sys.stdout.flush()
	return True if input() == 'SI' else False

def answerInteractive(ans):
	print('! {}'.format(ans))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
from math import gcd, floor, ceil
for _abc in range(1):
	main()


from os import path
from io import BytesIO, IOBase
import sys
from heapq import heappush, heappop
from functools import cmp_to_key as ctk
from collections import deque, Counter, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input().rstrip()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('a')
file = 1

def ceil(a, b):
	return (a + b - 1) // b

def solve():
	a = []
	n = ii()
	for i in range(n):
		(x, y) = mi()
		a.append([y, x])
	a.sort()
	l = 0
	r = n - 1
	cnt = 0
	tot = 0
	while l <= r:
		if a[l][0] <= cnt:
			tot += a[l][1]
			cnt += a[l][1]
			l += 1
		else:
			req = a[l][0] - cnt
			x = min(req, a[r][1])
			a[r][1] -= x
			if a[r][1] == 0:
				r -= 1
			cnt += x
			tot += 2 * x
	print(tot)
if file:
	if path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	else:
		input = sys.stdin.readline
solve()


import sys
import math
import bisect
import heapq
from bisect import bisect_right
from sys import stdin, stdout

def get_ints_in_variables():
	return map(int, sys.stdin.readline().strip().split())

def get_int():
	return int(sys.stdin.readline())

def get_ints_in_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_list_of_list(n):
	return [list(map(int, sys.stdin.readline().strip().split())) for _ in range(n)]

def get_string():
	return sys.stdin.readline().strip()

def myceil(x, y):
	return (x + y - 1) // y

def Solution(arr, n):
	arr = sorted(arr, key=lambda x: x[1])
	l = 0
	r = n - 1
	ans = 0
	itmBought = 0
	while l <= r:
		if arr[l][1] > itmBought:
			need = min(arr[l][1] - itmBought, arr[r][0])
			arr[r][0] -= need
			itmBought += need
			ans += 2 * need
			if arr[r][0] == 0:
				r -= 1
		else:
			itmBought += arr[l][0]
			ans += arr[l][0]
			l += 1
	print(ans)

def main():
	n = get_int()
	arr = [get_ints_in_list() for _ in range(n)]
	Solution(arr, n)
main()


from sys import stdin
n = int(stdin.readline())
lst = list()
for i in range(n):
	(a, b) = map(int, stdin.readline().split())
	lst.append([b, a])
lst.sort(key=lambda x: tuple(x))
nzi = n - 1
cur = 0
ans = 0
for i in range(n):
	while nzi >= 0 and cur < lst[i][0]:
		w = min(lst[i][0] - cur, lst[nzi][1])
		lst[nzi][1] -= w
		cur += w
		ans += 2 * w
		if lst[nzi][1] == 0:
			nzi -= 1
	ans += lst[i][1]
	cur += lst[i][1]
	lst[i][1] = 0
print(ans)


n = int(input())
item = []
for i in range(n):
	(a, b) = map(int, input().split())
	item.append([a, b])
item.sort(key=lambda x: x[1])
i = 0
j = n - 1
count = 0
ans = 0
while i <= j:
	if item[i][1] <= count:
		temp = item[i][0]
		item[i][0] = 0
		ans += temp
		count += temp
		i += 1
	elif item[i][1] - count <= item[j][0]:
		temp = item[i][1] - count
		item[j][0] -= temp
		count += temp
		ans += temp * 2
		temp = item[i][0]
		item[i][0] = 0
		ans += temp
		count += temp
		i += 1
	else:
		temp = item[j][0]
		item[j][0] = 0
		count += temp
		ans += temp * 2
		j -= 1
print(ans)


from sys import stdin
input = stdin.readline
n = int(input())
c = []
for _ in range(n):
	(a, b) = [int(x) for x in input().split()]
	c.append([b, a])
c.sort()
l = 0
r = n - 1
buyed = 0
costs = 0
while l <= r:
	needed_for_discount = c[l][0]
	needed_to_buy = c[l][1]
	if buyed >= needed_for_discount:
		buyed += needed_to_buy
		costs += needed_to_buy
		l += 1
	else:
		without_discount = c[r][1]
		if buyed + without_discount < needed_for_discount:
			costs += 2 * without_discount
			buyed += without_discount
			r -= 1
		else:
			new_buyed = needed_for_discount - buyed
			buyed += new_buyed
			costs += 2 * new_buyed
			c[r][1] -= new_buyed
			if c[r][1] == 0:
				r -= 1
print(costs)


n = int(input())
(a, b) = ([], [])
for _ in range(n):
	(ax, bx) = input().split(' ')
	a.append(int(ax))
	b.append(int(bx))
shopping_list = dict()
for (aa, bb) in zip(a, b):
	if bb in shopping_list:
		shopping_list[bb] += aa
	else:
		shopping_list[bb] = aa
items_bought = 0
cost = 0
ind = sorted(shopping_list)
while shopping_list:
	x = ind[0]
	if items_bought < x:
		y = ind[-1]
		if shopping_list[y] <= x - items_bought:
			cost += 2 * shopping_list[y]
			items_bought += shopping_list[y]
			del shopping_list[y]
			ind.pop(-1)
		else:
			shopping_list[y] -= x - items_bought
			cost += 2 * (x - items_bought)
			items_bought += x - items_bought
	else:
		cost += 1 * shopping_list[x]
		items_bought += shopping_list[x]
		del shopping_list[x]
		ind.pop(0)
print(cost)


n = int(input())
al = []
for _ in range(n):
	(ai, bi) = map(int, input().split())
	al.append([ai, bi])
al = sorted(al, key=lambda x: x[1])
p1 = 0
p2 = len(al) - 1
quan = 0
cost = 0
while p2 >= p1:
	diff = al[p1][1] - quan
	while diff > 0:
		tmp = min(diff, al[p2][0])
		diff -= tmp
		al[p2][0] -= tmp
		quan += tmp
		cost += 2 * tmp
		if al[p2][0] == 0:
			p2 -= 1
		if p2 < p1:
			break
	if p2 < p1:
		break
	cost += al[p1][0]
	quan += al[p1][0]
	al[p1][0] = 0
	p1 += 1
print(cost)


n = int(input())
dp = []
cnt1 = 0
cnt2 = 0
for i in range(n):
	(a, b) = list(map(int, input().split()))
	dp.append((b, a))
	cnt2 += a
dp.sort()
dp = dp[::-1]
for i in range(n):
	cnt1 += min(cnt2 - cnt1 - min(dp[i][0], cnt2), dp[i][1])
print(cnt2 * 2 - cnt1)