B - 変わらなかった時間 / Steady Hours Editorial by admin Editorial for printing
gpt-6-astra-mediumOverview
We compare adjacent characters in the string \(S\) and find the number of positions where the characters are the same. In the presented code, we count the number of times the state changed and subtract this from the total number of comparisons to calculate the answer.
Analysis
From the \(2\)-nd hour to the \(N\)-th hour, each hour is compared with the immediately preceding one, so there are \(N-1\) comparison positions in total.
Each position always falls into one of the following two cases:
- Adjacent characters are the same: The state of the light did not change.
- Adjacent characters are different: The state of the light changed.
Therefore, letting \(\mathrm{changes}\) be the number of times the state changed, the answer is:
\((N-1)-\mathrm{changes}\)
For example, when \(N=5\) and \(S=\) ooxxx, the pairs of adjacent characters are the \(4\) pairs: oo, ox, xx, and xx. The state changed only once at ox, so the answer is \(4-1=3\).
Note that for this problem, a naive approach of directly counting the positions where adjacent characters are the same easily runs well within the time limit. No optimization is necessary. However, merely counting the occurrences of o and x will not tell you whether adjacent characters are identical, so you must compare them in order.
Algorithm
- Read \(N\) and \(S\).
- Initialize the variable
changes, representing the number of state changes, to \(0\). - Using \(0\)-based indexing for the string, repeat the following for \(i=1\) to \(N-1\):
- If
s[i]ands[i - 1]are different, incrementchangesby \(1\).
- If
- Output \((N-1)-\mathrm{changes}\).
Since every adjacent pair is compared exactly once, the number of state changes is counted correctly. Subtracting this count from the total number of comparisons yields the number of times the state was the same.
Complexity
- Time Complexity: \(O(N)\)
- Space Complexity: \(O(N)\) (required to store the string \(S\); the additional space excluding input storage is \(O(1)\))
Implementation Notes
In C++, string indexing is \(0\)-based. Since the \(2\)-nd hour corresponds to
s[1], the loop should start fromi = 1.Because
s[i - 1]is accessed, be careful not to start comparing fromi = 0.The total number of comparison positions is \(N-1\), not \(N\).
When \(N=1\), there are no comparisons to make. The loop will not execute, and \(0\) will be correctly output.
Source Code
// 問題文から独立に実装: 状態が変わった回数を数え、N-1 から引く
#include <iostream>
#include <string>
int main() {
int n; std::string s; std::cin >> n >> s;
int changes = 0;
for (int i = 1; i < n; ++i) if (s[i] != s[i - 1]) changes++;
std::cout << (n - 1) - changes << std::endl;
}
This editorial was generated by gpt-6-astra-medium.
posted:
last update: