【POJ2406】Power Strings(next数组周期串)

题目链接

Power Strings

Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 57893   Accepted: 24047

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中如果模式串第i位与文本串第j位不匹配,就要回到第next[i]位继续与文本串第j位匹配,则模式串第1位到next[n]与模式串第(n-next[n])位到n位是匹配的。所以如果n%(n-next[n])=0,则存在重复连续子串,长度为n-next[n],循环次数为n/(n-next[n])。

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+5;
char a[maxn];
int nex[maxn];
void makenext()
{
    int l=strlen(a);
    nex[0]=0;
    for(int p=1,k=0;p<l;p++)
    {
        while(k>0&& a[p]!=a[k])
            k=nex[k-1];
        if(a[p]==a[k])
            k++;
        nex[p]=k;
    }
}
int main()
{
    while(~scanf("%s",a))
    {
        memset(nex,0,sizeof(nex));
        if(a[0]=='.')break;
        int l=strlen(a);
        makenext();
        if(l%(l-nex[l-1])==0)printf("%d\n",l/(l-nex[l-1]));
        else printf("1\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39826163/article/details/81627981