对于SA数组
SA[i]=i:表示 i~n的后缀 的起始位置为i
对于最长公共前缀我们可以hash+二分求解出来
对于SA数组的排序,可以根据最长公共前缀后一个字符作为关键字比较
#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const int N=1e6+1000;
ull h[N],p[N],P=131;
char s[N];
int n;
int sa[N],height[N];
ull get(int l,int r)
{
return h[r]-h[l-1]*p[r-l+1];
}
int check(int a,int b)
{
int l = 0, r = min(n - a + 1, n - b + 1);
while (l <= r)
{
int mid = l + r >> 1;
if (get(a, a + mid - 1) != get(b, b + mid - 1)) r = mid - 1;
else l = mid+1;
}
return r;
}
bool cmp(int a,int b)
{
int l=check(a,b);
return s[a+l]<s[b+l];
}
int main()
{
scanf("%s",(s+1));
n=strlen(s+1);
p[0]=1;
for(int i=1;i<=n;i++)
{
h[i]=h[i-1]*P+(s[i]-'a'+1);
p[i]=p[i-1]*P;
sa[i]=i;
}
sort(sa+1,sa+1+n,cmp);
for(int i=1;i<=n;i++) cout<<sa[i]-1<<" ";
cout<<endl;
for(int i=1;i<=n;i++)
{
if(i==1) printf("0 ");
else printf("%d ",check(sa[i-1],sa[i]));
}
}