Official

B - 筋トレの目標達成 / Achieving the Muscle Training Goal Editorial by admin Editorial for printing

gpt-6-astra-medium

Overview

For each member’s record, find the position where o first appears. If o does not appear at all, output -1.

Analysis

The record string represents Day \(1\), Day \(2\), … from left to right. Therefore, the day corresponding to the leftmost o is the day the goal was achieved for the first time.

For example, if the record is xxoxo, the first o is the \(3\)-rd character from the left, so the answer is \(3\). If the record is xxxxx, the goal was never achieved, so the answer is -1.

A naive approach of examining each string from left to right is fast enough. No optimization is necessary, but the following points should be noted:

  • In Python, string indices are \(0\)-based, so add \(1\) when outputting the day number.
  • Calling s.index('o') on a string that does not contain o causes an error, so check for its presence beforehand.

Algorithm

Repeat the following process for the \(H\) members:

  1. Read the string s representing the record.
  2. Check if o is included using 'o' in s.
  3. If it is included, find the position of the first o using s.index('o'), add \(1\), and output it.
  4. If it is not included, output -1.

Since s.index('o') returns the position of the leftmost o, this method finds the day the goal was first achieved.

Complexity

  • Time complexity: \(O(HW)\)
  • Space complexity: \(O(W)\)

For each member, checking the existence of o and searching for its position each takes at most \(O(W)\) time. Doing this for \(H\) members takes \(O(HW)\) time in total.

Additionally, since only one record of length \(W\) is stored in memory at a time, the space complexity is \(O(W)\).

Implementation Notes

The following part of the code is a conditional expression that switches the output depending on whether o is present:

print(s.index('o') + 1 if 'o' in s else -1)

In a conditional expression, only the selected branch is evaluated. Therefore, s.index('o') will never be executed if o is not present, allowing -1 to be safely output.

Source Code

# 問題文から独立に実装
h, w = map(int, input().split())
for _ in range(h):
    s = input()
    print(s.index('o') + 1 if 'o' in s else -1)

This editorial was generated by gpt-6-astra-medium.

posted:
last update: