公式

B - 行儀のよい列 / Polite Queue 解説 by admin

swe-2-high

Solution

We need the number of indices \(i\) (\(1 \leq i \leq N - 1\)) such that the \(i\)-th character of \(S\) is C and the \((i+1)\)-th character is A. In other words, we count the occurrences of the contiguous substring CA in \(S\).

Simply scan \(i = 1, 2, \ldots, N - 1\) and check whether the \(i\)-th and \((i+1)\)-th characters form CA, counting how many times this happens.

Proof of Correctness

By definition, a valid \(i\) is one where the \(i\)-th character of \(S\) is C and the \((i+1)\)-th is A. The algorithm checks this exact condition for every \(i\) in the range \(1 \leq i \leq N - 1\) and counts those satisfying it. Each \(i\) is tested independently, with no double counting and no omissions. Hence the printed value is exactly the number of valid indices.

Complexity

  • Time: \(O(N)\) — each position is examined once.
  • Space: \(O(N)\) to store the input string; auxiliary space is \(O(1)\).

Since \(N \leq 100\), this is more than fast enough.

投稿日時:
最終更新: