Given a string, we need to find the total number of its distinct substrings.
Input
T- number of test cases. T<=20; Each test case consists of one string, whose length is <= 50000
Output
For each test case output one number saying the number of distinct substrings.
Example
Input: 2 CCCCC ABABA Output: 5 9
求字符串字串的种类
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int N = 50005;
int sa[N],Rank[N],height[N],c[N];
int n,m;
char str[N];
int cmp(int r[],int a,int b,int l){
return r[a]==r[b]&&r[a+l]==r[b+l];
}
void build_SA(int n){
int x[N],y[N];
//第一次基数排序
memset(c,0,sizeof(c));
for(int i=0;i<n;i++) c[x[i]=str[i]]++;
for(int i=1;i<m;i++) c[i]+=c[i-1];
for(int i=n-1;i>=0;i--) sa[--c[x[i]]]=i;
// 倍增算法
for(int k=1;k<=n;k<<=1){
int p=0;
for(int i=n-k;i<n;i++) y[p++]=i;
for(int i=0;i<n;i++) if(sa[i]>=k) y[p++]=sa[i]-k;
memset(c,0,sizeof(c));
for(int i=0;i<n;i++) c[x[y[i]]]++;
for(int i=1;i<m;i++) c[i]+=c[i-1];
for(int i=n-1;i>=0;i--) sa[--c[x[y[i]]]]=y[i];
swap(x,y);
p=1;
x[sa[0]]=0;
for(int i=1;i<n;i++)
x[sa[i]]=cmp(y,sa[i-1],sa[i],k)?p-1:p++;
if(p>=n) break;
m=p;
}
}
void get_Rank(int n){
for(int i=1;i<=n;i++)
Rank[sa[i]]=i;
}
void get_height(int n){
for(int i=0,k=0;i<n;i++){
if(k) k--;
int j=sa[Rank[i]-1];
while(i+k<n&&j+k<n&&str[i+k]==str[j+k]) k++;
height[Rank[i]]=k;
}
}
int main(){
int T;
scanf("%d\n",&T);
while(T--){
scanf("%s",str);
n=strlen(str);
str[n]=0;
m=125;
build_SA(n+1);
get_Rank(n);
get_height(n);
int ans;
if(n%2) ans=(n+1)/2*n;//总子串个数
else ans=n/2*(n+1);
for(int i=1;i<=n;i++)
ans-=height[i];
printf("%d\n",ans);
}
return 0;
}