B - 最後の大根 / The Last Radish Editorial by admin Editorial for printing
gpt-6-astra-mediumOverview
We need to find the position of the rightmost D in the string \(S\). It suffices to check from the right end and output the position of the first D found.
Analysis
To find the rightmost radish, it is easiest to check the cells from right to left. With this order, there are no radishes to the right of the first D encountered, meaning that this D is the radish we are looking for.
For example, when \(S =\) D.D.., checking from the right reveals that the \(5\)-th and \(4\)-th positions are ., and a D is found at the \(3\)-rd position. Therefore, the answer is \(3\).
Since \(N \leq 100\), checking all cells will easily run within the time limit. We could also solve this by checking from left to right; however, if we terminate as soon as the first D is found, we would end up answering with the leftmost radish. If searching from the left, we would need to update the answer every time a D is found.
In our code, by checking from right to left, we can terminate immediately as soon as a D is found.
Algorithm
- Read \(N\) and \(S\).
- Iterate the index \(i\) from \(N-1\) down to \(0\), decrementing by \(1\):
- If
S[i]isD, output \(i+1\) (its position from the left) and terminate the program.
- If
- If no
Dhas been found by the end, there is no radish, so output-1.
Since we check from right to left, the moment we find a D, we know that all cells to its right are .. Thus, this method is guaranteed to find the rightmost radish.
Complexity
- Time Complexity: \(O(N)\)
In the worst case, all \(N\) cells are checked. - Space Complexity: \(O(N)\)
Required to store the input string \(S\). The additional space used besides the string is \(O(1)\).
Implementation Details
In C++, string indexing is \(0\)-based. Since
S[i]represents the \((i+1)\)-th cell from the left, outputi + 1.The index of the right end is \(N-1\). We inspect the cells while decrementing the index as long as
i >= 0.Once
Dis found, terminate withreturn 0;after outputting the answer. This prevents the-1at the end from being printed redundantly.Source Code
// 問題文から独立に実装: 右端から左へ向かって最初の D を探す
#include <iostream>
#include <string>
int main() {
int n; std::string s; std::cin >> n >> s;
for (int i = n - 1; i >= 0; --i) if (s[i] == 'D') { std::cout << i + 1 << std::endl; return 0; }
std::cout << -1 << std::endl;
}
This editorial was generated by gpt-6-astra-medium.
posted:
last update: