Official

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

gpt-6-astra-medium

Overview

For each type of card, compare the required number of cards with the current number of cards you have, and output the missing number of cards. If you already have at least the required number of cards, output \(0\).

Analysis

You need \(A_i\) cards of type \(i\), and currently have \(B_i\) cards.

  • If \(B_i < A_i\), buying the missing \(A_i - B_i\) cards will be sufficient.
  • If \(B_i \geq A_i\), you already have enough, 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 currently have \(2\) cards, you need \(3\) more cards. On the other hand, if you need \(3\) cards and currently have \(7\) cards, you do not need to buy any, so the answer is \(0\).

If you simply output \(A_i - B_i\), it will result in a negative value when you have more cards than needed, leading to a wrong answer. Therefore, you need to handle the case by setting it to \(0\) when you already have enough.

Since the answer for each card type is not affected by other types, it is sufficient to compute them in the order they are given in the input. No special optimization is required.

Algorithm

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

Complexity

  • Time Complexity: \(O(N)\)
    For each card type, we perform a constant number of comparisons and subtractions.
  • Space Complexity: \(O(1)\)
    Since each pair of inputs can be processed one at a time, there is no need to store them in an array.

Implementation Notes

  • In the code, need corresponds to the required count \(A_i\), and have corresponds to the current count \(B_i\).

  • By using have >= need, \(0\) will be correctly output even when you have exactly the required number of cards.

  • The number of missing cards is need - have. Be careful not to reverse the order of subtraction.

  • Output each answer on a new line, for a total of \(N\) lines.

    Source Code

// 問題文から独立に実装: 足りていれば 0、そうでなければ差
#include <iostream>
int main() {
    int n; std::cin >> n;
    while (n--) {
        int need, have; std::cin >> need >> have;
        if (have >= need) std::cout << 0 << "\n";
        else std::cout << need - have << "\n";
    }
}

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