Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct SuffixArray {
- string s;
- int n;
- vector<int> arr;
- #define modulo(x) (x >= n ? x - n : x)
- SuffixArray(const string& str)
- : s(str + char(0))
- , n(size(s))
- , arr(n)
- {
- vector<int> c(n), buff(c);
- iota(all(arr), 0);
- for (int deg = 0; (1 << (deg - 1)) < n; deg++) {
- if (deg == 0) {
- sort(all(arr), [&] (int i, int j) { return s[i] < s[j]; });
- for (int i = 1; i < n; i++) {
- c[arr[i]] = c[arr[i - 1]] + (s[arr[i]] == s[arr[i - 1]] ? 0 : 1);
- }
- } else {
- int len = 1 << (deg - 1);
- for (int i = 1, j = 1; i < n; i = j) {
- while (j < n && c[arr[i]] == c[arr[j]]) j++;
- sort(begin(arr) + i, begin(arr) + j, [&] (int a, int b) {
- return c[modulo(a + len)] < c[modulo(b + len)];
- });
- }
- for (int i = 1; i < n; i++) {
- buff[arr[i]] = buff[arr[i - 1]];
- if (c[arr[i]] != c[arr[i - 1]] || c[modulo(arr[i] + len)] != c[modulo(arr[i - 1] + len)]) {
- buff[arr[i]]++;
- }
- }
- copy(all(buff), begin(c));
- }
- }
- }
- void Print() {
- for (int val : arr) {
- cout << val << ' ';
- }
- cout << '\n';
- }
- #undef modulo
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement