705. New Distinct Substrings spoj(后缀数组求所有不同子串)

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

705. New Distinct Substrings

Problem code: SUBST1

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

Added by: Hoang Hong Quan
Date: 2006-01-18
Time limit: 2s
Source limit: 50000B
Memory limit: 256MB
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All except: NODEJS PERL 6
Resource: Base on a problem in ByteCode06
 
 
 
 
 
 
 
 
 #include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define N 51000
char a[N];
int c[N],d[N],e[N],sa[N],height[N],n,b[N],m;
int cmp(int *r,int a,int b,int l)
{
return r[a]==r[b]&&r[a+l]==r[b+l];
}
void da()
{
int i,j,p,*x=c,*y=d,*t;
for(i=;i<m;i++)b[i]=;
for(i=; i<n; i++)b[x[i]=a[i]]++;
for(i=; i<m; i++)b[i]+=b[i-];
for(i=n-; i>=; i--)sa[--b[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++)e[i]=x[y[i]];
for(i=;i<m;i++)b[i]=;
for(i=; i<n; i++)b[e[i]]++;
for(i=; i<m; i++)b[i]+=b[i-];
for(i=n-; i>=; i--)sa[--b[e[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++;
}
}
void callheight()
{
int i,j,k=;
for(i=; i<n; i++)b[sa[i]]=i;
n--;
for(i=; i<n; height[b[i++]]=k)
for(k?k--:,j=sa[b[i]-]; a[i+k]==a[j+k]; k++);
} int main()
{
int t,i;
cin>>t;
for(i=;i<t;i++)
{
scanf("%s",a);
n=strlen(a);
n++;
m=;
da();
callheight();
int sum=;
for(int j=;j<=n;j++)sum+=n-sa[j]-height[j];
cout<<sum<<endl;
}
}