后缀数组:SPOJ SUBST1 - New Distinct Substrings

时间:2021-09-07 04:45:35

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   题意:求一个字符串有多少不同子串
  LCP的应用,会打后缀数组的模板后就十分简单了
  后缀数组的理解:
  http://www.cnblogs.com/staginner/archive/2012/02/02/2335600.html
 #include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
const int maxn=;
char S[maxn];
int r[maxn],wa[maxn],wb[maxn],wv[maxn],ws[maxn],sa[maxn]; bool cmp(int *p,int i,int j,int l)
{return p[i]==p[j]&&p[i+l]==p[j+l];} void DA(int n,int m)
{
int i,j,p,*x=wa,*y=wb,*t;
for(i=;i<m;i++)
ws[i]=;
for(i=;i<n;i++)
++ws[x[i]=r[i]];
for(i=;i<m;i++)
ws[i]+=ws[i-];
for(i=n-;i>=;i--)
sa[--ws[x[i]]]=i; for(j=,p=;p<n;j<<=,m=p)
{
for(p=,i=n-j;i<n;i++)
y[p++]=i;
for(i=;i<n;i++)
if(sa[i]>=j)
y[p++]=sa[i]-j;
for(i=;i<n;i++)
wv[i]=x[y[i]];
for(i=;i<m;i++)
ws[i]=;
for(i=;i<n;i++)
++ws[wv[i]];
for(i=;i<m;i++)
ws[i]+=ws[i-];
for(i=n-;i>=;i--)
sa[--ws[wv[i]]]=y[i];
for(t=x,x=y,y=t,p=,x[sa[]]=,i=;i<n;i++)
x[sa[i]]=cmp(y,sa[i-],sa[i],j)?p-:p++;
}
} int rank[maxn],lcp[maxn];
void LCP(int n)
{
int i,j,k=;
for(i=;i<=n;i++)
rank[sa[i]]=i;
for(i=;i<n;lcp[rank[i++]]=k)
for(k?k--:k,j=sa[rank[i]-];r[i+k]==r[j+k];k++);
} int main()
{
int Q;
scanf("%d",&Q);
while(~scanf("%s",S))
{
int i,n;
long long ans=;
for(i=;S[i];i++)
r[i]=S[i];
DA(i+,);
LCP(i);
n=i;
for(i=;i<n;i++)
ans+=n-i-lcp[rank[i]];
printf("%d\n",ans);
}
return ;
}