http://acm.hdu.edu.cn/showproblem.php?pid=1358
题意 给出一个串,求其有循环节的前缀的最小循环节
如果对于next数组中的 i, 符合 i % ( i - next[i] ) == 0 && next[i] != 0 , 则说明字符串循环,而且
最小循环节长度为: i - next[i] 因为next数组失配的时候,总是回溯到最近的循环节,所以i-next[i]就是最小的循环节长度
最大循环次数为: i / ( i - next[i] )
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=1000010;
int nex[maxn];
char s[maxn];
void get_next(int len)
{
int i=0,j=-1;
nex[0]=-1;
while(i<len)
{
if(j==-1||s[i]==s[j])
{
i++;j++;
nex[i]=j;
}
else
j=nex[j];
}
}
int main()
{
int len,Cas=1;
while(~scanf("%d",&len)&&len)
{
scanf("%s",s);
get_next(len);
printf("Test case #%d\n",Cas++);
for(int i=2;i<=len;i++)
{
int tmp=i-nex[i];
if(i%tmp==0&&i/tmp>1)
printf("%d %d\n",i,i/tmp);
}
printf("\n");
}
return 0;
}