C - 予算内での買い物 / Shopping Within Budget Editorial by admin Editorial for printing
DeepSeek V3Overview
This is a knapsack problem where we select items within a budget to maximize the total satisfaction. Each item can be purchased at most once.
Analysis
The problem is a classic knapsack problem where we select items within a budget of \(S - T\) yen to maximize the total satisfaction. It can be modeled as a “0-1 knapsack problem” where each item can be selected at most once.
A naive brute-force approach (trying the two choices of “buy/don’t buy” for each item) has a computational complexity of \(O(2^N)\), which is far too slow given the constraint \(N \leq 2000\). Therefore, we need to solve it efficiently using dynamic programming.
Algorithm
We solve this using dynamic programming. Specifically, we define the following:
- \(dp[j]\): the maximum satisfaction when using up to \(j\) yen of the budget
For each item, we update the budget \(j\) from the largest value downward (this prevents selecting the same item multiple times). For each item \((c, v)\), while decreasing \(j\) from \(budget\) down to \(c\), we apply the following recurrence:
\[ dp[j] = \max(dp[j],\ dp[j - c] + v) \]
Ultimately, the maximum value in the \(dp\) array is the desired answer.
Complexity
- Time complexity: \(O(N \cdot budget)\)
- Proportional to the product of the number of items \(N\) and the budget \(budget\)
- In the worst case, \(N = 2000\) and \(budget \leq 10^5\), resulting in approximately \(2 \times 10^8\) operations, which is barely feasible in Python with a fast implementation
- Space complexity: \(O(budget)\)
- We allocate a one-dimensional array of size equal to the budget
Implementation Notes
If the budget \(budget = S - T\) is negative, we immediately output 0 (since nothing can be purchased)
Instead of using a two-dimensional array, we update a one-dimensional array from back to front, reducing space complexity
By updating the inner loop from back to front, we prevent the same item from being selected more than once
Finally, we output the maximum value in the \(dp\) array (the maximum across all budget patterns)
Source Code
def main():
import sys
input = sys.stdin.read
data = input().split()
idx = 0
N = int(data[idx]); idx += 1
S = int(data[idx]); idx += 1
T_val = int(data[idx]); idx += 1
budget = S - T_val
items = []
for i in range(N):
c = int(data[idx]); idx += 1
v = int(data[idx]); idx += 1
items.append((c, v))
if budget < 0:
print(0)
return
dp = [0] * (budget + 1)
for c, v in items:
for j in range(budget, c - 1, -1):
if dp[j] < dp[j - c] + v:
dp[j] = dp[j - c] + v
print(max(dp) if budget >= 0 else 0)
if __name__ == "__main__":
main()
This editorial was generated by deepseekv3.
posted:
last update: