首页 > 代码库 > POJ - 2406 Power Strings

POJ - 2406 Power Strings

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.
KMP的循环体问题
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<cstring>
 5 
 6 using namespace std; 
 7 
 8 char s[1000005];
 9 int Next[1000005];
10 
11 void getnext(char* s,int m)
12 {
13     Next[0]=0;
14     Next[1]=0;
15     for(int i=1;i<m;i++)
16     {
17         int j=Next[i];
18         while(j&&s[i]!=s[j])
19             j=Next[j];
20         if(s[i]==s[j])
21             Next[i+1]=j+1;
22             else
23                 Next[i+1]=0;
24     }
25 }
26 
27 int main()
28 {
29     while(scanf("%s",s))
30     {
31         if(s[0]==.&&s[1]==\0)
32             break;
33         memset(Next,0,sizeof(Next));
34         int m=strlen(s);
35         getnext(s,m);
36         int x=1;
37         if(m%(m-Next[m])==0)
38             x=m/(m-Next[m]);
39         printf("%d\n",x);
40     }
41     
42     
43     return 0;
44 }

 

POJ - 2406 Power Strings