poj 2406 Power Strings【最小循环节】

时间:2023-03-08 17:39:29
poj 2406 Power Strings【最小循环节】
Power Strings
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 36926   Accepted: 15254

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
mp算法:
#include<stdio.h>
#include<string.h>
#define MAX 1100000
char str[MAX];
int f[MAX];
void getfail()//失配函数 此函数定义出的数组f表示当原字符串与目标字符串失配
{ //后可以根据f[]跳转到原字符串相应位置从而提高运算的效率
int i,j;
int len=strlen(str);
j=0;
f[0]=f[1]=0;
for(i=1;i<len;i++)
{
j=f[i];
while(j && str[i] != str[j])
j = f[j];
f[i+1] = str[i] == str[j]?j+1:0;
}
}
int main()
{
int n,m,j,i,s,t;
while(scanf("%s",str)&&str[0]!='.')
{
getfail();
int len = strlen(str);
if(len%(len-f[len]))//此处len-f[len]的意思是原字符串中最大循环节的长度
printf("1\n"); //len%(len-f[len]有余数则证明除去最大循环节所有的节数仍然有
//不可循环的字符
else
printf("%d\n",len/(len-f[len]));//如果原字符的最大循环节可以将整个字符串表示完毕
} //则输出循环次数
return 0;
}