Power Strings
Language:Default
Power Strings
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.
Source |
next数组的利用
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN=1e6+7;
char s[MAXN];
int slen,nex[MAXN];
void GetNext()
{
int i,j;
i=0;
j=nex[0]=-1;
while(i<slen)
{
while(-1!=j && s[i]!=s[j]) j=nex[j];
nex[++i]=++j;
}
}
int main()
{
while(~scanf("%s",s)&&s[0]!='.')
{
slen=strlen(s);
GetNext();
int L=slen-nex[slen];//可能得最长长度循环子串
// printf("%d\n",slen/L);//不能直接这样输出,不然遇到abcabcabcab这样的情况,会WA的
int ans=1;
if(slen%L==0) ans=slen/L;//必须得先判断一下
printf("%d\n",ans);
}
return 0;
}