We need to solve problem: There are n items, each with a_i (required quantity) and b_i (threshold after which discount applies for that product). All items initially cost 2 rubles. For product i, if we have already bought b_i items in total (any products) before buying an item of product i, then that item costs 1 ruble instead of 2 (discount). The discount applies to all subsequent purchases of that product (once we have reached b_i total items, then for all future purchases of product i, we get discount). So the cost for each unit of product i depends on the order: we might buy some units before reaching b_i (cost 2) and the rest after reaching b_i (cost 1). The goal: minimize total cost, given we can choose order of purchases and can also buy extra items beyond required a_i? The problem says: "she can buy more items of some product than needed." So we can buy extra items to trigger discounts early, but they count towards the total items purchased. So we can buy extra items (at cost) to achieve b_i thresholds for other products.
Thus we need to choose a purchasing strategy: we have to purchase at least a_i of product i, but we can purchase more if beneficial. All purchases count towards total count of items bought. The discount for product i applies when total items purchased before that specific purchase is at least b_i. Since discount is per unit after that point, it's like we can switch the cost of product i from 2 to 1 after we have accumulated total purchases >= b_i. But careful: If we buy extra items of product i after discount, they also cost 1, so buying extra might be cheap. However, extra items themselves also cost money, so we need to weigh.
This is a classic greedy problem known as "PriceFixed" from Codeforces (CF 1439 B? Actually it's CF Round #? It's Codeforces problem "PriceFixed" 1439B? No that's Div2? Wait I recall a problem: "1462C" no. Actually I think it's from Codeforces Round #686 (Div3) maybe? Let's search memory: I think problem "1463B" is Find the Array. Hmm. There's a known problem "1472E" but not. I recall a problem: "PriceFixed" appears as Codeforces Round #1440 (Div2) problem C? Actually I've solved it: It's Codeforces #1400? Let’s recall: The solution sorts items by b_i ascending, and then uses two pointers: we try to buy as many as possible from the cheapest discount threshold? Actually typical solution: sort items by b_i (discount threshold). Then we maintain left pointer at small b_i and right pointer at large b_i. We try to buy from right (higher b_i) first at full price to accumulate total purchases to get discounts for left items? Wait typical solution: We want to minimize cost, so we want to trigger discounts for items with low b_i (i.e., easier to get discount) by buying items with high b_i (which are harder to get discount) at full price. However, we can also buy extra from items with low b_i after discount? Actually common approach: Sort by b_i ascending. We'll have two pointers: i from left (low b_i) and j from right (high b_i). We'll try to accumulate total purchases count 'bought' so far. For item i, we need to buy a_i items. But once bought >= b_i, we can get discount for the remaining of i. But since i has low b_i, it may be already triggered early if we buy some items from other products. So we want to buy items from j (with high b_i) at full price (cost 2) to increase count, so that we can then buy items from i at discount (cost 1). However, we can also buy extra items from i (beyond a_i) at discount to further increase count? But if i is already discount eligible, extra items cost 1, which is cheap, so it might be beneficial to buy extra from low b_i items to increase count for high b_i items? But high b_i items, if we buy them after discount, they also cost 1, but they only get discount when total count reaches b_i, which may be high. So maybe we want to trigger discounts for high b_i items as well, but that may be too costly. The typical solution is to use two pointers: We maintain total bought so far. For left item (low b_i), we want to satisfy its requirement as much as possible after discount, but we may need to buy some at full price if we cannot reach b_i by buying from right items (which are at full price). For right items (high b_i), we will buy at full price until we have enough total to get discount for left items. After left items are satisfied, we might then buy the remaining right items at discount? But they have high b_i, maybe we never reach that threshold. Actually we need to buy all required a_i items. The optimal strategy: we want to maximize the number of items bought at discount (cost 1). Each item bought at discount saves 1 ruble compared to full price. However, to get discount for a product i, we need total purchases before that item to be >= b_i. That is, discount applies only to purchases after we have reached b_i total items. So the order matters: If we can arrange to buy enough items at full price first to push total over b_i for many products, then the remaining items can be at discount. Also we might buy extra items cheaply at discount to further increase total and unlock more discounts. This suggests that we should try to delay buying items that have low b_i, because they become cheap once we have enough total purchases; whereas items with high b_i may never become cheap, but we can buy them early at full price, which helps increase total. Actually, if an item has high b_i, it's hard to reach that threshold before buying it; so likely we will buy it at full price, and maybe even extra to increase count. But buying extra items of a high b_i product at full price costs 2 each, and they increase total count, possibly enabling discounts for low b_i products. So there is a tradeoff: buying extra items of high b_i product costs 2, but enables saving 1 per discounted item for low b_i products. Is it worth it? Possibly yes, but we need to compute optimal.
The known solution for this CF problem "1462C" no. Let's think: The constraints: n up to 100k, a_i and b_i up to 1e14, sum of a_i up to 1e14, so we need O(n log n) or similar. The typical solution: Sort items by b_i (threshold). Use two pointers: left (low b_i) and right (high b_i). Maintain total_bought = 0. For left items, we want to buy as much as possible after discount. But we might need to buy some of them at full price if we can't get enough total from right items. The algorithm:
Initialize array of items (a_i, b_i). Sort by b_i ascending. Let left = 0, right = n-1. total_bought = 0, cost = 0. While left <= right:
- While left <= right and total_bought >= b_left (i.e., we have enough to get discount for left product), then we can buy all required a_left at discount (cost += a_left * 1). But careful: we also need to update total_bought += a_left. Then left++.
- Else (total_bought < b_left), we need to increase total_bought to try to reach b_left. We do this by buying items from right product (high b) at full price. But we must be careful not to buy more than needed: we want to buy just enough to reach b_left or to buy all of a_right, whichever is less. Actually we can buy from right product at full price (cost 2) because its discount threshold is high, and we might not reach it. But we might also later get discount for right product if total_bought becomes large enough? Possibly if total_bought reaches b_right, then future purchases of that product become discount. But in this algorithm, we typically buy from right at full price first, and after we have satisfied left products, we may have some right items remaining; then we can buy those at discount if total_bought has reached their thresholds? But if total_bought is already large, maybe we can get discount for right items. Actually after left items are done, we may have total_bought huge, then we can buy right items at discount. But this algorithm as I recall: it uses two pointers and buys from right until total_bought reaches b_left. However, we must also account that we might exceed b_left and then later left can be bought at discount. At the end, after left passes right, everything is bought.
But I need to verify with known solutions. I remember a Codeforces editorial: "PriceFixed" problem (CF #1462? Actually I think it's Codeforces Round #1440 (Div. 2) problem C? Let's recall: The problem ID is 1462C? That's "Unique Number". Not that. It might be from Codeforces Round #1462 (Div. 1)? Hmm. Let's search memory: I recall a problem: "C. PriceFixed" from Codeforces Round #1462 (Div. 2)?? Actually I recall problem statement: Lena is economical girl... That's exactly this problem. I think it's from Codeforces Round #1462 (Div. 2) problem C? Wait, I remember that round had problems: A. Favorite Sequence, B. Last Year's Substring, C. Unique Number, D. Add to Neighbour and Remove? That doesn't match. Another round: Codeforces Round #1462 is "Divide and Summarize"? Not.
Actually, I'm aware of a known problem: "C. PriceFixed" from Codeforces Round #1409 (Div. 2) perhaps? Let's quickly Google memory: It's a problem with a girl named Lena. I've solved it. I recall the solution: sort by b_i, two pointers, and use variable 'taken' (total bought). For the right product, we buy min(need, b[left] - taken) at full price. That's typical.
Let me derive the optimal strategy logically.
We have items i each with (a_i, b_i). Let total items we eventually purchase be T (which is at least sum a_i, but we might purchase extra). Each item costs either 2 or 1 depending on whether we have already purchased at least b_i items before that particular unit. So it's about ordering. In an optimal ordering, we can think of each unit being bought either at full price (2) or discounted (1). To minimize cost, we want as many units as possible to be discounted. However, to get a discount on a unit of product i, we need that the number of units bought before that unit is at least b_i. Since we control order, we can arrange to buy some units early (full price) and later units discounted.
One way to view: Suppose we decide on the total number of units we will buy (including extras) and an ordering. A classic greedy approach is to buy items with highest b_i first (full price) to increase count, then items with lower b_i later (discount). However, we might also buy extra of low b_i items at discount to further increase count for others? But once low b_i items are discounted, buying extra at cost 1 is cheap, and can help raise total to reach higher b_i thresholds, potentially unlocking discounts for high b_i items. So there might be a cycle.
Better: This problem is analogous to "unlocking discounts" where each product i has a threshold b_i, and after we have bought b_i total, the cost of that product becomes 1. So we want to minimize total cost, given we must buy at least a_i of each, and we can buy extra. This is like we have to pay 2 per item initially, but we can "activate" a discount for product i by ensuring that the total number of items purchased (including that product's own purchases? careful: the discount applies to items purchased after the threshold is reached. So if we want to get discount on some of product i's required units, we need to have bought at least b_i items before those units. That could include some of product i's own units if we buy some early at full price and then the rest later. So for product i, we can split its a_i units into some bought at full price (early) and some at discount (late). The discount activation can be achieved either by buying other products or by buying some of the same product at full price.
Thus each product i can be thought of: we will buy x_i units at full price (cost 2) and y_i units at discount (cost 1), with x_i + y_i >= a_i (we can buy extras, so >=). The total number of units bought (including extras) is X + Y, where X = sum of all x_i, Y = sum of all y_i. The order: we need to arrange purchases such that for each unit bought at discount, at the time of purchase, the total number of units already bought (before that unit) >= b_i. This imposes constraints on the ordering. Typically, if we think of buying all full price items first, then all discount items, then for each product i, the discount units come after we have accumulated at least b_i total purchases. If we buy all full price items first, then total full price purchases = X. Then we start buying discount items. For product i, we can only buy its discount units if X >= b_i. If X < b_i, we cannot buy any discount units for product i unless we also include some of its own units among the full price items? Actually if we allow mixing, we could buy some full price items from i after some discount items? The condition for a discount unit is that before that unit, total purchases >= b_i. So if we buy all full price first, then discount, the condition for i's discount units is X >= b_i. If X < b_i, then we could still get discount for i if we interleave: we could buy some discount units from other products, increasing total, then later buy discount units from i. But those other discount units themselves require that at their time, the total before them meets their own thresholds. This becomes complex.
Alternative perspective: We can treat the problem as we need to pay 2 per item by default, but we get a "discount" of 1 per item for those that are bought after the threshold. So total cost = 2 * (total items bought) - (number of items bought at discount). Since total items bought = sum of purchased quantities (including extras). Let S = sum a_i (minimum total). We may buy extra items, say E, so total T = S + E. Then total cost = 2T - D, where D is number of discounted items (each saves 1). So minimizing cost is equivalent to maximizing (D - 2E) because cost = 2S + 2E - D = 2S + (2E - D). Actually we want to minimize cost, so we want to maximize D - 2E? Let's rearrange: cost = 2T - D = 2S + 2E - D. Since 2S is constant (given S = sum a_i), we need to minimize (2E - D) = 2E - D, i.e., maximize D - 2E. But E = T - S, so cost = 2S + 2(T-S) - D = 2T - D. Minimizing cost is equivalent to maximizing D - 2(T-S) = D - 2E. However, T and D are linked via constraints.
But maybe easier to use known solution.
Let's search memory: I recall the editorial: Sort products by b_i. Use two pointers. Maintain total bought. For each product from left (low b_i), we need to buy its a_i items. We want to buy as many as possible at discount. So we try to first use purchases from right (high b_i) at full price to increase total bought until it reaches b_left, then we can buy the left product at discount. However, we might need to buy some of left product at full price if we cannot reach b_left even after buying all right products. But we can also buy extra of left product at full price? That might help reaching its own discount? But if we buy left product at full price, it increases total and also counts towards its own required a_i. So if we cannot reach b_left by buying only right products, we may have to buy some left items at full price until total reaches b_left, then the rest at discount.
Thus algorithm:
- Sort items by b_i ascending.
- Initialize left = 0, right = n-1, total_bought = 0, cost = 0.
- While left <= right:
- if total_bought >= b[left]:
// can buy all remaining required of left at discount
cost += a[left] * 1; (or we could just add a[left] because discounted)
total_bought += a[left];
left++;
- else:
// need to increase total_bought to b[left] by buying from right at full price
// but we must also ensure we don't over-buy from right beyond its requirement
// we can buy from right: amount = min(a[right], b[left] - total_bought)
// because we only need to buy enough to reach b[left]
// However, note that if we buy from right at full price, it contributes to total_bought and cost
// If we buy entire a[right] and still total_bought < b[left], we will then continue loop (still left same, right decreases)
// If we buy a partial amount from right (because we only need b[left] - total_bought), then after that, total_bought becomes exactly b[left] (or maybe more if we buy integer units? Actually a_i and b_i are integers, and we are buying integer items. So we can buy exactly that many items. It's fine.
// After buying that partial amount, we reduce a[right] by that amount, and if a[right] becomes 0, we move right--.
// Then next iteration, total_bought >= b[left] will be true, and we will buy left at discount.
// But careful: When we buy partial from right, we pay full price for those items (2 each). That seems correct.
// However, what about the possibility that after we satisfy left, we might later buy the remainder of right at discount if total_bought becomes large enough? This algorithm will later handle right when it becomes left? Actually after we finish all left items (low b_i), we will have some right items left. At that point, total_bought is likely large (since we have bought many items). Then we will process those right items: At that point, total_bought >= b[left] for all left, but for the right items, we need to check if total_bought >= b[right]? In the algorithm as described, after left > right, the loop ends. But we still need to buy the remaining right items. Usually the algorithm continues until left > right, and it also handles the case when left == right? Actually we need to ensure that all required a_i are purchased. In this two-pointer algorithm, we are decrementing right when its a becomes zero, and incrementing left when its a becomes zero. At the end, when left > right, all items are bought. But we must also consider that when we are in the else branch, we buy from right (maybe full price). But what about later when we have processed all left items, there might be right items left; but at that point total_bought is large, and we might be able to buy them at discount. However, in the algorithm as described, when left <= right and total_bought >= b[left] we buy left at discount and left++. But if left has moved past all low b_i, and only high b_i remain, then b[left] is high (since sorted ascending). So total_bought may be less than b[left] for those high b_i. Then the else branch will trigger and we will buy from right at full price. But the right pointer is at the highest b_i, but that's the same as left if only one remains? Actually when only high b_i remain, left points to the smallest among those remaining, which might still be high. So we would be buying from the rightmost (highest b_i) at full price to increase total_bought to reach b[left]? That seems odd: to get discount for a high b_i product, we would need to reach its high threshold. But we might not be able to reach it even after buying all other items, so we may end up buying it at full price. But the algorithm will treat that by buying from the rightmost? Actually if left points to a product with high b_i, and total_bought < b[left], we will attempt to buy from the rightmost (which has even higher b_i) at full price. That seems counterproductive: buying from a product with even higher b_i (which is harder to discount) at full price will increase total_bought, possibly enough to reach b[left]? But then later we might buy the left product at discount if total_bought reaches its b. But if left product's b is high, maybe we can reach it after buying the rightmost product entirely? Then after we buy the rightmost at full price (or partially), total_bought might become >= b[left], then we can buy left at discount. That is plausible: For a high b_i product, we might still get discount if we first buy other high b_i products at full price to accumulate enough total, then buy it at discount. However, note that when we buy the rightmost (highest b) product at full price, that product itself may later become eligible for discount if we later have enough total before buying some of its units? But in this algorithm, we buy all of a product either entirely at full price (if it's from the right) or entirely at discount (if it's from the left). But we might also split a product: some units at full price, some at discount. That might be necessary for optimality. Indeed, the two-pointer algorithm commonly includes the ability to split the rightmost product: we buy only as much as needed from the right to trigger discount for the left, and later we may buy the remainder of the right product at discount if possible. This is indeed typical.
Let's recall exactly: I think the correct algorithm is:
Sort items by b_i ascending. Let total_bought = 0, cost = 0. Two pointers: l = 0, r = n-1. While l <= r:
if total_bought >= b[l]:
// all remaining of l can be bought at discount
cost += a[l];
total_bought += a[l];
l++;
else:
// need to buy some items at full price to increase total_bought
// we buy from r (highest b) at full price, but only as much as needed to reach b[l] (or all of a[r] if not enough)
let need = b[l] - total_bought;
let take = min(a[r], need);
cost += take * 2;
total_bought += take;
a[r] -= take;
if a[r] == 0:
r--;
After loop, cost is answer.
But is this always optimal? Let's test on the sample.
Sample 1:
n=3
(3,4)
(1,3)
(1,5)
Sort by b: b values: 3,4,5? Actually (1,3) b=3, (3,4) b=4, (1,5) b=5. So sorted: index0: (1,3), index1: (3,4), index2: (1,5).
l=0,r=2,total=0,cost=0.
total(0) < b[l]=3 -> else: need=3-0=3. a[r]=1, take=min(1,3)=1. cost+=2, total=1, a[r]=0 -> r=1.
Now l=0,r=1,total=1 <3 -> else: need=2. a[r]=3, take=min(3,2)=2. cost+=4, total=3, a[r]=3-2=1. (r remains 1 because a[r] not zero).
Now total=3 >= b[l]=3 -> if: cost+= a[l]=1 (discount), total+=1 => total=4, l=1.
Now l=1,r=1,total=4 >= b[l]=4 -> if: cost+= a[l]=1? Wait a[l] is now? We have left index 1: originally (3,4) but we reduced its a to 1 (since we took 2 from it earlier). So a[1]=1. cost+=1, total=5, l=2. Now l=2,r=1 -> loop condition l<=r? l=2, r=1 => false, exit. So cost = 2+4+1 = 7? But sample answer is 8. Did we miss something? Actually we have not bought the item from index0? Wait index0 was (1,3) we bought at discount cost 1 (since a[l] was 1). That's accounted. Then we bought 2 from index1 at full price (cost 4) and later the remaining 1 from index1 at discount (cost 1). And we bought the item from index2 at full price (cost 2). Total cost = 1+4+1+2 = 8? But my calculation: cost added in steps: first else: cost+=2 (index2). Second else: cost+=4 (two items from index1 at full). Third if: cost+=1 (remaining from index1? Wait check: after second else, we have a[r] = 1 (remaining of index1). Then third if: total=3, b[l]=3 for index0? Actually third if was triggered for l=0? Wait I need to re-simulate carefully.
Let me step:
Initialize:
items sorted:
0: a=1, b=3
1: a=3, b=4
2: a=1, b=5
l=0, r=2, total=0.
Step1: total=0 < b0=3 => else: need = 3-0=3. take = min(a2=1,3)=1. cost += 2*1=2, total=1, a2=0 -> r=1. Now a=[1,3,0], r=1.
Step2: l=0, total=1 <3 => else: need=2. take = min(a1=3,2)=2. cost += 2*2=4, total=3, a1=1. (r remains 1 since a1>0). Now a=[1,1,0].
Step3: total=3 >= b0=3 => if: buy all of a0 at discount: cost += a0=1, total +=1 => total=4, l=1. a0 becomes 0. Now a=[0,1,0], l=1, r=1, total=4.
Step4: l=1, r=1, total=4 >= b1=4 => if: buy all of a1 at discount: cost += a1=1, total +=1 => total=5, l=2. Now l=2, r=1 => loop ends.
Total cost = 2+4+1+1 = 8. Yes cost=8, matches sample. I earlier miscounted steps: Actually step3 added 1, step4 added 1, so total 2+4+1+1=8. Good.
Now sample 2:
Input:
5
2 7
2 8
1 2
2 4
1 8
First compute S? Let's sort by b.
List products:
(2,7)
(2,8)
(1,2)
(2,4)
(1,8)
Sort by b:
b=2: (1,2)
b=4: (2,4)
b=7: (2,7)
b=8: (2,8) and (1,8) -> two with b=8, order maybe any. Let's order ascending, for ties it doesn't matter? But careful: the algorithm might be affected if we have ties? Usually not. We'll keep as: index0 (1,2), index1 (2,4), index2 (2,7), index3 (2,8), index4 (1,8). But we need to ensure stable? Not needed.
Now simulate algorithm:
Initial: a=[1,2,2,2,1], b=[2,4,7,8,8], total=0, cost=0, l=0, r=4.
Step1: total=0 < b0=2 => need=2, take = min(a4=1,2)=1 => cost+=2, total=1, a4=0, r=3. Now a=[1,2,2,2,0].
Step2: total=1 <2 => need=1, take = min(a3=2,1)=1 => cost+=2, total=2, a3=1, r=3 (since a3>0). Now a=[1,2,2,1,0].
Now total=2 >= b0=2 => if: buy all a0 at discount: cost+=1, total+=1 => total=3, l=1. a0=0.
Now l=1, r=3, total=3 < b1=4 => else: need=1, take = min(a3=1,1)=1 => cost+=2, total=4, a3=0, r=2. a=[0,2,2,0,0].
Now total=4 >= b1=4 => if: buy all a1 at discount: cost+=2, total+=2 => total=6, l=2. a1=0.
Now l=2, r=2, total=6 < b2=7 => else: need=1, take = min(a2=2,1)=1 => cost+=2, total=7, a2=1, r=2 (a2>0). a=[0,0,1,0,0].
Now total=7 >= b2=7 => if: buy all a2 at discount: cost+=1, total+=1 => total=8, l=3. Now l=3, r=2 => loop ends.
Total cost = steps: 2 + 2 + 1 + 2 + 2 + 2 + 1 = let's sum: step1:2, step2:2 =>4, step3:1 =>5, step4:2 =>7, step5:2 =>9, step6:2 =>11, step7:1 =>12. Yes 12 matches sample. Good.
Thus algorithm works for samples.
Now we need to prove correctness.
The idea: Sort by b_i. The plan: we want to buy as many items as possible at discount. The discount for product i becomes available after total purchased >= b_i. Since we can buy extra items, we can increase total purchases beyond sum a_i. But we must pay for extra items, possibly at discount (cost 1) if we can get discount on them. So we might consider buying extra of low b_i products after they are discounted to cheaply increase total to reach higher thresholds.
The two-pointer algorithm effectively does: we process products in increasing order of b_i (left). For each left product, we try to achieve its discount threshold by buying from the rightmost products (high b_i) at full price. Once we reach the threshold, we buy the left product entirely at discount. This ensures that for each left product, we only buy it after we have already bought enough items (from high b_i products) to meet its threshold, so it's all discounted. However, we might not be able to buy enough from right products to meet the threshold; in that case, we will end up buying some of the left product at full price? But the algorithm as described never buys left product at full price; it only buys left product entirely at discount once threshold reached. So what happens if we run out of right products before reaching b_left? Then we would have to buy the left product at full price? Actually in the algorithm, if we run out of right products (i.e., l <= r but we have no right products left? That can't happen because right pointer moves only when its a becomes zero; if we run out of right products before reaching b_left, then l would be less than or equal to r? Actually if r becomes less than l, loop ends, but there might still be left products not bought? Let's examine: The loop continues while l <= r. The left products are from l to r inclusive. The right products are also within that range. So if we have left product that hasn't been bought yet (l points to it) and we have no right products (i.e., r < l) then loop would have ended, but that's impossible because r >= l as long as there are products left. But could we have a scenario where we need to buy from right to reach b_left, but a[r] is empty? That would mean we already consumed all right products. Then l would still be <= r? Actually if a[r] becomes zero, we decrement r, so if all right products are consumed, r becomes l-1, loop ends. But left product at l hasn't been bought. That would be a problem. So the algorithm must guarantee that we don't exit with left product remaining without having bought it. Let's check: When we are in else branch, we take from a[r]. If a[r] becomes zero, we decrement r, but we still have l <= r? Possibly after decrement, r could become less than l if that was the last product? Let's consider scenario: we have only one product left (l == r). If total_bought < b[l], we go to else, take from a[r] (which is the same product). We would be buying from the same product at full price? But the algorithm says take from r, which is the same product as l (since l == r). That would be buying from the product itself at full price. That is allowed. In the else branch, we buy from the rightmost product, which may be the same as leftmost if they are the same. So we are essentially buying from that product at full price (cost 2) to increase total_bought to reach its own b threshold. Then after we have taken enough, we may have bought some of it at full price, and then later (when total_bought >= b[l]) we will buy the remainder at discount. This handles the case where we need to buy some of a product at full price to trigger its own discount for the rest. That's exactly the splitting of a product into full price and discount portions. So the algorithm covers the situation where there aren't enough other products to reach threshold; we then use part of the current product itself as full price purchases.
Thus the algorithm works.
But is it optimal? The typical proof: we sort by b_i. The intuition is that it's always better to use items with higher b_i as "sacrificial" full-price purchases because they are less likely to ever become discounted; whereas items with lower b_i are more likely to become discounted if we can accumulate enough purchases. So we use the highest b_i items first to build up total count, thereby unlocking discounts for lower b_i items. And if we run out of high b_i items, we start buying the current low b_i item at full price to reach its threshold, then the rest at discount. This minimizes total full-price purchases.
Now, we must ensure that we don't miss the possibility of buying extra items at discount to further increase total and unlock discounts for even lower b_i items? Actually the algorithm already accounts for that: after we buy a left product at discount (cheap), that increases total_bought, which might help reach thresholds for later left products. That's good. Also, after we have bought some right product at full price, we reduce its required amount; later, when we get to that product as a left product (if it becomes the leftmost after processing all lower b_i), we might buy the remainder at discount if total_bought >= its b. That's exactly what happens when the pointer moves: eventually, the product that we partially bought from the right will become the leftmost after we finish all lower b_i products. At that point, its remaining quantity might be bought at discount if total_bought is already >= its b (which likely it will be because we have increased total_bought a lot). So that product gets some units at full price (the ones we took earlier) and the rest at discount.
Thus algorithm yields optimal cost.
Now, we need to implement. n up to 100k, a_i up to 1e14, sum a_i up to 1e14, so we need 64-bit integers. We'll sort pairs by b_i. Use two indices, left=0, right=n-1. total_bought = 0, cost = 0. While left <= right:
if total_bought >= b[left]:
// discount for left product
cost += a[left];
total_bought += a[left];
left++;
else:
// need to increase total_bought to b[left]
// but careful: we can only take from right if right >= left.
// Actually if left == right, we take from the same product.
// amount to take: need = b[left] - total_bought
// take = min(a[right], need)
// buy take items from right at cost 2 each
cost += take * 2;
total_bought += take;
a[right] -= take;
if a[right] == 0: right--;
Note: It's possible that need > 0 but a[right] may be 0? That's impossible because right always points to a product with positive a (since we decrement only when zero). So fine.
Edge Cases: b_i could be up to 1e14, total_bought up to sum a_i (<=1e14) plus possibly extras? Actually total_bought will not exceed sum of a_i plus maybe extra? But we only buy required a_i plus maybe extras? Wait, we are allowed to buy extra items. In the algorithm, we buy exactly the required a_i? Or do we ever buy extra? Let's check: The algorithm buys items from right at full price until we reach b[left]. Those items are from a[right] which are required quantities (we might buy part of them). Later, when we get to that product as left, we will buy the remaining quantity at discount (or possibly at full price if still not enough). But we never buy more than a_i for any product? Actually we only buy the exact a_i for each product (we may buy part at full price and part at discount). We do not buy extra items beyond required a_i. However, is it ever beneficial to buy extra items beyond the required a_i? Suppose we have a product with low b_i. After we meet its a_i, we might buy additional units of it at discount (cost 1) to increase total cheaply, which could help unlock discounts for other products with higher b_i. Could that reduce total cost? Possibly, because buying an extra unit at 1 ruble increases total by 1, and could save 1 ruble on a future purchase (by converting a full-price purchase to discount). But does the algorithm capture that? Let's test: If we buy an extra unit cheap, we pay 1 ruble (instead of 2) for that unit, but it might allow another unit to be bought at discount instead of full price, saving 1 ruble. So net effect could be zero? Actually buying an extra cheap unit costs 1, and it enables a discount on another unit saving 1 (converting from 2 to 1), so net zero? But maybe it enables multiple discounts? Let's think: Suppose we have product X that needs a_x units, and we have enough total already to get discount on X. So we buy all a_x at discount (cost a_x). If we buy an extra unit of X at discount (cost 1), total increases by 1, which might unlock discount for another product Y with threshold b_y. If without that extra unit, we would have to buy some units of Y at full price, but with extra unit, we can buy all Y at discount, saving something. For example, suppose we have Y with a_y = 1, b_y = total+1. Without extra, we would need to buy one unit of Y at full price (2) because total < b_y. If we buy an extra cheap unit of X (cost 1), total becomes total+1, which meets b_y, then we can buy Y at discount (1). So total cost without extra: 2 (full price for Y). With extra: 1 (extra X) + 1 (discount Y) = 2. Same cost. But we also have an extra unit of X that we didn't need. That seems wasteful. But maybe it could reduce cost if we need to buy multiple units of Y? Example: Y requires 2 units, b_y = total+1. Without extra, we might buy one unit at full price (2) to reach threshold, then the second at discount (1) -> total 3. With extra cheap unit of X (cost 1), total reaches b_y, then both Y at discount (2) cost 2, plus extra X cost 1 = 3 again. So net same. What if b_y = total+2? Then without extra, we might need to buy two units at full price (4) to reach threshold? But we could also buy one unit at full price, then total+1, still not enough for discount on second, but we could buy second at full price as well, total+2, then if there are more Y? Actually we need to satisfy Y's a_y. We could buy all Y at full price: cost 2*a_y. Alternatively, we could buy some other items at full price to raise total, then buy Y at discount. The extra cheap unit may be cheaper than buying an extra full-price unit of something else. For example, suppose we have no other products except Y and X. X has low b, already discount. We need to buy a_x and a_y. Suppose total before any purchases is 0. X's b is small, say b_x = 1. So after buying one item (any), X becomes discounted. But we must buy at least a_x of X. Perhaps we could buy one X at full price to trigger discount on X? But we might want to buy extra X at discount to raise total for Y. Let's construct: X: a_x=1, b_x=1; Y: a_y=1, b_y=2. If we buy X first at full price (cost 2), total=1, which meets b_x, then we could buy X's required (but we already bought it? Actually we bought X at full price, that counts as its a_x. So cost=2. Then total=1, not enough for Y discount. We need to buy Y: we could buy Y at full price (2) => total cost=4. Alternatively, we could buy X at full price (2), then buy an extra X (beyond required) at discount (cost 1) -> total=2, cost so far=3, then buy Y at discount (1) -> total cost=4. Same. Another alternative: buy Y first at full price (2), total=1, then buy X at discount (1) -> total=2, cost=3. That's better! So we see ordering matters. In this case, the optimal is to buy Y first (full price) to get total=1, then buy X at discount (1) cost total 3. That matches our two-pointer algorithm? Let's test: items: (a_x=1,b_x=1), (a_y=1,b_y=2). Sort by b: (1,1), (1,2). l=0 (b=1), r=1 (b=2), total=0. total< b[0]=1 -> else: need=1, take = min(a[r]=1,1)=1 => cost+=2, total=1, a[r]=0 -> r=0. Now total=1 >= b[0]=1 -> cost+= a[0]=1, total=2, l=1. Loop ends. cost=3. That's optimal. So algorithm didn't require buying extra items.
Now consider a case where buying extra might help? Suppose we have three items: A: a=1,b=100; B: a=100,b=101; C: a=100,b=101. Sorted by b: A (b=100), B (b=101), C (b=101). Algorithm: l=0 (b=100), r=2. total=0 <100 -> need=100, take from C (a=100) -> cost 200, total=100, a_C=0, r=1. Now total=100 >= b[0]=100, so buy A at discount: cost+=1, total=101, l=1. Now l=1 (B, b=101), r=1. total=101 >=101? Actually total=101, so buy B at discount: cost+=100, total=201, l=2. Loop ends. cost total = 200+1+100 = 301. But what about C? We bought all C at full price (200). B and A at discount (101). Total cost = 301. Could we do better by buying extra of A at discount to increase total to unlock B and C discounts? A's b=100, after we have 100 items, A becomes discounted. Its required a is 1. If we buy A's required 1 at discount (cost 1) after reaching 100, that gives total 101. But to reach 100, we needed to buy 100 items at full price. Those 100 could be from C. But after we have 101 total, B and C have b=101, so they become discounted. So we can buy B and remaining C at discount. But we already bought all C at full price, so no remaining C. So we bought C all at full price. What if we bought only part of C at full price, and then buy extra of A at discount to increase total? But A's required is only 1, but we could buy extra A (beyond required) at discount (cost 1 each). Suppose we aim to reach total 100 to unlock A discount. We need 100 items before any discount. We can buy some from C at full price and maybe some from B at full price? But they all cost 2. Once we reach 100, we can buy A (required 1) at discount (1) and also buy extra A at discount to increase total further cheaply. For each extra A, we pay 1 and increase total by 1. Then we can get to 101 cheaply, unlocking B and C discounts. Then we buy B and C at discount (1 each). So total cost: to reach 100, we need to buy 100 items at full price (2 each) = 200. But we might not need to buy all from C; we could buy, say, 50 from C and 50 from B at full price (cost 200). Then after reaching 100, we buy A (1) at discount =1, and we might need to buy extra A to get to 101? Actually after buying 100 full-price items, total=100. Then buy A's required 1 at discount -> total=101. That's enough to unlock B and C discounts. So we can then buy the remaining of B and C at discount. But we already used up all required quantities? If we bought 50 from C at full price, we still need to buy the remaining 50 of C. For B, we bought 50 at full price, need remaining 50. After total=101, we can buy the remaining 50 C and 50 B at discount: cost 50+50 = 100. So total cost = 200 (full) + 1 (A) + 100 (discount) = 301. Same as before. So extra A didn't help because we didn't need it; the required A already gave the extra 1 after discount.
What if A's b is high and its a is small? Already considered.
Another scenario: Suppose we have items with very low b and large a. For example, A: a=100, b=1; B: a=1, b=101. Sorting: A (b=1) then B (b=101). Algorithm: l=0 (b=1), total=0 <1? Actually b=1, total=0 <1, else: need=1, take from B (a=1) at full price: cost+=2, total=1, a_B=0, r=0 (since after removing B, r becomes 0? Actually initial l=0, r=1. After taking from B, a_B=0 -> r becomes 0. Now total=1 >= b[0]=1, so buy A at discount: cost+=100, total=101. Total cost=2+100=102. But could we do better? If we buy A first? Since b=1, after buying 1 item (any), A becomes discounted. So we could buy one A at full price (2) to reach total=1, then the remaining 99 A at discount (99) and B at discount (1) because total after buying 99 A would be 100? Wait let's compute: Alternative order: Buy one A at full price (cost 2, total=1). Now A is discounted. Then buy the other 99 A at discount (cost 99, total=100). At this point total=100, but B's b=101, not met. So we need one more purchase to reach 101. We could buy B at full price (2) -> total=101, cost additional 2 => total cost = 2+99+2 = 103. Or we could buy an extra A at discount (cost 1) to reach 101, then buy B at discount (1): cost extra 2 => total 2+99+1+1=103. So our algorithm gives 102 which is better. Actually the algorithm's cost 102: 2 for B full, then 100 for A discount. But A discount cost 100 for 100 items? A's required a=100, so discount cost 100. Total 102. The alternative we computed gave 103. So algorithm is optimal.
Now consider scenario where we might buy extra of low b product after discount to avoid buying some high b product at full price. For instance, suppose we have A: a=1, b=1; B: a=100, b=100; C: a=100, b=100. Sorted: A (1,1), B (100,100), C (100,100). Algorithm: l=0 (b=1), total=0<1 => need=1, take from C (100) -> cost+=2, total=1, a_C=99, r still 1? Actually r initially 2, after taking 1 from C, a_C=99, r remains 2 (since a_C>0). Then total>=1, buy A at discount: cost+=1, total=2, l=1. Now l=1 (b=100), total=2<100 => need=98, take from C: a_C=99, take=98 => cost+=196, total=100, a_C=1. Now total=100>=b[1]=100 => buy B at discount: cost+=100, total=200, l=2. Now l=2 (C, b=100), total=200>=100 => buy remaining C at discount: cost+=1, total=201. Total cost = 2+1+196+100+1 = 300? Let's compute: 2+1=3, +196=199, +100=299, +1=300. So cost=300.
What if we instead use extra A? A's a=1, but we could buy extra A at discount after reaching b=1. In algorithm, after we bought A (required) at discount, we could also buy extra A (not required) at discount to increase total cheaply. But is that beneficial? Suppose we buy A required at discount (1) then extra A at discount (1) to increase total to 2, then maybe we need less full price purchases from C to reach 100? Let's try alternative: Buy A at full price first? Actually A b=1, so after 1 purchase, discount. We need to get to total 100 to unlock B and C discounts. We could buy 99 items from C at full price (cost 198) to reach total 99+? Let's design: Start: buy A at full price (2) -> total=1, A discounted. Now we need to reach total 100. We could buy extra A at discount (cost 1 each) to increase total cheaply. But we can only buy A extra after discount, but we need to have total at least b=1, which we already have. So we can buy as many A as we want at 1 each. So we could buy, say, 99 extra A at discount (cost 99) to reach total 100. Then we have total=100, and we haven't bought any of B or C yet. Now we can buy B and C at discount (cost 100+100 = 200). But we also need to buy A's required 1, which we already bought at full price? Actually we bought one A at full price (2) which counts as required. So total cost = 2 (A full) + 99 (extra A discount) + 200 (B and C discount) = 301. That's worse than 300. What if we buy C at full price first, then A discount, then extra A discount? Let's compute: Buy 1 C at full price (2) -> total=1, A discount active. Then buy required A at discount (1) -> total=2. Then buy extra A discount 98 units (cost 98) -> total=100. Then buy remaining C (99) and B (100) at discount: cost 99+100=199. Plus earlier costs: 2+1+98+199=300. Same as 300? Actually 2+1=3, +98=101, +199=300. Yes 300. So same.
What if we buy no extra A, but use B and C full price partially: algorithm gave 300. So extra A doesn't help.
But consider scenario where a low b product has a large a, and high b products have small a. Maybe buying extra of low b after discount could reduce the number of high b full price purchases needed. Let's try to construct: Suppose we have low b product L: a_L=100, b_L=1. High b product H: a_H=1, b_H=100. According to algorithm sorted: L (100,1), H (1,100). l=0 (b=1), total=0<1 => need=1, take from H (a=1) full price: cost 2, total=1, a_H=0, r becomes? After removing H, r becomes? Initially n=2, l=0,r=1. After taking all of H, r becomes 0. Then total>=1, buy L at discount: cost+=100, total=101. Total cost = 102. Alternative: Could we do better by buying L at full price first? Buy 1 L at full price (2) -> total=1, L discount activated. Then buy remaining 99 L at discount (99) -> total=100. Then buy H at discount (1) because total=100? H's b=100, so after total=100, discount applies, so H costs 1. Total cost = 2+99+1 = 102. Same. So no improvement.
What about buying extra L after discount to reach 100? Already included.
Now consider scenario with multiple thresholds. It seems that buying extra beyond required never reduces total cost because extra purchases cost at least 1, and they increase total, potentially saving at most 1 per item that would otherwise be bought at full price. But saving is exactly 1 (converting a 2-cost to 1-cost). So if we spend 1 to get an extra item, we save 1 on some other item, net zero. But could it create a chain where we save more than 1? For each item that we convert from full to discount, we save 1. To convert that item, we need to increase total purchases before