Advertisement
smatskevich

Seminar14

May 22nd, 2023
708
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. std::vector<int> SuffixArray(const std::string& s) {
  6.   const int n = s.size() + 1;
  7.   std::vector<int> suff_mass(n);
  8.   // Отсортируем по первому символу.
  9.   std::vector<int> c(std::max(256, n));
  10.   for (int i = 0; i <= s.size();++i) c[s[i]]++;
  11.   for (int i = 1; i < 256; ++i) c[i] += c[i - 1];
  12.   for (int i = n - 1; i >= 0; --i) suff_mass[--c[s[i]]] = i;
  13.  
  14.   // Первое заполнение карманов и концов групп
  15.   std::vector<int> pockets(n);
  16.   pockets[suff_mass[0]] = 0;
  17.   c[0] = 1;
  18.   int curr_pocket = 0;
  19.   for (int i = 1; i < n; ++i) {
  20.     if (s[suff_mass[i]] != s[suff_mass[i - 1]]) ++curr_pocket;
  21.     pockets[suff_mass[i]] = curr_pocket;
  22.     c[curr_pocket] = i + 1;
  23.   }
  24.  
  25.   for (int k = 0; (1 << k) < n; ++k) {
  26.     std::vector<int> b(n);
  27.     for (int i = n - 1; i >= 0; --i) {
  28.       int curr_suff = (suff_mass[i] - (1 << k) + n) % n;
  29.       b[--c[pockets[curr_suff]]] = curr_suff;
  30.     }
  31.     suff_mass = std::move(b);
  32.     // Обновим pockets и c.
  33.     std::vector<int> new_pockets(n);
  34.     int curr_pocket = 0;
  35.     for (int i = 0; i < n; ++i) {
  36.       if (i > 0 && (pockets[suff_mass[i]] != pockets[suff_mass[i - 1]] ||
  37.           pockets[(suff_mass[i] + (1 << k)) % n] != pockets[(suff_mass[i - 1] + (1 << k)) % n]))
  38.         ++curr_pocket;
  39.       new_pockets[suff_mass[i]] = curr_pocket;
  40.       c[curr_pocket] = i + 1;
  41.     }
  42.     pockets = std::move(new_pockets);
  43.   }
  44.  
  45.   return suff_mass;
  46. }
  47.  
  48. int main() {
  49.   std::string s; std::cin >> s;
  50.   std::vector<int> suff_mass = SuffixArray(s);
  51.   for (int suff : suff_mass) {
  52.     std::cout << s.substr(suff) << std::endl;
  53.   }
  54.   return 0;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement