E. Shopping Master
time limit per test
2 seconds
memory limit per test
1024 megabytes
input
standard input
output
standard output

In the Icpca Kingdom, two types of currency, coins and gems, are used. To buy a merchandise in shops in this kingdom, you pay either the number of coins shown on its price tag or only $$$1$$$ gem.

Today, the final day of your sightseeing trip to the Icpca Kingdom, you are visiting a souvenir shop to buy some bottles of local signature liquor. There are $$$n$$$ bottles of liquor in this shop. Each liquor is crafted by a different artisan, and therefore the prices may vary. Although you have enough number of coins, you'd like to buy all the $$$n$$$ bottles with the lowest possible amount of coins, appropriately using the unique benefits provided by the shop.

The detail of the unique benefits is as follows: for some of the bottles in this shop, a complimentary bag of some number of gems are attached to them. Therefore, buying some bottles using the bonus gems that are obtained at prior purchases may reduce the number of coins required.

Starting with no gems, what is the minimum number of coins required to buy all the $$$n$$$ bottles?

Figure E.1 describes the prices of the bottles and gems attached to them in the first test case of Sample Input 1. In this case, if you buy the first bottle for $$$400$$$ coins, you obtain one gem. Then, by buying the third, fourth, and second bottles in this order using gems, you can buy them all without paying any additional coins.

Figure E.1: The first test case of Sample Input 1
Input

The input contains one or more test cases, each in the following format.

$$$n$$$
$$$a_{1}$$$ $$$b_{1}$$$
$$$a_{2}$$$ $$$b_{2}$$$
$$$\vdots$$$
$$$a_{n}$$$ $$$b_{n}$$$

The integer $$$n$$$ $$$(1 \leq n \leq 10^5)$$$ in the first line is the number of bottles in the souvenir shop. The $$$i$$$-th line of the next $$$n$$$ lines describes the information on the $$$i$$$-th bottle $$$(i = 1, 2, \dots, n)$$$. The integer $$$a_i$$$ $$$(1 \leq a_i \leq 10^9)$$$ is the number of coins on the price tag of the $$$i$$$-th bottle, and the integer $$$b_i$$$ $$$(0 \leq b_i \leq n)$$$ is the number of gems in the bag attached to the $$$i$$$-th bottle.

The end of the input is indicated by a line containing a zero. The number of test cases does not exceed $$$2500$$$. The sum of $$$n$$$ over all the test cases does not exceed $$$10^5$$$.

Output

For each test case, output in a line the minimum number of coins required to buy all the $$$n$$$ bottles.

Example
Input
4
400 1
500 0
600 1
800 2
5
1540 0
1430 0
1320 0
1210 0
1100 0
20
861 0
901 0
955 1
602 1
882 1
188 1
817 0
932 2
669 0
621 2
276 0
668 0
825 1
834 1
341 2
545 0
218 0
939 0
179 1
587 1
0
Output
400
6600
1747