ProblemDescription
035 now faced atough problem,his english teacher gives him a string,which consists with nlower case letter,he must figure out how many substrings appear at leasttwice,moreover,such apearances can not overlap each other.
Take aaaa as an example.”a” apears four times,”aa” apears two times withoutoverlaping.however,aaa can’t apear more than one time without overlaping.sincewe can get “aaa” from [0-2](The position of string begins with 0) and [1-3].But the interval [0-2] and [1-3] overlaps each other.So “aaa” can not take intoaccount.Therefore,the answer is 2(“a”,and “aa”).
Input
The input dataconsist with several test cases.The input ends with a line “#”.each test casecontain a string consists with lower letter,the length n won’t exceed 1000(n<= 1000).
Output
For each test caseoutput an integer ans,which represent the answer for the test case.you’d betteruse int64 to avoid unnecessary trouble.
Sample Input
aaaa
ababcabb
aaaaaa
#
Sample Output
2
3
3
题目大意:求出有多少个子字符串重复了两次及其以上。
方法:通过后缀数组算出height值。暴力枚举子字符串的长度,计算重复的子字符串。
#include <iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<algorithm> using namespace std; int wa[1010] ,wb[1010] ,wv[1010] ,ws1[1010] ,sa[1010]; int rank1[1010],height[1010]; char str[1010]; int cmp(int *r,int a,int b,int l) {return r[a]==r[b]&&r[a+l]==r[b+l];} void da(char *r,int *sa,int n,int m) { int i,j,p,*x=wa,*y=wb,*t; for(i=0;i<m;i++) ws1[i]=0; for(i=0;i<n;i++) ws1[x[i]=r[i]]++; for(i=1;i<m;i++) ws1[i]+=ws1[i-1]; for(i=n-1;i>=0;i--) sa[--ws1[x[i]]]=i; for(j=1,p=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++) ws1[i]=0; for(i=0;i<n;i++) ws1[wv[i]]++; for(i=1;i<m;i++) ws1[i]+=ws1[i-1]; for(i=n-1;i>=0;i--) sa[--ws1[wv[i]]]=y[i]; for(t=x,x=y,y=t,p=1,x[sa[0]]=0,i=1;i<n;i++) x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++; } return; } void calheight(char *r,int *sa ,int n) { int i,j,k=0; for(i=1;i<=n;i++) rank1[sa[i]]=i; for(i=0;i<n;height[rank1[i++]]=k) for(k?k--:0,j=sa[rank1[i]-1];r[i+k]==r[j+k];k++); return; } int main() { int len ,ans ,flag; while(~scanf("%s",str)) { len = strlen(str); if(str[0]=='#'&&len==1) { break; } len++; da(str,sa,len,270); calheight(str,sa,len-1); ans = 0; int min1 ,max1; for(int i = 1;i<len;i++) { for(int j = 1;j<len;j++) { if(height[j] >= i) { min1 = max1 = sa[j-1]; flag = 0; for(;j < len;j++) { if(height[j] < i) { if(max1 - min1 >= i) { ans++; } flag = 1; break; } else { min1 = min(min1,min(sa[j-1],sa[j])); max1 = max(max1,max(sa[j-1],sa[j])); } } if(!flag) { if(max1 - min1 >= i) { ans++; } } } } } printf("%d\n",ans); } return 0; }