#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1000, M = 130;
char s[N];
int sa[N], t[N], t2[N], c[M], n;
int rank[N], high[N];
bool cmp(int *y, int i, int k)
{
return y[sa[i-1]] == y[sa[i]] && y[sa[i-1]+k] == y[sa[i]+k];
}
void build(int m)
{
int i, *x = t, *y = t2;
for(i = 0; i < m; i++) c[i] = 0;
for(i = 0; i < n; i++) c[x[i] = s[i]]++;
for(i = 1; i < m; i++) c[i] += c[i-1];
for(i = n-1; i >= 0; i--) sa[--c[x[i]]] = i;
for(int k = 1, p; k <= n; k<<=1, m=p) {
p = 0;
for(i = n-k; i < n; i++) y[p++] = i;
for(i = 0; i < n; i++) if(sa[i] >= k) y[p++] = sa[i] - k;
for(i = 0; i < m; i++) c[i] = 0;
for(i = 0; i < n; i++) c[x[y[i]]]++;
for(i = 1; i < m; i++) c[i] += c[i-1];
for(i = n-1; i >= 0; i--) sa[--c[x[y[i]]]] = y[i];
swap(x, y);
p = 1; x[sa[0]] = 0;
for(i = 1; i < n; i++) {
x[sa[i]] = cmp(y, i, k) ? p-1 : p++;
}
if(p >= n) break;
}
}
void get_high()
{
int k = 0;
for(int i = 0; i < n; i++) rank[sa[i]] = i;
for(int i = 0; i < n; i++) {
if(k) k--;
int j = sa[rank[i]-1];
while(s[i+k] == s[j+k]) k++;
high[rank[i]] = k;
}
}
void PR()
{
printf("The rank is:\n");
printf("%d", rank[0]);
for(int i = 1; i < n-1; i++)
printf(" %d", rank[i]);
puts("");
}
int main()
{
scanf("%s", s);
n = strlen(s) + 1;
int maxi = 0;
for(int i = 0; i < n; i++) {
maxi = maxi > s[i] ? maxi : s[i];
}
s[n-1] = 0;
build(maxi+1);
get_high();
PR();
return 0;
}
【后缀数组】后缀数组模板
最新推荐文章于 2022-06-26 16:30:09 发布