poj 2406:Power Strings(KMP算法,next[]数组的理解)

Power Strings
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 30069   Accepted: 12553

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

 
  KMP算法,next[]数组的理解
  这道题考察的是对next[]数组的理解。如果 i 能整除 (i-next[i]) 的话,证明在这个字符之前,是一个由同一前缀重复连接构成的字符串。例如:aabaabaabc,c位置的下标 i 就可以整除他的下标和next数组值的差(i-next[i]),则它之前的字符串aabaabaab就是一个重复字符串,构成它的前缀的长度就是 (i - next[i])。
  注意:输入以一个'.'结束;注意这一组测试数据“aabaabaa”,WA的可以测试一下,正确结果应该为1。
  如果觉得文字太枯燥可以猛戳这里:hdu 1358:Period(KMP算法,next[]数组的使用)
  代码
 #include <stdio.h>

 char s[];
int next[];
void GetNext(char a[],int next[],int n) //获得a数列的next数组
{
int i=,k=-;
next[] = -;
while(i<n){
if(k==-){
next[i+] = ;
i++;k++;
}
else if(a[i]==a[k]){
next[i+] = k+;
i++;k++;
}
else
k = next[k];
}
} int main()
{
while(scanf("%s",s)!=EOF){
if(s[]=='.') break;
int i;
for(i=;s[i];i++);
int len = i;
GetNext(s,next,len);
if(len%(len-next[len])==)
printf("%d\n",len/(len-next[len]));
else
printf("1\n");
}
return ;
}

Freecode : www.cnblogs.com/yym2013

上一篇:Linux的Cgroup<实例详解>


下一篇:junit测试套件