——代码
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #define N 100005 5 6 int m = ‘z‘ + 1; 7 int len, buc[N], x[N], y[N], sa[N], rank[N], h[N]; 8 char s[N]; 9 10 inline void build_sa() 11 { 12 scanf("%s", s); len = strlen(s); 13 int i, k, p; 14 for(i = 0; i < m; i++) buc[i] = 0; 15 for(i = 0; i < len; i++) buc[x[i] = s[i]]++; 16 for(i = 1; i < m; i++) buc[i] += buc[i - 1]; 17 for(i = len - 1; i >= 0; i--) sa[--buc[x[i]]] = i; 18 for(k = 1; k <= len; k <<= 1) 19 { 20 p = 0; 21 for(i = len - 1; i >= len - k; i--) y[p++] = i; 22 for(i = 0; i < len; i++) if(sa[i] >= k) y[p++] = sa[i] - k; 23 for(i = 0; i < m; i++) buc[i] = 0; 24 for(i = 0; i < len; i++) buc[x[y[i]]]++; 25 for(i = 1; i < m; i++) buc[i] += buc[i - 1]; 26 for(i = len - 1; i >= 0; i--) sa[--buc[x[y[i]]]] = y[i]; 27 std::swap(x, y); 28 p = 1, x[sa[0]] = 0; 29 for(i = 1; i < len; i++) 30 x[sa[i]] = y[sa[i - 1]] == y[sa[i]] && y[sa[i - 1] + k] == y[sa[i] + k] ? p - 1 : p++; 31 if(p >= len) break; 32 m = p; 33 } 34 } 35 36 int main() 37 { 38 int i, j, k = 0; 39 build_sa(); 40 for(i = 0; i < len; i++) printf("%d ", sa[i] + 1); 41 puts(""); 42 for(i = 0; i < len; i++) rank[sa[i]] = i; 43 for(i = 0; i < len; i++) 44 { 45 if(rank[i] == 0) 46 { 47 h[0] = 0; 48 continue; 49 } 50 if(k) k--; 51 j = sa[rank[i] - 1]; 52 while(s[i + k] == s[j + k] && i + k < len && j + k < len) k++; 53 h[rank[i]] = k; 54 } 55 for(i = 1; i < len; i++) printf("%d ", h[i]); 56 puts(""); 57 return 0; 58 }
原文:http://www.cnblogs.com/zhenghaotian/p/6973077.html