KMP的精髓就在于next[]数组,求最小循环节是KMP的一个活用,当i%(i-next[i])==0,最小循环节存在,为i/(i-next[i])
这道题就是求前i个字符有几个最小循环节。
Period
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 18 Accepted Submission(s) : 9
3 aaa 12 aabaabaabaab 0
Test case #1 2 2 3 3 Test case #2 2 2 6 2 9 3 12 4
#include <iostream>
#include <cstring>
using namespace std;
int next[1000002];
char a[1000005];
int main()
{
int len,n,i,j,m;
m=1;
while(cin>>n&&n)
{
cin>>a;
len=strlen(a);
cout<<"Test case #"<<m++<<endl;
i=0,j=-1,next[0]=-1;
while(i<n)
{
if(j==-1||a[i]==a[j])
{
i++,j++;
if(i%(i-j)==0&&i/(i-j)>1)
cout<<i<<" "<<i/(i-j)<<endl;
if(a[i]!=a[j])
next[i]=j;
else
next[i]=next[j];
}
else
{
j=next[j];
}
}
cout<<endl;
}
}