Official

C - お菓子の購入 / Buying Sweets Editorial by admin

Gemini 3.8 Flash (High)

Overview

This problem asks us to find the maximum possible total satisfaction obtained when purchasing exactly \(K\) pieces of snacks from \(N\) types of snacks in total. If the total stock across all snacks is less than \(K\), output \(-1\).

Analysis

Strategy for Maximizing Satisfaction

For each snack \(i\), the satisfaction gained per piece, \(B_i\), is constant. Therefore, to maximize total satisfaction, the optimal strategy is a greedy one: “prioritize snacks with a larger satisfaction \(B_i\) per piece and buy as many as possible.”

For example, consider the following situation: - Snack 1: Stock 3, satisfaction 10 - Snack 2: Stock 5, satisfaction 5 - Target number to purchase \(K = 4\)

In this case, we buy as many pieces of Snack 1 (which has higher satisfaction) as possible (3 pieces), and buy the remaining 1 piece from Snack 2. This yields a total satisfaction of \(3 \times 10 + 1 \times 5 = 35\), which is maximized.

Naive Approaches and Challenges

  • Dynamic Programming (DP): If we consider a DP approach with the number of purchased snacks or the satisfaction as states, since \(K \le 10^9\), the table size becomes enormous, exceeding both the memory limit and the time limit.
  • Simulating One Piece at a Time: If we pick snacks one by one in decreasing order of satisfaction (e.g., using a priority queue), it would require up to \(K\) operations. Since \(K \le 10^9\), this will lead to Time Limit Exceeded (TLE).

Greedy Approach

If we process the purchase quantity for each snack type in bulk, each type can be handled in \(O(1)\). By sorting all snacks in descending order of satisfaction \(B_i\) and greedily purchasing the minimum of the “current stock” and the “remaining required count” from top to bottom, we can compute the answer quickly.

Additionally, if we still have not reached a total of \(K\) pieces after examining all snack types, it is impossible to purchase exactly \(K\) pieces, so we output \(-1\).

Algorithm

  1. Store the information of each snack as a pair \((B_i, A_i)\) in an array.
  2. Sort the array in descending order of satisfaction \(B_i\).
  3. Initialize variables remaining = K (remaining required count) and total_satisfaction = 0 (total satisfaction).
  4. Iterate through the sorted snacks from the beginning:
    • Let take be the number of pieces to buy of that snack, which is \(\min(\text{remaining}, A_i)\).
    • Add \(\text{take} \times B_i\) to total_satisfaction.
    • Subtract take from remaining.
    • If remaining == 0, we have purchased all the required pieces, so break out of the loop.
  5. Finally, if remaining > 0, it was not possible to purchase \(K\) pieces, so output -1. If remaining == 0, output total_satisfaction.

Complexity

  • Time Complexity: \(O(N \log N)\)
    • Sorting the snacks in descending order of satisfaction takes \(O(N \log N)\).
    • The subsequent scan loops at most \(N\) times, which takes \(O(N)\).
    • In total, the time complexity is \(O(N \log N)\), which is sufficiently fast under the constraint \(N \le 2 \times 10^5\).
  • Space Complexity: \(O(N)\)
    • It uses \(O(N)\) memory to store the information of the \(N\) snacks.

Implementation Notes

  • Handling Large Numbers (Language-Dependent): The maximum total satisfaction can reach \(K \times \max(B_i) \approx 10^9 \times 10^9 = 10^{18}\). In languages like C++, this exceeds the maximum value of a 32-bit integer type (int, approximately \(2 \times 10^9\)) and causes an overflow, so a 64-bit integer type (long long) must be used (Python supports arbitrary-precision integers, so large numbers are handled correctly automatically).

  • Fast I/O: Since the input size is large (\(N \le 2 \times 10^5\)), reading all input at once in Python using methods like sys.stdin.read().split() can significantly reduce the execution time.

    Source Code

import sys

def main():
    input_data = sys.stdin.read().split()
    if not input_data:
        return
    
    N = int(input_data[0])
    K = int(input_data[1])
    
    items = []
    idx = 2
    for _ in range(N):
        a = int(input_data[idx])
        b = int(input_data[idx+1])
        items.append((b, a))
        idx += 2
        
    items.sort(reverse=True)
    
    total_satisfaction = 0
    remaining = K
    
    for b, a in items:
        take = min(remaining, a)
        total_satisfaction += take * b
        remaining -= take
        if remaining == 0:
            break
            
    if remaining > 0:
        print(-1)
    else:
        print(total_satisfaction)

if __name__ == '__main__':
    main()

This editorial was generated by gemini-3.8-flash-high.