SPOJ Problem Set (classical)694. Distinct SubstringsProblem code: DISUBSTR |
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.
给定一个字符串,求不相同的子串的个数。
算法分析:
每个子串一定是某个后缀的前缀, 那么原问题等价于求所有后缀之间的不相
同的前缀的个数。如果所有的后缀按照 suffix(sa[1]), suffix(sa[2]),
suffix(sa[3]), …… ,suffix(sa[n])的顺序计算,不难发现,对于每一次新加
进来的后缀 suffix(sa[k]),它将产生 n-sa[k]+1 个新的前缀。但是其中有
height[k]个是和前面的字符串的前缀是相同的。所以 suffix(sa[k]) 将 “贡献 ”
出 n-sa[k]+1- height[k]个不同的子串。累加后便是原问题的答案。这个做法
的时间复杂度为 O(n)。
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
#define N 2000
int x[N],s[N],sa[N],rank[N],height[N],c[N],t1[N],t2[N];
void build_sa(int *s,int n,int m)
{
int *x=t1,*y=t2,i,k;
for(i=0;i<m;i++) c[i]=0;
for(i=0;i<n;i++) c[x[i]=s[i]]++;
for(i=1;i<m;i++) c[i]+=c[i-1];
for(i=n-1;i>=0;i--) sa[--c[x[i]]]=i;
for(k=1;k<=n;k<<=1)
{
int p=0;
for(i=n-k;i<n;i++) y[p++]=i;
for(i=0;i<n;i++) if(sa[i]>=k) y[p++]=sa[i]-k;
for(i=0;i<m;i++) c[i]=0;
for(i=0;i<n;i++) c[x[y[i]]]++;
for(i=1;i<m;i++) c[i]+=c[i-1];
for(i=n-1;i>=0;i--) sa[--c[x[y[i]]]]=y[i];
swap(x,y);
p=1; x[sa[0]]=0;
for(i=1;i<n;i++)
x[sa[i]]=y[sa[i-1]]==y[sa[i]]&&y[sa[i-1]+k]==y[sa[i]+k]?p-1:p++;
if(p>=n)
break;
m=p;
}
}
void getheight(int n)
{
int i,k=0,j;
for(i=0;i<=n;i++)
rank[sa[i]]=i;
for(i=0;i<n;i++)
{
if(k) k--;
j=sa[rank[i]-1];
while(s[j+k]==s[i+k])
k++;
height[rank[i]]=k;
}
}
int main()
{
int t,sum,n,i;
char str[N];
scanf("%d",&t);
while(t--)
{
scanf("%s",str);
n=strlen(str);
for(i=0;str[i]!='\0';i++)
s[i]=str[i];
s[n]=0;
build_sa(s,n+1,200);
getheight(n);
sum=0;
for(i=1;i<=n;i++)
sum+=n-sa[i]-height[i];
printf("%d\n",sum);
}
return 0;
}