Official

C - 予算内での買い物 / Shopping Within Budget Editorial by admin Editorial for printing

Gemini 3.1 Pro (Thinking)

Overview

This is a classic “0-1 Knapsack Problem” where we maximize the total satisfaction within the effective budget of \(S - T\) yen available for purchasing products.

Analysis

First, the maximum amount Takahashi can spend on products is \(W = S - T\) yen. The goal is to select some products from the \(N\) types within this \(W\) yen budget to maximize the total satisfaction.

Each product has two choices: “buy” or “don’t buy,” and at most one of each can be purchased. A naive brute-force approach trying both choices for every product would result in \(2^N\) combinations. Given the constraint \(N \leq 2000\), the computational complexity of \(O(2^N)\) would certainly result in a Time Limit Exceeded (TLE) verdict.

This type of problem — “selecting items with given values and weights without repetition to fit into a knapsack of fixed capacity” — can be solved efficiently using Dynamic Programming (DP).

Algorithm

We find the solution using dynamic programming (DP) with a 1-dimensional array.

  1. Budget Calculation Compute the available budget \(W = S - T\).
  2. DP Table Definition Prepare an array dp of length \(W + 1\), initializing all elements to \(0\). Here, dp[j] represents “the maximum satisfaction achievable when spending at most \(j\) yen in total.”
  3. DP Transitions For each product (price \(C_i\), satisfaction \(V_i\)), update the dp array one product at a time. Loop the budget \(j\) from \(W\) down to \(C_i\) in descending order (from larger to smaller), updating with the following recurrence: $\(dp[j] = \max(dp[j], dp[j - C_i] + V_i)\)$
    • \(dp[j]\): maximum satisfaction when not buying product \(i\)
    • \(dp[j - C_i] + V_i\): maximum satisfaction when buying product \(i\)

[Why loop in descending order?] If we loop in ascending order (from smaller to larger), the same product could be counted as bought more than once in the computation (turning it into an unbounded knapsack problem). By updating in descending order, we ensure that “the result of computing the current product” does not affect subsequent computations for the same product, thus maintaining the constraint that each product can be selected at most once. 4. Output the Answer After processing all products, the value of dp[W] is the desired maximum satisfaction.

Complexity

  • Time complexity: \(O(N \times (S - T))\) For each of the \(N\) products, we loop at most \(S - T\) times.
  • Space complexity: \(O(S - T)\) Since we use only a single 1-dimensional array of length \(S - T + 1\), memory usage is kept very low.

Implementation Notes

  • Memory savings with a 1-dimensional array Textbook DP often uses a 2-dimensional array dp[i][j], but when only the previous state’s array is needed for computation (as in this case), we can overwrite a 1-dimensional array to significantly reduce space complexity.

  • Speeding up input In Python, reading large inputs line by line with input() can be slow. Therefore, we use sys.stdin.read().split() to read all input at once, reducing execution time.

  • Overflow caution (for other languages) The satisfaction \(V_i\) can be up to \(10^9\), and with 2000 products, the total can reach up to \(2 \times 10^{12}\). Python handles integer overflow automatically, but when implementing in C++ or Java, you need to use 64-bit integers (long long, etc.) instead of 32-bit integers (int).

    Source Code

import sys

def solve():
    input = sys.stdin.read
    data = input().split()
    if not data:
        return
    
    N = int(data[0])
    S = int(data[1])
    T = int(data[2])
    
    W = S - T
    
    if W < 0:
        print(0)
        return
        
    dp = [0] * (W + 1)
    
    idx = 3
    for _ in range(N):
        c = int(data[idx])
        v = int(data[idx+1])
        idx += 2
        
        if c <= W:
            for j in range(W, c - 1, -1):
                if dp[j - c] + v > dp[j]:
                    dp[j] = dp[j - c] + v
                    
    print(dp[W])

if __name__ == '__main__':
    solve()

This editorial was generated by gemini-3.1-pro-thinking.

posted:
last update: