【题目】
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.
【分析】
大致意思:一个字符串由它的一个子串不断拼接而成,求最长拼接的长度
比如说样例, 就是由
拼接 3 次形成的,最长的长度也就是 3
很容易想到用 KMP 中的 next 数组求最小循环节,答案是
有一个要注意的地方是当 时,如
,答案也只能为 1
【代码】
#include<cstdio>
#include<cstring>
#include<algorithm>
#define L 1000005
using namespace std;
char s[L];
int next[L];
int main()
{
int i,j,l,ans;
scanf("%s",s+1);
while(s[1]!='.')
{
l=strlen(s+1);
j=0,next[1]=0;
for(i=2;i<=l;++i)
{
while(j&&s[i]!=s[j+1]) j=next[j];
if(s[i]==s[j+1]) ++j;
next[i]=j;
}
ans=1;
if(l%(l-next[l])==0)
ans=l/(l-next[l]);
printf("%d\n",ans);
scanf("%s",s+1);
}
return 0;
}