题目:求一个串的最大的循环次数。

分析:dp。KMP,字符串。这里利用KMP算法。

            KMP的next函数是跳跃到近期的串的递归结构位置(串元素取值0 ~ len-1);

            由KMP过程可知:

            假设存在循环节,则S[0 ~ next[len]-1] 与 S[len-next[len] ~ len-1]相匹配;

            则S[next[len] ~ len-1]就是循环节(且最小)。否则next[len]为0;

            因此,最大循环次数为len/(len-next[len])。最小循环节为S[next[len] ~ len-1]。

说明:强大的KMP(⊙_⊙)。

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>

using namespace std;

char str[1000004];
int next[1000004];

void getnext( char *T, int L )
{
next[0] = -1;
int i = 0,j = -1;
while ( i < L ) {
if ( j == -1 || T[i] == T[j] ) {
i ++; j ++;
next[i] = j;
}else j = next[j];
}
}

int main()
{
while ( scanf("%s",str) && strcmp( str, "." ) ) {
int len = strlen(str);
getnext( str, len );
printf("%d\n",len/(len-next[len]));
}
return 0;
}