KMP入门(周期)
Description
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.
解题思路:题目大意:给定一个字符串由某一个子串重复得来,求出重复的次数。
利用fail数组fail[len],子串循环的次数满足if(len%(len-fail[len])==0)
ans=len/(len-fail[len]);
ans=len/(len-fail[len]);
否则ans=1
#include<iostream> #include<cstdio> #include<cstring> using namespace std; char s[1000005]; int fail[1000005]; int len; void get_fail(); int main() { while(scanf("%s",s+1),s[1]!='.') { len=strlen(s+1); get_fail(); int ans=1; //ÀûÓÃfail[len] if(len%(len-fail[len])==0) ans=len/(len-fail[len]); printf("%d\n",ans); } } void get_fail() { memset(fail,0,sizeof(fail)); fail[0]=-1; for(int i=1;i<=len;i++) { int p=fail[i-1]; while(p>=0&&s[p+1]!=s[i]) p=fail[p]; fail[i]=p+1; //cout<<i<<" "<<fail[i]<<endl; } }

浙公网安备 33010602011771号