【模板】后缀数组
如题,这是一个模板。。。
1 #include <algorithm> 2 #include <iostream> 3 #include <cstring> 4 #include <cstdlib> 5 #include <cstdio> 6 7 using namespace std; 8 9 const int N = 1001010; 10 11 char s[N]; 12 int n, m, c[N], y[N], x[N], sa[N], rk[N]; 13 14 inline void Get_SA() 15 { 16 for (int i = 1; i <= n; ++i) ++c[x[i] = s[i]]; 17 for (int i = 2; i <= m; ++i) c[i] += c[i - 1]; 18 for (int i = n; i >= 1; --i) sa[c[x[i]]--] = i; 19 for (int k = 1; k <= n; k <<= 1) 20 { 21 int num = 0; 22 for (int i = n - k + 1; i <= n; ++i) y[++num] = i; 23 for (int i = 1; i <= n; ++i) if (sa[i] > k) y[++num] = sa[i] - k; 24 for (int i = 1; i <= m; ++i) c[i] = 0; 25 for (int i = 1; i <= n; ++i) ++c[x[i]]; 26 for (int i = 2; i <= m; ++i) c[i] += c[i - 1]; 27 for (int i = n; i >= 1; --i) sa[c[x[y[i]]]--] = y[i], y[i] = 0; 28 swap(x, y); 29 x[sa[1]] = 1, num = 1; 30 for (int i = 2; i <= n; ++i) 31 x[sa[i]] = (y[sa[i]] == y[sa[i - 1]] && 32 y[sa[i] + k] == y[sa[i - 1] + k]) ? num : ++num; 33 if (num == n) break; 34 m = num; 35 } 36 for (int i = 1; i <= n; ++i) 37 printf("%d ", sa[i]); 38 } 39 40 int main() 41 { 42 scanf("%s", s + 1); 43 n = strlen(s + 1), m = 123; 44 Get_SA(); 45 return 0; 46 }