后缀数组模板题
1 #include<algorithm> 2 #include<cstdlib> 3 #include<cstring> 4 #include<cstdio> 5 #include<cmath> 6 using namespace std; 7 8 #define N 100010 9 10 int wa[N],wb[N],ws[N],wv[N]; 11 int sa[N],rank[N],height[N]; 12 int r[N]; 13 char s[N]; 14 15 int cmp(int *r,int a,int b,int l) 16 { 17 return r[a]==r[b] && r[a+l]==r[b+l]; 18 } 19 20 void da(int *r,int n,int m) 21 { 22 int i,j,p,*x=wa,*y=wb,*t; 23 for (i=0;i<m;i++) ws[i]=0; 24 for (i=0;i<n;i++) ws[x[i]=r[i]]++; 25 for (i=1;i<m;i++) ws[i]+=ws[i-1]; 26 for (i=n-1;i>=0;i--) sa[--ws[x[i]]]=i; 27 for (j=1,p=1;p<n;j<<=1,m=p) 28 { 29 for (p=0,i=n-j;i<n;i++) y[p++]=i; 30 for (i=0;i<n;i++) if (sa[i]>=j) y[p++]=sa[i]-j; 31 for (i=0;i<n;i++) wv[i]=x[y[i]]; 32 for (i=0;i<m;i++) ws[i]=0; 33 for (i=0;i<n;i++) ws[wv[i]]++; 34 for (i=1;i<m;i++) ws[i]+=ws[i-1]; 35 for (i=n-1;i>=0;i--) sa[--ws[wv[i]]]=y[i]; 36 for (t=x,x=y,y=t,p=1,x[sa[0]]=0,i=1;i<n;i++) 37 x[sa[i]]=cmp(y,sa[i-1],sa[i],j) ? p-1 : p++; 38 } 39 return ; 40 } 41 42 void calheight(int *r,int n) 43 { 44 int i,j,k=0; 45 for (i=1;i<=n;i++) rank[sa[i]]=i; 46 for (i=0;i<n;height[rank[i++]]=k) 47 for (k ? k-- : 0,j=sa[rank[i]-1];r[i+k]==r[j+k];k++); 48 return ; 49 } 50 51 int main() 52 { 53 scanf("%s",s); 54 int n=strlen(s); 55 for (int i=0;i<n;i++) 56 r[i]=s[i]-'a'+2; 57 r[n]=0; 58 da(r,n+1,30); 59 calheight(r,n); 60 for (int i=1;i<=n;i++) 61 printf("%d ",sa[i]+1); 62 printf(" "); 63 for (int i=2;i<=n;i++) 64 printf("%d ",height[i]); 65 return 0; 66 } 67