后缀数组的水题。
将字符串再复制一份到末尾,剖环为链。
然后求出sa,那么后缀在前pos个的后缀的末尾字符就是答案。
代码:
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 200000 + 10;
int wa[maxn],wb[maxn],ws[maxn],wv[maxn],sa[maxn],r[maxn],rank[maxn];
char op[maxn],b[maxn];
int n,pos;
void init()
{
freopen("bzoj1031.in","r",stdin);
freopen("bzoj1031.out","w",stdout);
}
void readdata()
{
scanf("%s",op);
}
bool cmp(int *r,int a,int b,int len)
{
return r[a] == r[b] && r[a + len] == r[b + len];
}
void da(int *r,int *sa,int n,int m)
{
int *x = wa,*y = wb,*t;
for(int i = 0;i < m;i++)ws[i] = 0;
for(int i = 0;i < n;i++)++ws[x[i]=r[i]];
for(int i = 1;i < m;i++)ws[i] += ws[i-1];
for(int i = n - 1;i >= 0;i--)sa[--ws[x[i]]] = i;
for(int j = 1,p = 1;p < n;j <<= 1,m = p)
{
p = 0;
for(int i = n - j;i < n;i++)y[p++] = i;
for(int i = 0;i < n;i++)
if(sa[i] >= j)y[p++] = sa[i] - j;
for(int i = 0;i < n;i++)wv[i] = x[y[i]];
for(int i = 0;i < m;i++)ws[i] = 0;
for(int i = 0;i < n;i++)++ws[wv[i]];
for(int i = 1;i < m;i++)ws[i] += ws[i-1];
for(int i = n - 1;i >= 0;i--)sa[--ws[wv[i]]] = y[i];
t = x,x = y,y = t;x[sa[0]] = 0;p = 1;
for(int i = 1;i < n;i++)
x[sa[i]] = cmp(y,sa[i-1],sa[i],j) ? p-1 : p++;
}
}
void solve()
{
pos = strlen(op);
strncpy(op + pos,op,pos);n = strlen(op);
for(int i = 0;i < n;i++)r[i] = op[i];
r[n] = 0;
da(r , sa, n + 1,128);
for(int i = 1;i <= n;i++)
{
if(sa[i] < pos)printf("%c",r[sa[i] + pos - 1]);
}
printf("\n");
}
int main()
{
init();
readdata();
solve();
return 0;
}