CSES - String Transform

Author: Benjamin Qi

GFG does an okay (?) job of explaining it and giving some intuition. But the code can be so much shorter ...

My Implementation

Let be the BWT of , where ends with a character that is smaller than all other characters in (# in this case).

Consider all indices modulo . If corresponds to (the last character of the -th smallest rotation) then define

corresponds to the _th smallest rotation of , and is formed by cyclically shifting by one character. is the last character of and the first character of .

Define to be the unique such that . Then we know that . Given , we can compute

so for all .

We know that

so we can sort the using a stable sort. Then is just the index of the -th rotation in this sort!

1#include <bits/stdc++.h>
2using namespace std;
3
4using ll = long long;
5using ld = long double;
6using db = double;
7using str = string; // yay python!
8
9using pi = pair<int,int>;
10using pl = pair<ll,ll>;

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!

Give Us Feedback on CSES - String Transform!