Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define all(x) begin(x),end(x)
- #define make_unique(x) if (!is_sorted(all(x))) sort(all(x)); x.erase(unique(all(x)), x.end());
- #define remax(x,y) (x > y ? x = y, true : false)
- #define remin(x,y) (x < y ? x = y, true : false)
- #define size(x) int(x.size())
- using namespace std;
- using ll = long long;
- struct SuffixArray {
- const string s;
- const 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(n), ind(n), cnt(n);
- iota(all(arr), 0);
- vector<int> mp(256);
- for (int i = 0; i < n; i++) { mp[s[i]]++; }
- for (int i = 1; i < 256; i++) { mp[i] += mp[i - 1]; }
- for (int i = n - 1; i >= 0; i--) { arr[--mp[s[i]]] = i; }
- c[arr[0]] = 0;
- for (int i = 1; i < n; i++) {
- c[arr[i]] = c[arr[i - 1]];
- if (s[arr[i]] != s[arr[i - 1]]) {
- c[arr[i]]++;
- }
- }
- for (int deg = 1; (1 << (deg - 1)) < n; deg++) {
- const int len = 1 << (deg - 1);
- fill(all(cnt), 0);
- ind[0] = 0;
- for (int i = 0; i < n; i++) {
- arr[i] -= len;
- if (arr[i] < 0) arr[i] += n;
- }
- for (int i = 0; i < n; i++) { cnt[c[arr[i]]]++; }
- for (int i = 1; i < n; i++) { ind[i] = ind[i - 1] + cnt[i - 1]; }
- for (int i = 0; i < n; i++) { buff[ind[c[arr[i]]]++] = arr[i]; }
- copy(all(buff), begin(arr));
- buff[arr[0]] = 0;
- 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 << endl;
- }
- #undef modulo
- };
- int main() {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- string s;
- cin >> s;
- SuffixArray arr(s);
- arr.Print();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement