Official

E - Reverse Permutation Editorial by en_translator Editorial for printing


First, let us rephrase the procedure as follows:

  • Let \(A=()\).
  • For \(k=1,2,\ldots,N\), do the following:
    • Append \(k\) to the end of \(A\).
    • If \(S_k=\), reverse \(A\).

Moreover, by maintaining the reversion count \(c\), we can apply the reversion all at once in the end, instead of applying it every time.

  • Let \(A=()\) and \(c=0\).
  • For \(k=1,2,\ldots,N\), do the following:
    • If \(c\) is even, append \(k\) to \(A\); if \(c\) is odd, prepend \(k\) to \(A\).
    • If \(S_k=\) o, add \(1\) to \(c\).
  • If \(c\) is odd, reverse \(A\).

This algorithm runs in \(O(N)\) time by, for example, maintaining the prepended elements in another array.

The problem can be solved by properly implementing this algorithm.

Sample code (Python 3)

n = int(input())
s = input()
a, b = [], []
rev = False
for i in range(n):
    if rev:
        a.append(i + 1)
    else:
        b.append(i + 1)
    if s[i] == "o":
        rev ^= True
ans = a[::-1] + b
if rev:
    ans = ans[::-1]
print(*ans)

posted:
last update: