Power Strings(求循环次数最多的循环节 kmp)

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.

nxt数组典型应用求循环节

对于长度n 循环节次数就是n/(n-nxt[n]) 很容易推导

#include<cstdio>
#include<string.h>
using namespace std;
char s[400005];
int nxt[400005];
int n;
void get_nxt()
{
    int i=0;
    int k=-1;
    nxt[0]=-1;
    while(i<n)
    {
        if(k==-1||s[i]==s[k])
        {
            i++;
            k++;
            nxt[i]=k;
        }
        else
        {
            k=nxt[k];
        }
    }
    return;
}
int ans[400005];
int main()
{
    while(~scanf("%s",s))
    {
        n=strlen(s);
        get_nxt();
        int cnt=0;
        ans[++cnt]=n;
        int x=n;
        while(x)
        {
            x=nxt[x];
            if(x!=0)
            {
                ans[++cnt]=x;
            }
        }
        for(int i=cnt;i>=1;i--)
        {
            printf("%d%s",ans[i],i==1?"
":" ");
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/caowenbo/p/11852214.html