A - 経費の申請 / Expense Claims Editorial by admin Editorial for printing
gpt-6-astra-mediumOverview
This problem asks whether the total sum of \(N\) expenses is less than or equal to the limit of \(B\) yen. We subtract each expense from the limit in order, and if the remaining amount at the end is \(0\) or greater, we output Yes.
Analysis
The condition for all expenses to be claimed is as follows:
\(\displaystyle A_1 + A_2 + \cdots + A_N \leq B\)
There is no need to select or reorder the expenses; simply checking their sum is sufficient. Even a straightforward approach of computing the sum requires only \(N\) additions, easily running well within the time limit.
In the presented code, instead of computing the total sum, we keep track of “how many yen can still be claimed.” Setting the initial remaining amount to \(B\) and subtracting each expense one by one, the final remaining amount is:
\(\displaystyle \text{remaining} = B - (A_1 + A_2 + \cdots + A_N)\)
Therefore, if the remaining amount is \(0\) or greater, all expenses can be claimed; if it is negative, the limit has been exceeded.
For example, if \(B=1000\) and the expenses are \(200, 300, 400\) yen, the remaining amount changes as \(1000 \to 800 \to 500 \to 100\). Since the final remaining amount is \(0\) or greater, the answer is Yes.
Note that using a 32-bit integer type to handle these amounts may exceed the range of representable values, leading to incorrect answers. In C++, use the 64-bit integer type long long.
Algorithm
- Read \(N\) and \(B\).
- Initialize the variable
remaining, representing the remaining balance, to \(B\). - Read the \(N\) expenses one by one, and subtract each amount from
remaining. - After processing all of them, output the following:
- If
remainingis \(0\) or greater, outputYes. - If
remainingis negative, outputNo.
- If
Since having a final remaining amount of \(0\) or greater is equivalent to the sum of expenses being at most \(B\), this method correctly determines the answer.
Complexity
- Time Complexity: \(O(N)\)
- Space Complexity: \(O(1)\)
Each expense is processed once and not stored in an array, so the required extra space is constant.
Implementation Notes
Expenses matching the limit exactly can also be claimed. Check with
remaining >= 0rather thanremaining > 0.The sum of expenses can reach up to \(100 \times 10^9 = 10^{11}\) yen. Use
long longfor \(B\) and the remaining amount to prevent integer overflow.Use a signed integer type because the remaining amount can become negative.
The output is case-sensitive; output
YesorNoexactly as specified.Source Code
// 問題文から独立に実装: 上限から引いていき、負になったら No
#include <iostream>
int main() {
int n; long long b; std::cin >> n >> b;
long long remaining = b;
for (int i = 0; i < n; ++i) { long long a; std::cin >> a; remaining -= a; }
std::cout << (remaining >= 0 ? "Yes" : "No") << std::endl;
}
This editorial was generated by gpt-6-astra-medium.
posted:
last update: