【题意】给个字符串s,求它的类似循环次数,即它的字串看成x ,s=k*x,s是由几个x 叠加而成的 求k
【思路】kmp求 循环周期;一些KMP算法结论附在代码中
Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n).
Input
Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.
Output
For each s you should print the largest n such that s = a^n for some string a.
Sample Input
abcd aaaa ababab .
Sample Output
1 4 3
Hint
This problem has huge input, use scanf instead of cin to avoid time limit exceed.
Select Code
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxn=1e6+10;
int nex[maxn];
char s[maxn];
int getnex(int m){
int i=1,j=0;//初始化nex[0]=0,则j=nex[j-1]与其他人写的不一样,若初始化为-1,则j=nex[j]
memset(nex,0,sizeof(nex));
while(i<m){
if(s[i]==s[j])
nex[i++]=++j;
else if(!j)
++i;
else
j=nex[j-1]; //nex[]数组失配是总是要回溯到最近的循环节
} //所以j-nex[j-1]就是最小的循环长度
return i; //总结一下 求循环长度 若i%(i-nex[i-1]==0)&&nex[i-1]!=0
} //则说明字符串循环,长度为i/(i-nex[i-1]);(i为while(i<m)结束的值)
//详情可见https://www.cnblogs.com/jackge/archive/2013/01/05/2846006.html
int kmp(int n){
int i=0,j=0;
while(i<n&&j<n){
if(s[i]==s[j]){
++i;
++j;
}
else if(!j)
++i;
else
j=nex[j-1];
}
}
int main(){
while(scanf("%s",s)&&s[0]!='.'){
int n=strlen(s);
int i=getnex(n);
if(i%(i-nex[i-1])==0&&nex[i-1]!=0)
printf("%d\n",i/(i-nex[i-1]));
else printf("%d\n",1);
}
}