#P3612. Infinite Code String

    ID: 16863 Type: Default 1000ms 256MiB

Infinite Code String

Infinite Code String

Given an initial string \(s\), define the function \(F(s) = s + R(s)\), where \(R(s)\) is the right rotation of \(s\) (i.e. the last character of \(s\) becomes the first). Starting with \(S_0 = s\), we recursively define \(S_k = F(S_{k-1}) = S_{k-1} + R(S_{k-1})\) for \(k \ge 1\). This process produces an infinite-length string.

Your task is: given the initial string \(s\) and an index \(N\), find the character at the \(N\)th position in the infinite string \(\lim_{k \to \infty}S_k\).

The key observation is that the string is built recursively by concatenating a string with its right-rotated copy. If a string \(T\) has length \(L\) then its right rotated copy \(R(T)\) is defined as:

\[ R(T)[1] = T[L], \quad R(T)[i] = T[i-1] \;\text{for}\; 2 \le i \le L. \]

Using a recursive approach, one can determine the location of the \(N\)th character without constructing the entire string.

inputFormat

The input consists of two lines:

  1. The first line contains the initial string \(s\), a non-empty sequence of characters.
  2. The second line contains an integer \(N\) (1-indexed), representing the position in the infinite code string.

outputFormat

Output a single character, which is the \(N\)th character of the infinite code string.

sample

COW
4
W