后缀数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
#include<vector>
#include<stack>
#include<string>
#include<cstring>
#include<map>
using namespace std;
#define ll long long
#define R register
#define fo(a,b,c) for(R int a=b;a<=c;++a)
#define mmt(x,y) memset(x,y,sizeof(x))
#define dbg(x) cout<<#x<<" = "<<x<<'\n'
#define maxn 1000010
char a[maxn];
int tmp[maxn],tax[maxn],rak[maxn],sa[maxn],n,m;
void jsort()
{
fo(i,0,m)tax[i]=0;
fo(i,1,n)tax[rak[i]]++;
fo(i,1,m)tax[i]+=tax[i-1];
for(int i=n;i;--i)sa[tax[rak[tmp[i]]]--]=tmp[i];
}
int main()
{
scanf("%s",a+1);n=strlen(a+1);
fo(i,1,n)rak[i]=a[i],tmp[i]=i;
m=127;jsort();
for(int w=1,p=0;p<n;w<<=1,m=p)
{
p=0;
fo(i,n-w+1,n)tmp[++p]=i;
fo(i,1,n)if(sa[i]>w)tmp[++p]=sa[i]-w;
jsort();swap(rak,tmp);
rak[sa[1]]=1;p=1;
fo(i,2,n)rak[sa[i]]=(tmp[sa[i]]==tmp[sa[i-1]]&&tmp[sa[i]+w]==tmp[sa[i-1]+w])?p:++p;
}
for(int i=1,j=0,k=0;i<=n;heig[rak[i++]]=k)
for(k=k?k-1:k,j=sa[rak[i]-1];a[i+k]==a[j+k];++k);
return 0;
}
显示 Gitment 评论