【poj 2406】Power Strings

来源:互联网 发布:淘宝水星小飞船证吗 编辑:程序博客网 时间:2024/06/05 07:14
Power Strings
Time Limit: 3000MS Memory Limit: 65536KTotal Submissions: 50601 Accepted: 21105

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

abcdaaaaababab.

Sample Output

143

Hint

This problem has huge input, use scanf instead of cin to avoid time limit exceed.

Source

Waterloo local 2002.07.01


题意:给定一个长度不超过N(N <= 106)的字符串,它一定是某个串重复K次得到,求这个K的最大值。
题解:假设子串T重复K次后得到串S,那么T的长度一定为L = N/K(要整除),则T = S[1...L],将S拆分成K份,每份长度为L,则有
S[1...L] = S[L+1...2L] = S[2L+1...3L] = ... = S[(K-1)L+1...KL]
由于要保证K最大,势必L要取最小,所以根据Next函数的定义,有Next[KL] = (K-1)L;
即Next[N] = N - L,所以L = N - Next[N];
但是得出的长度L还要保证能被N整除,所以如果不能整除说明L = N,即K = 1;而如果能整除,那么K = N / (N - Next[N]);


代码:
#include<cstdio>#include<cstring>char p[1000005];int next[1000005];void makenext(){next[0]=0;int l=strlen(p);int k=0;int q=0;for(int i=1;i<l;i++){while(k>0&&p[i]!=p[k])k=next[k-1];if(p[i]==p[k])k++;next[i]=k;if(next[i]==0)q=i;} printf ("%d\n",(l % (q+1) == 0) ? (l / (q+1)) : 1); } int main(){scanf("%s",p);while(p[0]!='.'){makenext();scanf("%s",p);}    return 0;} 



原创粉丝点击