Question: calculate the maximum number of cycles of a string.
Analysis: DP, KMP, String. The KMP algorithm is used here.
The next function of KMP jumps to the recursive structure position of the nearest string (the value of the string element is 0 ~ Len-1 );
The KMP process shows that:
If a circular section exists, s [0 ~ Next [Len]-1] and S [Len-next [Len] ~ Len-1] matching;
Then s [next [Len] ~ The len-1] is the loop section (and the smallest), otherwise next [Len] is 0;
Therefore, the maximum number of loops is Len/(LEN-next [Len]), and the minimum cycle is s [next [Len] ~. Len-1].
Note: Powerful 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;}