A - カードを揃える / Collecting Cards 解説 by admin
swe-2-highSolution
Consider each card type \(i\) independently. Exactly \(A_i\) cards of type \(i\) are required, and Takahashi currently has \(B_i\) of them.
If he buys \(x\) more cards, he will have \(B_i + x\) cards. The condition for having enough cards is
\[ B_i + x \geq A_i. \]
Since \(x\) must be a nonnegative integer, the minimum number he needs to buy is
\[ \max(0, A_i - B_i). \]
Therefore, it is sufficient to print this value for each \(i\) on its own line.
The answer for every card type is uniquely determined, so no special tie-breaking is required.
Correctness Proof
Fix an arbitrary \(i\).
- If \(B_i \geq A_i\), Takahashi already has at least the required number of cards, so he needs to buy \(0\) more. In this case, \(A_i-B_i \leq 0\), so \(\max(0,A_i-B_i)=0\), which is correct.
- If \(B_i < A_i\), he must buy at least \(A_i-B_i\) cards to reach the required number. Buying exactly \(A_i-B_i\) cards gives him \(B_i+(A_i-B_i)=A_i\) cards. Thus, the minimum number to buy is \(A_i-B_i\), and \(\max(0,A_i-B_i)=A_i-B_i\).
Hence, for every \(i\), the printed value is exactly the minimum number of additional cards needed.
Complexity
The program performs a constant-time calculation for each of the \(N\) card types, so the time complexity is \(O(N)\). Since each input pair is processed as it is read, the auxiliary space complexity is \(O(1)\).