poj2406 power strings

来源:互联网 发布:JAVA string类型去空格 编辑:程序博客网 时间:2024/06/06 12:34
Power Strings
Time Limit: 3000MS Memory Limit: 65536KTotal Submissions: 48385 Accepted: 20137

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.

要找字符串的循环接 
利用next数组  里面存的是这一位之前的最大前后缀长度 。如果这个长度乘二等于字符串长度 那么正好两个。
如果大于 则说明有交叉的部分 此时 len-next[len]就是这个循环节的长度
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char a[1000005];
int n[1000005];
void kmp(int len)
{
    n[0]=-1;
    int k=-1;
    int j=0;
    while(j<=len)
    {
        if(k==-1||a[j]==a[k])
        {
            k++;
            j++;
            n[j]=k;
        }
        else k=n[k];
    }
}
int main()
{
    while(~scanf("%s",a))
    {
        if(a[0]=='.')break;
        int len=strlen(a);
        //memset(n,0,sizeof(n));
        kmp(len);
        if(len%(len-n[len])==0)
        cout<<len/(len-n[len])<<endl;
        else cout<<"1"<<endl;
    }
    return 0;
}