Official

A - Rightmost Editorial by en_translator


Let \(n\) be the length of \(S\). This problem can be solved by performing the following operations:

  • If the \(n\)-th character of \(S\) is a, then print \(n\) and terminate the program.
  • Next, if the \((n-1)\)-th character of \(S\) is a, then print \((n-1)\) and terminate the program.
  • Next, if the \((n-2)\)-th character of \(S\) is a, then print \((n-2)\) and terminate the program.
  • Next, if the \((n-3)\)-th character of \(S\) is a, then print \((n-3)\) and terminate the program.

\(\qquad \vdots\)

  • Next, if the \(1\)-st character of \(S\) is a, then print \(1\) and terminate the program.
  • Finally, if an a is not found so far, print \(-1\) and terminate the program.

Each of these operation can be implemented with an if statement. However, since \(n\) can be up to \(100\) in this problem, writing them down as it is requires a total of \(100\) if statements.

Here, note that each operation is in almost an identical form. Indeed, all steps except for the last is in the form of “if the \(i\)-th character of \(S\) is a, print \(i\) and terminate the program,” and we need to perform it in the order of \(i = n, n - 1, \dots, 1\).

The loop is useful in such case; we can use a for statement or a while statement to implement such an algorithm. For example, a sample code in C++ follows:

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    cin >> s;
    int n = size(s);
    for (int i = n; i >= 1; i -= 1) {
        if (s[i - 1] == 'a') {
            cout << i << '\n';
            return 0;
        }
    }
    cout << -1 << '\n';
    return 0;
}

Since the indices in a program are 0-based, note that the \(i\)-th character of \(S\) should be denoted by s[i - 1] in the code.
By the way, the statement return 0; means “terminating the main function,” which allows us to accomplish the process of “printing \(i\) and terminating the program.”

A sample code in Python follows:

def main():
  s = input()
  n = len(s)
  for i in range(n, 0, -1):
    if s[i - 1] == 'a':
      print(i)
      return
  print(-1)

main()

posted:
last update: