EntropyIncreaser

Suffix Array

Jan 9th, 2018
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstring>
  3.  
  4. using namespace std;
  5.  
  6. struct node {
  7.     int a, b, id;
  8. };
  9.  
  10. const int N = 100010;
  11.  
  12. int n;
  13. char s[N];
  14. int cnt[N], sa[N], rk[N * 2], height[N], h[N];
  15. node p[N], q[N];
  16.  
  17. int main() {
  18.     scanf("%s", s + 1);
  19.     n = strlen(s + 1);
  20.     for (int i = 1; i <= n; ++i)
  21.         cnt[s[i] - 'a'] = 1;
  22.     for (int i = 1; i < 26; ++i)
  23.         cnt[i] += cnt[i - 1];
  24.     for (int i = 1; i <= n; ++i)
  25.         rk[i] = cnt[s[i] - 'a'];
  26.     for (int l = 1; l < n; l <<= 1) {
  27.         for (int i = 1; i <= n; ++i) {
  28.             p[i].id = i;
  29.             p[i].a = rk[i];
  30.             p[i].b = rk[i + l];
  31.         }
  32.         memset(cnt, 0, sizeof(cnt));
  33.         for (int i = 1; i <= n; ++i)
  34.             ++cnt[p[i].b];
  35.         for (int i = 1; i <= n; ++i)
  36.             cnt[i] += cnt[i - 1];
  37.         for (int i = n; i; --i)
  38.             q[cnt[p[i].b]--] = p[i];
  39.         memset(cnt, 0, sizeof(cnt));
  40.         for (int i = 1; i <= n; ++i)
  41.             ++cnt[q[i].a];
  42.         for (int i = 1; i <= n; ++i)
  43.             cnt[i] += cnt[i - 1];
  44.         for (int i = n; i; --i)
  45.             p[cnt[q[i].a]--] = q[i];
  46.         for (int i = 1; i <= n; ++i) {
  47.             rk[p[i].id] = rk[p[i - 1].id];
  48.             if (p[i].a != p[i - 1].a || p[i].b != p[i - 1].b)
  49.                 ++rk[p[i].id];
  50.         }
  51.     }
  52.     for (int i = 1; i <= n; ++i)
  53.         sa[rk[i]] = i;
  54.     for (int i = 1; i < n; ++i)
  55.         printf("%d ", sa[i]);
  56.     printf("%d\n", sa[n]);
  57.     for (int i = 1; i <= n; ++i) {
  58.         h[i] = h[i - 1] - 1;
  59.         if (h[i] < 0)
  60.             h[i] = 0;
  61.         while (s[i + h[i]] == s[sa[rk[i] - 1] + h[i]])
  62.             ++h[i];
  63.     }
  64.     for (int i = 1; i <= n; ++i)
  65.         height[rk[i]] = h[i];
  66.     for (int i = 2; i < n; ++i)
  67.         printf("%d ", height[i]);
  68.     if (n > 1)
  69.     printf("%d\n", height[n]);
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment