Official

A - カードを揃える / Collecting Cards Editorial by admin Editorial for printing

gpt-6-astra-medium

Overview

For each type of card, we subtract the number of cards currently owned from the required number to determine the shortage. If you already have at least the required number, output \(0\).

Analysis

For the \(i\)-th type of card, \(A_i\) cards are required, and you currently have \(B_i\) cards.

  • If \(A_i > B_i\): There is a shortage of cards, so you need to buy \(A_i - B_i\) more cards.
  • If \(A_i \leq B_i\): You already have enough cards, so the number of cards to buy is \(0\).

Therefore, the answer can be expressed by the following formula:

\(\max(A_i - B_i, 0)\)

For example, if you need \(5\) cards and have \(2\), you need \(3\) more cards. On the other hand, if you need \(3\) cards and have \(7\), you do not need to buy any, so the answer is \(0\).

If you simply output \(A_i - B_i\), a negative value will be output when you already have more cards than required, resulting in an incorrect answer. If the difference is negative, it must be replaced with \(0\).

Since each card type can be processed independently, it suffices to compute the answer once for each type. There is no need for time-consuming searches or similar methods.

Algorithm

  1. Read the number of card types, \(N\).
  2. Repeat the following process \(N\) times:
    • Read the required number of cards \(A_i\) and the current number of cards \(B_i\).
    • If \(A_i > B_i\), output \(A_i - B_i\).
    • Otherwise, output \(0\).

This process outputs the shortfall when cards are lacking and \(0\) when you have enough, producing the correct answer for each type.

Complexity

  • Time complexity: \(O(N)\). A constant number of comparisons and operations are performed for each type.
  • Space complexity: \(O(1)\). Since the input can be processed line by line, there is no need to store the information for all types at once.

Implementation Notes

The expression a - b if a > b else 0 in the code is a conditional expression that evaluates to a - b if a > b holds, and 0 otherwise.

When the required number of cards is equal to the number of cards owned, the answer is also \(0\). Also, make sure not to sum the answers, but rather output them line by line for each type in the order they are given in the input.

Source Code

# 問題文から独立に実装
n = int(input())
for _ in range(n):
    a, b = map(int, input().split())
    print(a - b if a > b else 0)

This editorial was generated by gpt-6-astra-medium.

posted:
last update: