POJ2406-Power Strings

Power Strings
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 55320   Accepted: 22983

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.

       题解:题意就是由一个字符串重复多遍组成,求最多重复次数。

       也就是求这个字符串的最小长度即可。很明显与KMP的fail数组有关,求出可以发现如果重复次数大于1,那么n-fail[n]必定是最小的字符串长度。随便列几次就可以发现了。

Code:

#include<cstdio>  
#include<cstring>  
#include<algorithm>  
#include<iostream>  
using namespace std;  
#define N 1000005  
int next[N],len;
int main()  
{  
    char a[N];  
    while(~scanf("%s",a))  
    {
        if(a[0]=='.')break;  
        len=strlen(a);  
        int i=0,j=-1;  
        next[0]=-1;  
        while(i<len)  
        {  
            if(j==-1||a[i]==a[j])  
            {  
                i++,j++;  
                next[i]=j;  
            }else j=next[j];  
        }    
        int k=len-next[len];  
        if(len%k==0)printf("%d\n",len/k);  
            else printf("1\n");  
    }  
    return 0;  
}  

猜你喜欢

转载自blog.csdn.net/qq_34531807/article/details/80088456
今日推荐