spoj694 Distinct Substrings

来源:互联网 发布:java统计页面访问量 编辑:程序博客网 时间:2024/06/05 08:10

Description

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 <= 1000

Output

For each test case output one number saying the number of distinct substrings.

Example

Sample Input:
2
CCCCC
ABABA

Sample Output:
5
9

Explanation for the testcase with string ABABA: 
len=1 : A,B
len=2 : AB,BA
len=3 : ABA,BAB
len=4 : ABAB,BABA
len=5 : ABABA
Thus, total number of distinct substrings is 9.


Analysis

      统计本质不同的子串个数,用后缀数组

Code

//spoj694 Distinct Substrings#include <cstdio>#include <algorithm>#define maxn 1100using namespace std;int sa[maxn], wa[maxn], wb[maxn], wv[maxn], ws[maxn], rank[maxn],height[maxn];bool cmp(int *r, int a, int b, int l){return r[a]==r[b] and r[a+l]==r[b+l];}void build_sa(int *r, int* sa, int n, int m){int i, j, p, k=0, *t, *x=wa, *y=wb;for(i=0;i<m;i++)ws[i]=0;for(i=0;i<n;i++)ws[x[i]=r[i]]++;for(i=1;i<m;i++)ws[i]+=ws[i-1];for(i=n-1;i>=0;i--)sa[--ws[x[i]]]=i;for(p=1,j=1;p<n;m=p,j<<=1){for(p=0,i=n-j;i<n;i++)y[p++]=i;for(i=0;i<n;i++)if(sa[i]>=j)y[p++]=sa[i]-j;for(i=0;i<n;i++)wv[i]=x[y[i]];for(i=0;i<m;i++)ws[i]=0;for(i=0;i<n;i++)ws[wv[i]]++;for(i=1;i<m;i++)ws[i]+=ws[i-1];for(i=n-1;i>=0;i--)sa[--ws[wv[i]]]=y[i];for(t=x,x=y,y=t,x[sa[0]]=0,i=1,p=1;i<n;i++)x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++;}for(i=1;i<n;i++)rank[sa[i]]=i;for(i=0;i<n-1;height[rank[i++]]=k)for(k?k--:0,j=sa[rank[i]-1];r[i+k]==r[j+k];k++);}int main(){int T, x[maxn], i, j, ans;char s[maxn];scanf("%d",&T);while(T-->0){scanf("%s",s);for(i=0;s[i];x[i]=s[i],rank[i]=sa[i]=wa[i]=wb[i]=0,i++);x[i]=0;build_sa(x,sa,i+1,300);for(ans=0;i;i--)ans+=sa[i]+1-height[i];printf("%d\n",ans);}return  0;}



0 0
原创粉丝点击