Official

B - Triple Metre Editorial by en_translator


There are several possible solutions for this problem. We will introduce some of them.

First, one may literally follow the instruction in the problem statement: “actually construct \(T\) and check if \(S\) is a substring of \(T\).”
For example, in Python, for two objects S and T of type str, one can check if S is a substring of T.
The following is a sample code in Python.

S = input()
T = "oxx" * 10 ** 5
print("Yes" if S in T else "No")

Since Python does not specify the complexity, so strictly speaking the complexity of the implementation above is unclear. However, in the processing system which is chosen when you chose Python 3.8.2 as the submission language (namely, in CPython), an algorithm of computing it in a total of \(\mathrm{O}(|S| + |T|)\) time by the methods like Boyer-Moore Algorithm is implemented, so we may consider it is \(\mathrm{O}(|S| + |T|)\).

Next, we will introduce an advanced solution with reduced complexity.
If a string satisfies the condition, it satisfies one of the three conditions below:

  • If the remainder of \(i\) divided by \(3\) is \(0\), then S[i] = 'o'; otherwise S[i] = 'x'.
  • If the remainder of \(i\) divided by \(3\) is \(1\), then S[i] = 'o'; otherwise S[i] = 'x'.
  • If the remainder of \(i\) divided by \(3\) is \(2\), then S[i] = 'o'; otherwise S[i] = 'x'.

Therefore, we can check if \(S\) satisfies one of these conditions with for loop, so that the problem is solved in a total of \(\mathrm{O}(|S|)\) time.
A sample code in C++ follows.

#include <iostream>
#include <string>
using namespace std;

int main() {
  string S;
  cin >> S;
  for (string T : {"oxx", "xox", "xxo"}) {
    bool ok = true;
    for (int i = 0; i < (int)S.size(); i++) {
      if (T[i % 3] != S[i]) ok = false;
    }
    if (ok) {
      cout << "Yes" << endl;
      exit(0);
    }
  }
  cout << "No" << endl;
}

posted:
last update: