模板题,代码如下:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1000009;
int n,m,x[N],y[N],c[N],sa[N];
char s[N];
void init()
{
scanf("%s",s+1);
n=strlen(s+1);
}
void Rsort()
{
for (int i=1;i<=m;i++)
c[i]=0;
for (int i=1;i<=n;i++)
c[x[y[i]]]++;
for (int i=1;i<=m;i++)
c[i]+=c[i-1];
for (int i=n;i>=1;i--)
sa[c[x[y[i]]]--]=y[i];
}
void Get_SA()
{
m=122;
for (int i=1;i<=n;i++)
x[i]=s[i],y[i]=i;
Rsort();
for (int k=1;k<=n;k<<=1)
{
int num=0;
for (int i=n-k+1;i<=n;i++)
y[++num]=i;
for (int i=1;i<=n;i++)
if(sa[i]>k)
y[++num]=sa[i]-k;
Rsort(),swap(x,y);
x[sa[1]]=num=1;
for (int i=2;i<=n;i++)
x[sa[i]]=(y[sa[i]]==y[sa[i-1]]&&y[sa[i]+k]==y[sa[i-1]+k])?num:++num;
if(num==n)
break;
m=num;
}
}
void work()
{
Get_SA();
for (int i=1;i<=n;i++)
printf("%d ",sa[i]);puts("");
}
int main()
{
init();
work();
return 0;
}