山东济南彤昌机械科技有限公司 山东济南江鹏工贸游有限公司

poj2406 Power Strings(kmp失配函数)

                                      Power Strings

Time Limit: 3000MS

 

Memory Limit: 65536K

Total Submissions: 39291

 

Accepted: 16315

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

Waterloo local 2002.07.01

 

【思路】

       KMP。

       应用KMP算法中的失配函数,如果是一个周期串那么错位部分(n-f[n])一定是一个最小循环节(仔细想想f函数的意义),则答案为i/(n-f[n])。否则ans=1。

   时间复杂度为O(n)。

【代码】

 

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #define FOR(a,b,c) for(int a=(b);a<=(c);a++)
 5 using namespace std;
 6 
 7 const int maxn = 1000000+10;
 8 
 9 void getFail(char* P,int* f) {
10     int m=strlen(P);
11     f[0]=f[1]=0;
12     for(int i=1;i<m;i++) {
13         int j=f[i];
14         while(j && P[i]!=P[j]) j=f[j];
15         f[i+1]=P[i]==P[j]?j+1:0;
16     }
17 }
18 
19 char s[maxn];
20 int f[maxn];
21 
22 int main() {
23     while(scanf("%s",s)==1 && s[0]!='.') {
24         getFail(s,f);
25         int n=strlen(s);
26         if(f[n]>0 && n%(n-f[n])==0) printf("%d\n",n/(n-f[n]));
27         else printf("%d\n",1);
28     }
29     return 0;
30 }

 

posted on 2015-11-28 17:44  hahalidaxin  阅读(379)  评论(0编辑  收藏  举报