C - 予算内での買い物 / Shopping Within Budget Editorial by admin Editorial for printing
GPT 5.2 HighOverview
This is a problem of finding the maximum total satisfaction when selecting at most one of each item within a usable budget of \(W = S - T\) yen. It can be solved as a classic 0/1 knapsack problem.
Analysis
First, since “you must keep \(T\) yen for living expenses,” the actual spending limit is \(W = S - T\) yen. If \(W \le 0\), you cannot buy anything, so the answer is \(0\).
A naive approach of exhaustively searching “buy/don’t buy” for each item would result in \(2^N\) combinations. With \(N \le 2000\), this is far too slow (TLE).
Instead, we use dynamic programming to track the “maximum satisfaction obtainable for each budget (weight).” An important note here is the condition that each item can be selected at most once. If we update the budget from the smaller side, we would reference states where the same item has been used multiple times (turning it into an unbounded knapsack), resulting in WA. Therefore, we update \(w\) from the larger side.
Example: Consider \(W=5\) and an item \((c=3, v=10)\): - Updating from the larger side, \(dp[5]\) can reference \(dp[2]+10\) as a state where “this item is used exactly once” - Updating from the smaller side, the already-updated \(dp[2]\) may include the same item, potentially resulting in the same item being used multiple times
Algorithm
We perform 0/1 knapsack DP.
- Set the budget limit as \(W = S - T\)
- Prepare an array \(dp[w] =\) “maximum satisfaction obtainable with a total cost of at most \(w\) yen” (all initial values are \(0\))
- For each item \((C_i, V_i)\), iterate \(w\) from \(W\) down to \(C_i\) in descending order and update:
- \(dp[w] = \max(dp[w], dp[w - C_i] + V_i)\)
Finally, \(dp[W]\) is the answer (since it has been updated to maximize satisfaction within the budget).
Complexity
- Time complexity: \(O(NW)\) (\(W = S - T \le 10^5\))
- Space complexity: \(O(W)\)
Implementation Notes
If \(W = S - T\) is \(0\) or less, immediately output \(0\)
The update loop for each item must always be in descending order (from \(W\) to \(C_i\)) (to maintain the 0/1 constraint)
Items with \(C_i > W\) cannot be purchased anyway, so skipping them reduces unnecessary work
Since \(V_i\) can be up to \(10^9\), the total can become large, but Python’s
inthandles this without issuesSource Code
import sys
def main():
it = iter(sys.stdin.buffer.read().split())
N = int(next(it))
S = int(next(it))
T = int(next(it))
W = S - T
if W <= 0:
print(0)
return
dp = [0] * (W + 1)
for _ in range(N):
c = int(next(it))
v = int(next(it))
if c > W:
continue
d = dp
for w in range(W, c - 1, -1):
nv = d[w - c] + v
if nv > d[w]:
d[w] = nv
print(dp[W])
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.2-high.
posted:
last update: