B - 筋トレの目標達成 / Achieving the Muscle Training Goal Editorial by admin Editorial for printing
gpt-6-astra-mediumOverview
For each member’s record, determine the 1-based position of the leftmost o. If there is no o, output -1.
Analysis
Since the characters in the record are ordered by date, the first o appearing from the left corresponds to the day the member achieved the goal for the first time. The answer for each member can be found independently.
For example, if the record is xxoxo, the first o is the \(3\)-rd character, so the answer is \(3\). If it is xxxxx, the goal was never achieved, so the answer is -1.
A naive approach of examining each string from left to right is well within the time limit. Even when checking all members, the total number of characters to examine is at most \(H \times W \leq 100\).
However, we need to be careful about the following points in the implementation:
- Python string indexing is \(0\)-based, but the days in the problem are \(1\)-based.
- If
ois not found, we must output-1without converting it to a day number.
Algorithm
We can use the Python string method find. s.find('o') returns the index of the first occurrence of o in string s, or -1 if not found.
- Read \(H, W\).
- For each member, do the following:
- Read the record string
s. - Find the position of the first
ousingidx = s.find('o'). - If
idxis not-1, set the answer toidx + 1. - If
idxis-1, set the answer to-1. - Append the answer to the list for output.
- Read the record string
- Output the answers in the list separated by newlines, in the order of the members.
Since find returns the leftmost o, if found, it always gives the first day of achievement. Also, if not found, the member never achieved the goal, so -1 is the correct answer.
Complexity
- Time Complexity: \(O(HW)\)
For each member’s string, we examine at most \(W\) characters. - Space Complexity: \(O(H + W)\)
We store the answers for \(H\) members for output, and hold a string of at most \(W\) characters being processed. Under the constraints of this problem, the number of characters per answer is constant.
Implementation Notes
Pay attention to the difference between indices and days.
For example,find('o')onxxoxoreturns \(2\), so the day to output is \(2 + 1 = 3\).Be careful not to add \(1\) to
-1.
If you unconditionally doidx + 1, it will mistakenly output \(0\) when the goal was not achieved.In the code, the answers are converted to strings and stored in
out, then output all at once separated by newlines using"\n".join(out).Source Code
import sys
def main():
data = sys.stdin.readline().split()
H = int(data[0])
W = int(data[1])
out = []
for _ in range(H):
s = sys.stdin.readline().strip()
idx = s.find('o')
out.append(str(idx + 1 if idx != -1 else -1))
sys.stdout.write("\n".join(out) + "\n")
main()
This editorial was generated by gpt-6-astra-medium.
posted:
last update: