Official

C - Follow the Letters Editorial by evima


The answer to this problem is the number of repetitions of the period of \(S\), that is, the number of \(i\) such that cyclically shifting \(S\) by \(i\) yields \(S\) again. Let this number be \(K\).

The fact that the answer is at least \(K\) can be shown from the fact that the people corresponding to the above \(i\) can never gather together. For example, if S = abcdabcdabcd, then \(K = 3\) (\(i = 1, 5, 9\)), and the people initially on islands \(1, 5, 9\) always move the same distance, so they can never gather together.

It remains to construct a sequence of operations that achieves \(K\). For example, it suffices to repeat \(S\) \(N\) times.

We only need to consider how people move under the operation sequence \(S\). Combining the facts that

  • a person who was on an island \(i\) corresponding to the start of the above period returns to island \(i\) after going exactly once around,
  • a person who was on an island other than \(i\) necessarily moves through \(N + 1\) or more islands, and
  • in general, no person ever overtakes another person,

we can see that repeating \(S\) \(N\) times causes everyone to eventually gather on island \(i\).

Aside

  • There exist cases, such as S = abababab...abaab, that require \(\Omega(N^2)\) operations.
  • The minimum length of a desired operation sequence can also be found in \(O(26N^2)\) time.
  • The judge (output checker) for this problem runs in \(O(26N + L)\) time.

posted:
last update: