您的位置:首页 > 其它

SPOJ 694 后缀数组 解题报告

2017-07-28 19:07 295 查看
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.

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.

【解题报告】

题目:给定一个长为n(1≤n≤105 )的字符串,求出该字符串中不相同子串的个数。

子串即后缀的前缀。考虑得到SA数组后,按顺序一个一个加入后缀,加入一个长为len[i]的后缀则多了len[i]个子串(因为它有len[i]个前缀),但其中有重复的,显然重复了height[i]个,于是减去height[i]即可。

所以做法即每次累加(len[i]-height[i])即为答案。

不知道为什么SPOJ的数组的名称不能取rank。。。

代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 1010

int wa
,wb
,wsf
,wv
,sa
;
int rak
,height
,s
,a
;
char str
,str1
,str2
;

int cmp(int *r,int a,int b,int k)
{
return r[a]==r[b]&&r[a+k]==r[b+k];
}
void getsa(int *r,int *sa,int n,int m)
{
int i,j,p,*x=wa,*y=wb,*t;
for(i=0;i<m;++i) wsf[i]=0;
for(i=0;i<n;++i) wsf[x[i]=r[i]]++;
for(i=1;i<m;++i) wsf[i]+=wsf[i-1];
for(i=n-1;i>=0;--i) sa[--wsf[x[i]]]=i;
for(p=1,j=1;p<n;j*=2,m=p)
{
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) wsf[i]=0;
for(i=0;i<n;++i) wsf[wv[i]]++;
for(i=1;i<m;++i) wsf[i]+=wsf[i-1];
for(i=n-1;i>=0;--i) sa[--wsf[wv[i]]]=y[i];
swap(x,y);
x[sa[0]]=0;
for(p=1,i=1;i<n;++i)
x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++;
}
}
void getheight(int *r,int n)
{
int i,j,k=0;
for(i=1;i<=n;++i)  rak[sa[i]]=i;
for(i=0;i<n;++i)
{
k?k--:k=0;
j=sa[rak[i]-1];
while(r[i+k]==r[j+k]) ++k;
height[rak[i]]=k;
}
}
int t,ans,n,m;

int main()
{
int len;
for(scanf("%d",&t);t;--t)
{
scanf("%s",str);
len=strlen(str);
for(int i=0;i<=len-1;++i) s[i]=str[i];
s[len]=0;
getsa(s,sa,len+1,300);
getheight(s,len);
ans=(1+len)*len/2;
for(int i=2;i<=len;++i) ans-=height[i];
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: