B - 変わらなかった時間 / Steady Hours Editorial by admin Editorial for printing
gpt-6-astra-mediumOverview
We compare adjacent characters in the string \(S\) and count the number of pairs that have the same character.
Analysis
The lighting state at hour \(i\) being the same as the previous hour corresponds to the \(i\)-th character of \(S\) being equal to the \((i-1)\)-th character. Therefore, we can find the answer by checking from the \(2\)-nd hour to the \(N\)-th hour in order.
For example, when \(S=\) oooxx, the adjacent characters are as follows:
- \(1\)st and \(2\)nd characters:
oando, so they are the same - \(2\)nd and \(3\)rd characters:
oando, so they are the same - \(3\)rd and \(4\)th characters:
oandx, so they are different - \(4\)th and \(5\)th characters:
xandx, so they are the same
Thus, the answer is \(3\).
This problem can be solved sufficiently fast with a naive approach that compares all adjacent characters. However, counting the “number of contiguous blocks of identical characters” will lead to a wrong answer. For example, in ooo, there is \(1\) contiguous block, but there are \(2\) hours in total—the \(2\)nd and \(3\)rd hours—where the state is the same as the previous hour.
Algorithm
- Read \(N\) and \(S\).
- Since Python strings are 0-indexed, iterate the index \(i\) from \(1\) to \(N-1\).
- Each time
s[i] == s[i - 1]holds, add \(1\) to the answer. - Output the answer.
In the reference implementation, a \(1\) is generated for each index satisfying the condition, and their sum is computed using sum.
Complexity
- Time complexity: \(O(N)\)
We compare adjacent characters \(N-1\) times. - Space complexity: \(O(N)\)
Required to store the input string. The auxiliary space complexity excluding the input is \(O(1)\).
Implementation Notes
range(1, n)generates indices from \(1\) to \(n-1\) in order. This corresponds to the \(2\)nd hour through the \(N\)-th hour in the problem statement.Be careful not to start comparing from index \(0\). In Python,
s[-1]refers to the last character, so starting from \(0\) would erroneously compare the first character with the last character.When \(N=1\), there are no pairs to compare. In this case,
range(1, n)is empty andsumreturns \(0\), so no special case handling is necessary.Since a generator expression is passed to
sum, no intermediate list is constructed for counting.Source Code
# 問題文から独立に実装
n = int(input())
s = input().strip()
print(sum(1 for i in range(1, n) if s[i] == s[i - 1]))
This editorial was generated by gpt-6-astra-medium.
posted:
last update: