公式

A - 財布の中身 / Contents of the Wallet 解説 by admin

gpt-6-astra-medium

Overview

Determine whether the string \(S\) contains both C (representing coins) and B (representing banknotes). This can be determined by counting the number of coins.

Analysis

Let \(\mathrm{coins}\) be the number of coins. Since each piece of money is either a coin or a banknote, the number of banknotes is \(N-\mathrm{coins}\).

The condition for having at least one of both coins and banknotes is that: - There are coins: \(\mathrm{coins}>0\) - There are banknotes: \(\mathrm{coins}<N\)

both hold true. In other words, if \(0<\mathrm{coins}<N\), the answer is Yes.

For example, if \(N=4\) and \(S=\) CCBC, there are \(3\) coins. Since this satisfies \(0<3<4\), output Yes. On the other hand, if \(S=\) CCCC, there are \(4\) coins and no banknotes, so the answer is No.

For this problem, a naive approach of checking the characters in the string one by one from the beginning is fast enough to pass within the time limit. However, if you only check whether C is present, it will mistakenly output Yes even when all items are coins. Make sure to also check for the existence of banknotes.

Algorithm

  1. Read \(N\) and \(S\).
  2. Initialize a variable coins, representing the number of coins, to \(0\).
  3. Check each character of \(S\), and if it is C, increment coins by \(1\).
  4. If coins > 0 and coins < n, output Yes; otherwise, output No.

Complexity

  • Time Complexity: \(O(N)\)
    Each character of the string is inspected once.
  • Space Complexity: \(O(N)\)
    Required to store the input string \(S\). Excluding the storage space for the input, the auxiliary space complexity is \(O(1)\).

Implementation Notes

  • The provided code is in C++. By using &&, both conditions—having coins and having banknotes—are checked simultaneously.

  • coins == 0 corresponds to the case where all are banknotes, and coins == n corresponds to the case where all are coins, so both result in No.

  • When \(N=1\), it is impossible to have both types of money. In this case, the same conditional expression correctly evaluates to No.

    Source Code

// 問題文から独立に実装: 硬貨の枚数が 0 でも N でもないなら両方ある
#include <iostream>
#include <string>
int main() {
    int n; std::string s; std::cin >> n >> s;
    int coins = 0;
    for (int i = 0; i < n; ++i) if (s[i] == 'C') coins++;
    std::cout << ((coins > 0 && coins < n) ? "Yes" : "No") << std::endl;
}

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