C - お菓子の購入 / Buying Sweets Editorial by admin
Claude Opus 5 (High)Overview
This problem asks us to choose exactly \(K\) snacks in total from \(N\) types of snacks (each with a stock of \(A_i\) and a satisfaction value of \(B_i\) per item) to maximize the sum of satisfaction values. It is a typical greedy algorithm problem (similar to the fractional knapsack problem), where we should greedily take snacks with larger satisfaction values as much as stock allows.
Analysis
Feasibility Check
Whether we can buy \(K\) snacks depends solely on whether the total stock \(A_1 + A_2 + \dots + A_N\) is at least \(K\).
- When \(\sum A_i < K\): It is impossible to buy \(K\) snacks by any means, so the answer is \(-1\).
- When \(\sum A_i \ge K\): Since we can freely choose any total count from \(0\) to \(\sum A_i\) in increments of 1, there always exists a combination to buy exactly \(K\) snacks.
Note that \(\sum A_i\) can be up to \(2\times 10^5 \times 10^9 = 2 \times 10^{14}\), which requires a 64-bit integer (in Python, arbitrary-precision integers handle this automatically, but in C++, use long long).
Maximization Strategy
The action of “buying one snack \(i\)” is completely independent, granting \(B_i\) satisfaction per snack bought. The only constraints on the counts are “exactly \(K\) in total” and “at most \(A_i\) per type”, with no interactions such as “buying snack 1 prevents buying snack 2”.
In other words, this is equivalent to the problem of “choosing a total of \(K\) items from piles where each pile has \(A_i\) items of value \(B_i\), maximizing the total value”. Therefore, it is optimal to pick items in descending order of value.
Proof sketch by exchange argument: Suppose in some optimal solution, there exist snacks such that \(B_i > B_j\), yet \(x_i < A_i\) and \(x_j > 0\) (where \(x_k\) is the number of snack \(k\) purchased). If we decrease the count of snack \(j\) by 1 and increase the count of snack \(i\) by 1, the total number of snacks remains \(K\), but the total satisfaction increases by \(B_i - B_j > 0\). This contradicts the optimality of the solution. Therefore, in an optimal solution, we must completely exhaust the stock of snacks with larger \(B\) before moving to snacks with smaller \(B\).
Why Naive Approaches Fail
- DP: If we consider a DP tracking “the maximum satisfaction when buying \(j\) items”, the number of states explodes because \(K \le 10^9\), which will exceed both time and memory limits.
- Greedy one by one: An implementation using a priority queue to repeatedly “buy 1 snack with the currently largest \(B\)” \(K\) times would take \(K \le 10^9\) iterations, resulting in TLE.
The solution is to “sort in descending order of \(B\) and buy each snack in bulk (all at once up to its stock)”. Instead of picking one by one, processing “buy \(\min(A_i, \text{remaining items})\) items at once” requires only \(N\) iterations.
Algorithm
- Read the input, construct an array of pairs \((B_i, A_i)\), and compute the total stock
total. - If
total < K, output \(-1\) and terminate. - Sort the array in descending order of \(B\).
- Set the remaining number of items to buy as
rem = K, and iterate through the array from the beginning:- Buy
t = min(A_i, rem)items. - Update
ans += t * B_iandrem -= t. - If
rem == 0, break out of the loop.
- Buy
- Output
ans.
Example
Consider \(N=3, K=5\), and \((A,B) = (2, 10), (1, 7), (4, 3)\).
The total stock is \(2+1+4=7 \ge 5\), so it is feasible. In descending order of \(B\), we have \((10,\,A=2), (7,\,A=1), (3,\,A=4)\).
- For \(B=10\): buy \(\min(2,5)=2\) items \(\to ans = 20\), \(rem = 3\)
- For \(B=7\): buy \(\min(1,3)=1\) item \(\to ans = 27\), \(rem = 2\)
- For \(B=3\): buy \(\min(4,2)=2\) items \(\to ans = 33\), \(rem = 0\)
The answer is \(33\).
Complexity
- Time complexity: \(O(N \log N)\) (dominated by sorting. The feasibility check and the greedy loop take \(O(N)\))
- Space complexity: \(O(N)\)
Implementation Notes
Beware of overflow: The answer can be up to around \(K \times \max B_i \le 10^9 \times 10^9 = 10^{18}\). In C++, use
long long(unsignedis not necessary, butintis insufficient). The same applies to the total stock \(\sum A_i\). In Python, integers have arbitrary precision, so this is not an issue.Sorting key: Sort in descending order of \(B\). Creating tuples
(b, a)and callingsort(reverse=True)sorts them by \(B\) descending (the tie-breaking order for the same \(B\) does not affect the result).Early exit: Break out of the loop when
remreaches \(0\) (even without breaking,t=0would keep the answer correct, but it avoids unnecessary computations).Fast I/O: Since \(N\) can be up to \(2\times 10^5\), in Python it is safer to read all input at once using
sys.stdin.buffer.read().split()rather than callinginput()line by line.Do not forget the \(-1\) check: Handle the case where the total stock is strictly less than \(K\) beforehand. Forgetting this check will cause the greedy loop to buy all available stock and erroneously output an answer even when fewer than \(K\) items were bought.
Source Code
import sys
def main():
data = sys.stdin.buffer.read().split()
n = int(data[0]); k = int(data[1])
items = []
total = 0
for i in range(n):
a = int(data[2 + 2*i]); b = int(data[3 + 2*i])
total += a
items.append((b, a))
if total < k:
print(-1)
return
items.sort(reverse=True)
ans = 0
rem = k
for b, a in items:
if rem <= 0:
break
t = a if a < rem else rem
ans += t * b
rem -= t
print(ans)
main()
This editorial was generated by claude5opus-high.