We need to find minimal total cost to buy N items with M discount tickets, where each ticket used on an item halves the price (floor division by powers of two). Tickets can be split across items arbitrarily. Equivalent: we have N numbers A_i, we can apply up to M total operations, where each operation on a number divides it by 2 (floor). But note that tickets can be used multiple on same item: using Y tickets on an item X reduces price to floor(X / 2^Y). The total cost is sum_i floor(A_i / 2^{k_i}) with constraint sum_i k_i <= M, k_i >= 0 integers. We want minimize sum.
N, M up to 1e5, A_i up to 1e9, so we need O((N+M) log something) or similar.
Intuition: To minimize total sum, we want to apply tickets to the largest numbers because halving a larger number yields larger absolute reduction (though not necessarily the best in terms of reduction per ticket? Actually, we need to consider that each ticket halves the current value, and the reduction from applying a ticket to a value X is X - floor(X/2) = ceil(X/2). So the reduction is about half of the current value. So the larger the current value, the larger the reduction. But after applying some tickets, the value becomes smaller, so subsequent tickets yield smaller reductions. So we need to decide where to allocate tickets to maximize total reduction from the initial sum. Equivalent to maximize sum_{i} (A_i - floor(A_i / 2^{k_i})). Given M tickets, we want to allocate them to numbers to maximize total reduction.
This is like a greedy: always apply a ticket to the item that gives the largest immediate reduction if we were to apply one additional ticket. That is, at each step, we compute for each item the reduction if we apply one more ticket (starting from current k_i), i.e., current_value - floor(current_value/2). Then pick the largest reduction, use a ticket on that item, update its value, and repeat. Since M up to 1e5 and N up to 1e5, we can simulate M steps with a max-heap of pairs (reduction, value, maybe current divisor exponent). However, we need to handle the fact that after applying a ticket, the reduction for the next ticket on that item changes. But we can compute the reduction for the next ticket: if current value is v, after applying one more ticket it becomes floor(v/2). The reduction is delta = v - floor(v/2). Then after that, new v = floor(v/2). The next reduction would be new_v - floor(new_v/2). So we can push new reduction each time.
The total steps M can be 1e5, so O(M log N) works.
But careful: The initial sum of A_i can be up to 1e14 (1e5 * 1e9 = 1e14). We need 64-bit.
So algorithm: Initialize a max-heap where each element is the reduction that would be achieved by using one ticket on that item currently. Initially, for each A_i, reduction = A_i - floor(A_i/2). But we also need to know the current value to compute next reduction. We can store in heap the current value, and compute reduction on the fly when popping? We'll need to know the value after applying ticket to compute new reduction. So we could store (current_value) in the heap, but ordering by reduction. However, reduction is derived from current_value: reduction = current_value - floor(current_value/2) = ceil(current_value/2). So actually if we store current_value, we can compute reduction. Since we want max-heap by reduction, we can use -current_value? Not directly: reduction = ceil(current_value/2) is monotonic increasing with current_value. For positive integers, larger current_value yields larger reduction. So the reduction is strictly increasing with current_value? Let's check: v1 > v2 => ceil(v1/2) >= ceil(v2/2). Yes, it's monotonic. So the item with the largest current_value also gives the largest reduction. So we can simply maintain a max-heap of the current values. Then at each step, pop the largest value v, apply a ticket: new_v = v//2 (floor division). Then push new_v back into heap. After M steps, we sum all values in the heap. However, is it always optimal to always apply the ticket to the largest current value? Because after applying a ticket, the value reduces by about half. But maybe applying a ticket to a smaller value could yield a bigger reduction if the larger value has been heavily discounted? But at each step, the reduction from using a ticket on a value v is ceil(v/2). Since this is increasing in v, the largest reduction always comes from the current largest value. So greedy of always picking the current largest value is optimal. This is a classic problem: we have a multiset of numbers, we can apply operation "replace x by floor(x/2)" up to M times to minimize sum. The greedy works because operation's benefit (reduction) is monotonic and each operation only affects one element. Indeed, it's like we have a priority queue and we repeatedly halve the largest element. This is a known solution.
But we should verify: If we had a scenario where we could apply two tickets to a large number, but maybe it's better to apply one to a large and one to another medium? But the greedy of always picking the largest current value works because it's like we are maximizing the immediate reduction at each step, and the operation doesn't affect other items. Since there is no future dependence except the value itself, the greedy is optimal.
However, there might be nuance: when v=1, floor(v/2)=0, reduction=1. When v=0, reduction=0. So eventually all become 0. So we can stop early if max becomes 0, but M up to 1e5 and A_i up to 1e9 so not too many steps.
Thus we can simulate M times: each time extract max, replace with floor(max/2), then continue. Finally sum all values in the heap.
But careful: initial heap contains N values. After M operations, we will have N values (some modified). Sum them.
Time: O((N+M) log N) which is fine for 1e5.
Edge Cases: M may be larger than needed to bring all numbers to 0. But we can break early if max is 0, as further tickets do nothing. However, simulation up to M=1e5 is okay; but if M=1e5 and numbers are huge, max won't become 0 quickly (1e9 halved ~30 times gives 0). So at most ~30*N operations? Actually each number can be halved at most log2(1e9) ~ 30 times before reaching 0. So total possible tickets that affect sum is at most N * 30 = 3e6, which might be more than M (max 1e5). So M is less than that; but if M were larger than total beneficial tickets (like 1e9), we would need to break early. But M <= 1e5, so it's fine. However, we must consider N=1e5 and M=1e5, each number may be halved many times, but we only do M operations total. So M operations each O(log N) ~ 17, so about 1.7 million operations, fine.
Thus solution: Use a max-heap (priority queue) implemented as negative values for min-heap.
Pseudo:
read N, M
A = list(map(int, input().split()))
import heapq
heap = [-a for a in A]
heapq.heapify(heap)
for _ in range(M):
max_val = -heapq.heappop(heap)
if max_val == 0:
# if all zeros, break
heapq.heappush(heap, 0) # push back or break? Actually we popped, need to maintain size N. But if max_val is 0, all other are 0 because max is 0 => all zeros. So we can push back 0 and break, but sum will be 0 anyway. Simpler: push back 0 and continue, but since M might be large, we can break to avoid useless ops.
break
new_val = max_val // 2
heapq.heappush(heap, -new_val)
total = sum(-v for v in heap)
print(total)
Check examples:
Example1: N=3 M=3, A=[2,13,8]
Heap: 13,8,2
Step1: pop 13, new=6 -> push 6 => heap:8,6,2
Step2: pop 8, new=4 -> push 4 => heap:6,4,2
Step3: pop 6, new=3 -> push 3 => heap:4,3,2
Sum=4+3+2=9. Output 9. OK.
Example3: 1 100000, A=1e9 => repeatedly halve. After ~30 steps becomes 0, then rest do nothing. Sum 0. Output 0.
Example4: 10 1, all 1e9. Largest is 1e9, after one ticket: 5e8, sum = 9*1e9 + 5e8 = 9.5e9 = 9500000000. OK.
So greedy works.
But is there any catch? Let's test more: if two numbers equal, it doesn't matter which we choose. The reduction is same. So okay.
We should consider whether there is any benefit to using multiple tickets on the same item at once vs spreading? Since greedy picks the largest each time, it will naturally allocate tickets to the same item if it remains the largest after halving. So it's equivalent to a multistage process.
Thus solution is straightforward.
But wait, can there be a scenario where the reduction is not monotonic with current value? For example, if v=3, reduction = 3 - 1 = 2 (since floor(3/2)=1). v=2, reduction = 2 - 1 =1. v=1, reduction=1-0=1. Actually v=2 reduction 1, v=1 reduction 1. So v=2 and v=1 yield same reduction. But v=3 gives 2 > 1. So larger v gives larger or equal reduction? v=1 vs v=2: v=2 gives reduction 1, v=1 gives reduction 1. So monotonic non-decreasing? Indeed ceil(v/2) is non-decreasing. So the largest value gives at least as much reduction as any smaller. So greedy optimal.
Hence algorithm is sound.
Potential optimization: use heap of negative values; simple.
Now, we must consider possible integer overflow in Python? Python integers arbitrary precision, fine.
Time complexity: O((N+M) log N). Works.
But wait, the constraints: N, M <= 10^5. However, there might be a more efficient approach using counting sort or something, but not needed.
Double-check: Is there any scenario where using a ticket on a number with value 1 yields reduction 1, and on another with value 2 also yields reduction 1, but using on 2 might allow later to have larger reductions? But greedy already picks the largest, so if both have same reduction but one is larger value? Actually if both have same reduction, they are equally good from immediate reduction perspective. But we need to think about future: maybe using on a 2 (value 2) leaves it at 1, which still can yield reduction 1 if we use another ticket. Using on a 1 yields reduction 1 and leaves it at 0, which yields no further reduction. So from a future perspective, using on a 2 might be better because it leaves a value that can be further reduced. But if we have a choice between a 2 and a 1, both give immediate reduction 1, but the 2 after reduction becomes 1, still could be used again. The 1 becomes 0. So maybe it's better to apply the ticket to the 2 to preserve potential for future reductions. But in greedy by current value, if we have values 2 and 1, the larger current value is 2, so greedy picks 2. So that's good. However, what about values 2 and 2? both same. So any choice fine.
What about values 3 and 4? 4 reduction = 2, 3 reduction = 2? Actually 4 - 2 = 2, 3 -1 =2. Both give reduction 2. Larger current value is 4, so greedy picks 4. But after halving, 4 becomes 2 (value 2), 3 becomes 1. Both still have potential? The 2 can be further reduced to 1 (reduction 1), 1 can be reduced to 0 (reduction 1). So similar. But if we had chosen 3 first, it becomes 1, leaving 4 unchanged; then next step we would pick 4 (reduction 2) then later maybe 2? Actually sequence: choices: pick 4 first: state: (2,3) -> then pick 3? Actually after first: 4->2, so values: 3,2? Wait original: [4,3]. Step1: pick 4 -> new=2 => [3,2]. Step2: pick larger is 3 -> new=1 => [2,1]. Step3: maybe pick 2 -> new=1 => [1,1] etc. Alternatively, if we had picked 3 first: state: 4,1 -> then pick 4 -> new=2 => [2,1] -> then pick 2 -> new=1 => [1,1]. So total reductions: using greedy gives reductions: step1: from 4 (2), step2: from 3 (2) = total reduction 4 after two tickets. Alternative gives step1: from 3 (2), step2: from 4 (2) = also 4. So same. So it's fine.
Consider values: 5 and 6? 6 reduction=3, 5 reduction=3? floor(6/2)=3 reduction=3; floor(5/2)=2 reduction=3. Both 3. Larger is 6, greedy picks 6. After halving: 6->3, so [5,3] -> then pick 5 reduction=3 -> [3,2]? Actually 5->2, so [3,2] total reduction after two: 3+3=6. Alternative: pick 5 first: [6,2] -> then pick 6: reduction=3 -> [3,2] total reduction also 6. So fine.
Thus greedy works.
One might think: we should consider not only immediate reduction but also the fact that using a ticket on a value reduces it to floor(v/2), which might still be large and yield more future reductions. But picking the largest current value ensures that after reduction, the new value is still likely among the larger ones. The standard proof by exchange argument: consider an optimal allocation of tickets. If at some step there is an item i with more tickets than greedy would assign relative to another, we can swap a ticket from a smaller value to a larger value and not increase total sum. Since the reduction function is convex? Actually we can prove by noting that the cost function after applying k tickets to an item is floor(A/2^k). This is a decreasing convex function in k? We want to minimize sum, i.e., maximize total reduction. The reduction per ticket is decreasing as k increases. So we want to allocate tickets to items with highest marginal reduction, which is exactly the greedy of picking current largest.
So the algorithm is correct.
Implementation details:
Use heapq with negative values to simulate max-heap.
Loop for _ in range(M):
v = -heapq.heappop(heap)
if v == 0: break # because all zeros, push back 0? Actually if v is 0, then all others are 0 as well because max is 0. So we can break and push back? But we popped one, we need to keep the heap size N. So either push back 0 and break, or break and later sum includes missing element? We popped one, so if we break without pushing back, the heap size becomes N-1, and we lost that zero. So we should push back 0 before breaking. Alternatively, we can just avoid breaking and continue; since v==0, new_val = 0//2 = 0, push 0 back, then the heap remains all zeros. Next iterations do nothing. So we can just not break; it's fine because M up to 1e5, and after all become zero, each iteration does pop 0 and push 0, O(log N) but if M is huge (like 1e9) might be problematic. But M is only 1e5, so even if we do M iterations after zeros, it's fine. So we can simply always do the loop without break. But to be safe, we could break if v == 0, because then all are zero; but we need to maintain heap size. So we can push back 0 and break.
new_v = v // 2
heapq.heappush(heap, -new_v)
After loop, compute sum = sum(-x for x in heap).
Time O((N+M) log N). N and M 1e5 => at most 200k * log2(100k) ~ 200k * 17 = 3.4 million operations, fine.
Now consider large M where M might be larger than total beneficial tickets. But still within 1e5, it's okay.
But check input constraints: M can be as high as 1e5, but each item can be halved up to 30 times to become 0. So total beneficial tickets <= 30*1e5 = 3e6, which is larger than M. So M is not extremely large relative to that. Even if M were 1e6, still okay. So no issue.
Thus solution is done.
We should also consider alternative: using a multiset or a sorted list and always halve the max. But heap is simplest.
Edge Cases: N=0? Not possible because N>=1.
M=0: we just sum A_i.
Now, is there any scenario where using tickets in a different order yields better? E.g., using two tickets on same item at once yields floor(A/4) vs using one on one item and one on another? But greedy of picking the largest each step effectively does the same as considering each ticket individually; it's like repeatedly halving the current maximum. This is equivalent to doing binary reduction in any order as long as we always apply to the current max.
But is there any scenario where we should save tickets for later? No, because the reduction of a ticket on any item is independent of when you use it? Actually, if you apply a ticket earlier, the value becomes smaller, so subsequent tickets on that item yield smaller reductions. But if you apply tickets later, the value is still larger, so the reduction from each ticket might be larger. That might suggest that it's better to spread tickets across different items first to keep values larger? However, the greedy method always picks the current largest, which is the best immediate reduction. But could there be a scenario where using a ticket on a slightly smaller item now yields a larger total reduction in the long run because it allows the larger item to remain large for a future ticket? Let's examine.
Suppose we have two items: A=10, B=8. M=2 tickets. Greedy: pick 10 -> becomes 5 (reduction 5). Now items: 8 and 5. Next pick 8 -> becomes 4 (reduction 4). Total reduction = 9, final sum = (5+4)=9? Wait initial sum 18, reduction 5+4=9, final sum 9. Alternative: use first ticket on 8 -> becomes 4 (reduction 4). Items: 10 and 4. Second ticket on 10 -> becomes 5 (reduction 5). Total reduction 9, final sum 9. Same.
Now try A=9, B=6, M=2. Greedy: pick 9 -> becomes 4 (reduction 5) -> [6,4] -> pick 6 -> becomes 3 (reduction 3) total reduction 8, final sum = 4+3=7, initial 15 so reduction 8. Alternative: pick 6 first -> becomes 3 (reduction 3) -> [9,3] -> pick 9 -> becomes 4 (reduction 5) total reduction 8. Same.
Now try A=7, B=6, M=2. Greedy: 7->3 (reduction 4) -> [6,3] -> 6->3 (reduction 3) total reduction 7, final sum =3+3=6, initial 13 so reduction 7. Alternative: 6->3 (reduction 3) -> [7,3] -> 7->3 (reduction 4) total reduction 7. Same.
Now try A=3, B=3, M=2. Greedy: pick 3->1 (reduction 2) -> [3,1] -> pick 3->1 (reduction 2) total reduction 4, final sum 1+1=2, initial 6. Alternative: same. Good.
Now what about more tickets than items? Suppose A=10, B=1, M=2. Greedy: pick 10->5 (red5), then pick 5->2 (red3) final: [2,1] sum=3. Alternative: pick 10->5, then pick 1->0 (red1) final: [5,0] sum=5. Greedy yields lower sum (3) because it used second ticket on the 5 rather than on 1. So greedy better.
But could there be a case where using a ticket on a smaller item now yields a larger sum later? The greedy always picks the largest, so it will use second ticket on 5 instead of 1, which is better. So fine.
Now try A=8, B=5, M=2. Greedy: 8->4 (red4), then pick 5->2 (red3) final [4,2] sum=6. Alternative: 5->2 (red3), then 8->4 (red4) same sum=6.
Now try three items: A=100, B=99, C=98, M=2. Greedy: 100->50, then 99->49, final 50+49+98=197. Alternative: 99->49, 98->49, final 100+49+49=198. So greedy yields 197. Is there a better? 100->50, 98->49 gives 50+99+49=198. So greedy best. Good.
Now think about scenario where the reduction from the second ticket on a large item might be less than the reduction from first ticket on a medium item if we have already heavily discounted the large item. But greedy will then pick the medium item when its current value becomes larger than the halved large item. So it's adaptive.
Thus greedy is optimal.
We can also consider that the problem is equivalent to: we want to minimize sum floor(A_i / 2^{k_i}) subject to sum k_i <= M. This is like we have a set of items each with a convex cost reduction per ticket. The optimal solution is to allocate tickets to items where the marginal benefit (i.e., reduction from an additional ticket) is highest. Since marginal benefit for item i after k tickets is f_i(k) = floor(A_i / 2^k) - floor(A_i / 2^{k+1}) = something like maybe not exactly but it's decreasing in k. The greedy algorithm that always picks the current highest marginal benefit corresponds to using a priority queue of these marginal benefits. And since the marginal benefit from the next ticket on an item only depends on its current value, it's equivalent to maintaining a max-heap of current values.
But note: The marginal benefit when current value is v is v - floor(v/2) = ceil(v/2). That is exactly the reduction we used. So yes.
Thus algorithm is correct.
Potential issues: Need to ensure we handle large sums: use Python int.
Now we produce final solution.
But wait: Input format: first line N M, second line A_i. So reading accordingly.
Also we might use sys.stdin.read to be faster.
We'll implement:
import sys
import heapq
def solve():
data = sys.stdin.read().split()
if not data:
return
it = iter(data)
N = int(next(it))
M = int(next(it))
A = [int(next(it)) for _ in range(N)]
heap = [-a for a in A]
heapq.heapify(heap)
for _ in range(M):
v = -heapq.heappop(heap)
if v == 0:
# all zeros, push back and break?
heapq.heappush(heap, 0) # push back 0
break
v //= 2
heapq.heappush(heap, -v)
# if we break early, there may be remaining iterations not done but it's okay
total = sum(-x for x in heap)
print(total)
if name == "main":
solve()
We should test with given examples.
But let's manually test with example3: N=1, M=100000, A=1000000000. Heap: -1e9. Loop: each time we pop, compute v//2. After about 30 iterations, v becomes 0. Then we push 0. Next iteration we pop 0, push 0. That will continue 100000 times, but it's fine. But we could break if v==0 to avoid useless work. With M=100000 and N=1, after 30 steps it's zero, but then we still loop 99970 more times, each time popping and pushing 0. That's fine. But for larger M, say M=1e9 (but M max 1e5). So fine.
Alternatively, we can improve by checking if max is 0, we break. But not necessary.
Now, consider scenario where after some operations, the heap contains many zeros. The max could be zero if all zero. So if v becomes 0, then all are 0. So we can break.
Implementation with break:
for _ in range(M):
v = -heapq.heappop(heap)
if v == 0:
heapq.heappush(heap, 0)
break
heapq.heappush(heap, - (v//2))
But if we break, we must also consider that there might be other items non-zero? Actually if popped v is 0 and it came from max-heap, then all items are <=0? Since we store negative, the smallest negative corresponds to largest positive. So when we pop the smallest negative (most negative), that corresponds to largest positive. If that is 0, then all are 0. So yes, break.
But what if we had a case where some items are positive and some zero? Could the largest be zero? Only if all are zero. Because if any positive exists, largest positive >0, so popped v would be >0. So break safe.
Thus break saves time if M large relative to needed tickets. But M is 1e5, not huge.
Now final answer: print total.
Edge Cases: M might be greater than the number of tickets we can effectively use? We apply M operations; if after applying all beneficial operations we still have tickets left, numbers will be zero and further tickets do nothing. So final sum could be zero. Our loop will handle that.
Now, consider memory: heap of size N, fine.
Now, I should produce final solution code.
But wait: There is a nuance: The tickets can be used any number on an item, but the rounding down is floor division by 2^Y. That is the same as repeated floor division by 2. So our model is correct.
Thus answer done.
But before finalizing, let's double-check with some random tests using brute force for small N and M to ensure greedy is indeed optimal. We'll do mental test with N=2, M=2, values like 5 and 4. All combinations: k1,k2 >=0, k1+k2<=2.
A=5,4:
(0,0): sum=9
(1,0): 5//2=2 + 4 =6
(0,1):5 + 4//2=2 ->7? Actually 4//2=2, sum=7
(2,0):5//4=1 +4=5
(0,2):5 + 4//4=1=6
(1,1):2+2=4
So min=4. Greedy: initial heap:5,4. Step1: pop5->2 => [4,2]; step2: pop4->2 => [2,2] sum=4. OK.
Now N=2, M=3, A=5,4:
All possibilities: k1+k2<=3.
We can compute all:
k1,k2:
(3,0):5//8=0+4=4
(2,1):1+2=3
(1,2):2+1=3
(0,3):5+0=5
(3,0):4 as above
(2,0) already 5? Actually (2,0) sum=1+4=5
(0,2):5+1=6
(1,1):2+2=4
(2,1):1+2=3 min=3.
Greedy: start 5,4
Step1:5->2 => [4,2]
Step2:4->2 => [2,2]
Step3:2->1 (pop largest 2) => [2,1]? Actually after step2 heap:2,2. Step3: pop one 2->1 push1 => heap:2,1 sum=3. Works.
One more tricky case: maybe we should consider that using two tickets on the same item yields floor(A/4) which could be less than using one on each of two items: floor(A1/2)+floor(A2/2). But greedy would consider that because it picks one at a time.
Thus solution final.
Now we can write the answer.
However, I recall a known problem from AtCoder: "Discount Tickets" or something similar? Actually it might be from ABC 141 D? No, that was "Powerful Discount Tickets" where tickets are applied to prices and each ticket halves the price (rounded down) but there was a twist: there were multiple items and each ticket can be used on any item, and the solution was to use a max heap. Yes, that's a classic AtCoder problem: "Expedition" or "Buying Items"? It's from ABC 141 D: "Powerful Discount Tickets". I recall that problem: "Takahashi is going to buy N items, each with price A_i yen. He has M tickets. If he uses a ticket on an item, its price becomes half (rounded down). He can use any number of tickets on an item. Minimize total cost." The solution: use a max-heap and pop the largest, halve it, push back, repeat M times. Exactly.
Thus answer done.
Now produce final answer.
But we need to ensure we account for possible large M relative to N but our code is fine.
Now, potential pitfalls: The heap with negative numbers; when we pop and push, we need to ensure we maintain correct sign.
One might also consider using a binary search approach? Not needed.
Thus final solution.
Now I will produce final answer: explanation plus code.
In the response, I should give a clear explanation and Python code.
Since the user asked: "Takahashi is going to buy N items one by one. ... Print the minimum amount of money required to buy all the items." So I will output code in Python.
I will also include some comments.
Now final answer. We can use a greedy strategy: always apply a discount ticket to the currently most expensive item.
The reduction achieved by using a ticket on an item of price (X) is (\left\lceil\frac{X}{2}\right\rceil), which is larger when (X) is larger.
Applying a ticket to the current maximum gives the best immediate reduction, and because future reductions only depend on the current prices, this greedy choice is optimal.
We maintain a max‑heap of the current prices. For each of the (M) tickets:
Pop the largest price (v).
Replace it with (\left\lfloor\frac{v}{2}\right\rfloor).
Push the new value back.
After processing all tickets (or when all prices become (0) and further tickets do nothing), the sum of the heap is the minimum total cost.
The algorithm runs in (O((N+M)\log N)), which is fast for the given constraints ((N, M \le 10^5)).
python
import sys
import heapq
def solve() -> None:
data = sys.stdin.read().split()
if not data:
return
it = iter(data)
N = int(next(it))
M = int(next(it))
A = [int(next(it)) for _ in range(N)]
# max‑heap via negative values
heap = [-a for a in A]
heapq.heapify(heap)
for _ in range(M):
v = -heapq.heappop(heap) # current largest price
if v == 0: # all prices are already 0
heapq.heappush(heap, 0)
break
heapq.heappush(heap, -(v // 2))
total = sum(-x for x in heap)
print(total)
if __name__ == "__main__":
solve()