![]() | ||||||||||
| ||||||||||
Boring countingTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 1783 Accepted Submission(s): 721
Problem Description
035 now faced a tough problem,his english teacher gives him a string,which consists with n lower case letter,he must figure out how many substrings appear at least twice,moreover,such apearances can not overlap each other.
Take aaaa as an example.”a” apears four times,”aa” apears two times without overlaping.however,aaa can’t apear more than one time without overlaping.since we 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 into account.Therefore,the answer is 2(“a”,and “aa”).
Input
The input data consist with several test cases.The input ends with a line “#”.each test case contain a string consists with lower letter,the length n won’t exceed 1000(n <= 1000).
Output
For each test case output an integer ans,which represent the answer for the test case.you’d better use int64 to avoid unnecessary trouble.
Sample Input
Sample Output
|
思路:枚举字串长度,然后遍历height数组,找出满足这个长度且不重叠的子串数加入答案
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=1010;
int sa[maxn],height[maxn],rank[maxn],t[maxn],t2[maxn],c[maxn];
int n,ans;
string str;
void build_sa(int m,int n)
{
int *x=t,*y=t2;
for(int i=0;i<m;i++)c[i]=0;
for(int i=0;i<n;i++)c[x[i]=str[i]]++;
for(int i=1;i<m;i++)c[i]+=c[i-1];
for(int i=n-1;i>=0;i--)sa[--c[x[i]]]=i;
for(int k=1;k<=n;k<<=1)
{
int p=0;
for(int i=n-k;i<n;i++)y[p++]=i;
for(int i=0;i<n;i++)if(sa[i]>=k)y[p++]=sa[i]-k;
for(int i=0;i<m;i++)c[i]=0;
for(int i=0;i<n;i++)c[x[y[i]]]++;
for(int i=1;i<m;i++)c[i]+=c[i-1];
for(int i=n-1;i>=0;i--)sa[--c[x[y[i]]]]=y[i];
swap(x,y);
x[sa[0]]=0;p=1;
for(int 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 k=0;
for(int i=1;i<=n;i++)rank[sa[i]]=i;
for(int i=0;i<n;i++)
{
if(k)k--;
int j=sa[rank[i]-1];
while(str[i+k]==str[j+k])k++;
height[rank[i]]=k;
}
}
void judge(int len)
{
int mx=0,mn=10000000;
for(int i=1;i<=n;i++)
{
if(height[i]<len)
{
if(mx-mn>=len)
ans++;
mx=mn=sa[i];
}
else
{
mx=max(mx,sa[i]);
mn=min(mn,sa[i]);
}
}
if(mx-mn>=len)ans++;
}
void solve()
{
ans=0;
for(int i=1;i<=n;i++)
judge(i);
printf("%d\n",ans);
}
int main()
{
while(cin>>str)
{
if(str=="#")break;
n=str.size();
build_sa(123,n+1);
getheight(n);
solve();
}
return 0;
}