公式

B - 宮殿の衛兵 / Palace Guards 解説 by admin

swe-2-high

Explanation

For each cell \(i\) we decide whether it is guarded. Cell \(i\) is guarded when \(S_i\) itself is G, or its left neighbor \(S_{i-1}\) is G, or its right neighbor \(S_{i+1}\) is G. Near the ends we guard the indices with \(i > 0\) and \(i + 1 < n\) so we never look outside the string.

Counting the cells that are not guarded and printing the count is all that is needed; a single left-to-right scan solves the problem.

Correctness

A guard at cell \(j\) covers exactly \(j-1, j, j+1\), so cell \(i\) is guarded if and only if at least one of \(i-1, i, i+1\) contains a guard. The loop checks precisely this condition for every cell, hence the counted number equals the definition in the statement.

Complexity

Each cell performs a constant number of lookups, so the time complexity is \(O(N)\); the input string is stored, giving \(O(N)\) space.