A - 財布の中身 / Contents of the Wallet Editorial by admin Editorial for printing
swe-2-highSolution
The task is to determine whether the string \(S\) contains both C (coins) and B (bills) at least once.
Algorithm
- Read \(N\) and the string \(S\).
- Scan \(S\) and maintain two flags:
hasC(whetherCappeared) andhasB(whetherBappeared). Alternatively, use the language’s built-in character search. - Print
Yesif both flags are true, andNootherwise.
Proof of Correctness
After the scan, hasC is true if and only if S contains at least one C: every character is examined exactly once, and hasC is set to true precisely when a C is found. The same holds for hasB.
The program prints Yes exactly when hasC && hasB holds. Since \(S\) consists only of C and B, the condition “the wallet contains at least one coin and at least one bill” is equivalent to “C occurs in \(S\) and B occurs in \(S\)”. Hence the algorithm matches the problem requirement exactly.
When \(N = 1\), \(S\) has a single character, so only one of the two kinds can be present and the program correctly prints No.
Complexity
- Time: \(O(N)\) — each character is examined once.
- Space: \(O(N)\) for storing the input string \(S\); only \(O(1)\) auxiliary space for the flags.
The Python implementation uses 'C' in S and 'B' in S, while the C++ implementation uses an explicit loop; both perform the same check.
posted:
last update: