B - 筋トレの目標達成 / Achieving the Muscle Training Goal Editorial by admin
gpt-6-astra-mediumOverview
For each member, examine their record from the beginning to find the first day on which o appears. If o never appears, output -1.
Analysis
Since the records are ordered chronologically by date, the first o from the left corresponds to the first day the goal was achieved.
Here, the string consists only of the characters o and x. Therefore, we can find the answer by counting how many consecutive xs there are from the beginning.
For example, if the record is xxoxo, there are \(2\) consecutive xs at the beginning. The next character is o, so the goal was first achieved on day \(3\). On the other hand, if all characters are x like xxxxx, the goal was never achieved, so the answer is -1.
In this problem, a naive approach of checking each character in order is fast enough. No special optimization is required, but note that string indices are \(0\)-indexed, whereas days are \(1\)-indexed.
Algorithm
For each member, perform the following steps:
- Read the string \(s\) representing the record.
- Initialize a variable \(k\) to \(0\), representing the number of consecutive
xs from the beginning. - While \(k < W\) and \(s[k]\) is
x, increment \(k\) by \(1\). - If \(k = W\), all characters are
x, so output-1. - Otherwise, \(s[k]\) is the first
o, so output \(k + 1\).
When this process terminates, all characters before index \(k\) are x. If \(k < W\), \(s[k]\) is not x (hence it must be o), which indicates that this is the first day the goal was achieved.
Complexity
- Time complexity: \(O(HW)\)
For each member, we read a string of length \(W\) and examine at most \(W\) characters. - Space complexity: \(O(W)\)
We only need to store the record of one member at a time. The auxiliary space other than the string is \(O(1)\).
Implementation Notes
Since
s[k]corresponds to the record for day \(k + 1\), outputk + 1once the firstois found.Check
k < wfirst, as inwhile (k < w && s[k] == 'x'). Since the&&operator in C++ does not evaluate the right-hand side if the left-hand side is false (short-circuit evaluation), the character is only checked when the index is within the valid range of the record.If the first character is
o, \(k\) remains \(0\), so the answer is \(1\); if all characters arex, \(k\) becomes \(W\), so the answer is-1.Source Code
// 問題文から独立に実装: 先頭から x が続く長さを数える
#include <iostream>
#include <string>
int main() {
int h, w; std::cin >> h >> w;
for (int i = 0; i < h; ++i) {
std::string s; std::cin >> s;
int k = 0;
while (k < w && s[k] == 'x') k++;
std::cout << (k == w ? -1 : k + 1) << "\n";
}
}
This editorial was generated by gpt-6-astra-medium.