B - 最後の大根 / The Last Radish Editorial by admin
gpt-6-astra-mediumOverview
Find the rightmost D in the string \(S\), and output its 1-based position from the left. If there is no D, output -1.
Analysis
If we search from right to left, the first D we find is the rightmost radish. Therefore, we can terminate the search as soon as we find a D.
For example, when \(S =\) D..D., the character right after the rightmost . is a D. Since this radish is the \(4\)-th from the left, the answer is \(4\).
Since \(N \leq 100\), checking every cell will easily run within the time limit. If searching from the left, you can still get the correct answer by updating the answer every time you find a D. However, if you stop the search at the first D found from the left, you will end up choosing the leftmost radish, leading to a wrong answer.
Additionally, to handle the case where there are no radishes, initialize the answer to -1.
Algorithm
- Initialize the variable
ansrepresenting the answer to-1. - Iterate index \(i\) in the order \(N-1, N-2, \ldots, 0\) to inspect the string from right to left.
- If
s[i]isD, perform the following:- Assign \(i+1\) to
ans. - Terminate the search.
- Assign \(i+1\) to
- Output
ans.
When a D is found, all cells to its right have already been checked and none of them were D. Therefore, the radish found is indeed the rightmost radish. If no D is found at all, ans remains -1.
Complexity
- Time complexity: \(O(N)\) — In the worst case, every cell is checked once.
- Space complexity: \(O(N)\) — Required to store the input string. The additional space used for the search is \(O(1)\).
Implementation Notes
Python uses \(0\)-based indexing for strings, but since the required position to output is \(1\)-based, the answer is
i + 1.range(n - 1, -1, -1)generates indices in descending order from \(N-1\) down to \(0\). The stop value-1is not included.Once
Dis found, terminate withbreak. If you continue searching and updating the answer, it will be overwritten by the position of a radish further to the left.Source Code
import sys
def main():
data = sys.stdin.read().split()
n = int(data[0])
s = data[1]
ans = -1
for i in range(n - 1, -1, -1):
if s[i] == 'D':
ans = i + 1
break
print(ans)
main()
This editorial was generated by gpt-6-astra-medium.