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[]数组的使用)
  代码
 1 #include <stdio.h>
 2 
 3 char s[1000001];
 4 int next[1000001];
 5 void GetNext(char a[],int next[],int n)    //获得a数列的next数组
 6 {
 7     int i=0,k=-1;
 8     next[0] = -1;
 9     while(i<n){
10         if(k==-1){
11             next[i+1] = 0;
12             i++;k++;
13         }
14         else if(a[i]==a[k]){
15             next[i+1] = k+1;
16             i++;k++;
17         }
18         else
19             k = next[k];
20     }
21 }
22 
23 int main()
24 {
25     while(scanf("%s",s)!=EOF){
26         if(s[0]=='.') break;
27         int i;
28         for(i=0;s[i];i++);
29         int len = i;
30         GetNext(s,next,len);
31         if(len%(len-next[len])==0)
32             printf("%d\n",len/(len-next[len]));
33         else
34             printf("1\n");
35     }
36     return 0;
37 }

 

Freecode : www.cnblogs.com/yym2013

posted @ 2014-04-26 21:47  Freecode#  阅读(520)  评论(0编辑  收藏  举报