n-sa[k]+1-height[k] 累加
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 const int maxn=1000+10; 6 char s[maxn]; 7 int sa[maxn],t[maxn],t2[maxn],c[maxn]; 8 int rank[maxn],height[maxn]; 9 void build_sa(int n,int m) 10 { 11 int i,*x=t,*y=t2; 12 13 for(i=0;i<m;i++) c[i]=0; 14 for(i=0;i<n;i++) c[x[i]=s[i]]++; 15 for(i=1;i<m;i++) c[i]+=c[i-1]; 16 for(i=n-1;i>=0;i--) sa[--c[x[i]]]=i; 17 for(int k=1;k<=n;k<<=1) 18 { 19 int p=0; 20 for(i=n-k;i<n;i++) y[p++]=i; 21 for(i=0;i<n;i++) if(sa[i]>=k) y[p++]=sa[i]-k; 22 23 for(i=0;i<m;i++) c[i]=0; 24 for(i=0;i<n;i++) c[x[y[i]]]++; 25 for(i=1;i<m;i++) c[i]+=c[i-1]; 26 for(i=n-1;i>=0;i--) sa[--c[x[y[i]]]]=y[i]; 27 28 swap(x,y); 29 p=1;x[sa[0]]=0; 30 for(i=1;i<n;i++) 31 x[sa[i]]=y[sa[i-1]]==y[sa[i]]&&y[sa[i-1]+k]==y[sa[i]+k]?p-1:p++; 32 if(p>=n) break; 33 m=p; 34 } 35 } 36 void getHeight(int n) 37 { 38 int i,k=0; 39 for(i=1;i<=n;i++) rank[sa[i]]=i; 40 for(i=0;i<n;i++) 41 { 42 if(k) k--; 43 int j=sa[rank[i]-1]; 44 while(s[i+k]==s[j+k]) k++; 45 height[rank[i]]=k; 46 } 47 } 48 49 int main() 50 { 51 int t,n; 52 scanf("%d",&t); 53 while(t--) 54 { 55 getchar(); 56 scanf("%s",s); 57 n=strlen(s); 58 build_sa(n+1,128); 59 getHeight(n); 60 long long ans=0; 61 for(int i=1;i<=n;i++) 62 ans+=n-sa[i]-height[i]; 63 printf("%lld ",ans); 64 } 65 return 0; 66 }