POJ 2406 - Power Strings - [KMP求最小循环节]

Posted tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ 2406 - Power Strings - [KMP求最小循环节]相关的知识,希望对你有一定的参考价值。

题目链接:http://poj.org/problem?id=2406

Time Limit: 3000MS Memory Limit: 65536K

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

题意:

求给出字符串,最多是多少个循环节组成的。

题解:

利用len % (len-Next[len]) == 0的话,len-Next[len]是最小循环节长度的性质。

AC代码:

#include<cstdio>
#include<cstring>
using namespace std;

const int MAXpat = 1000000+5;

char pat[MAXpat];
int Next[MAXpat],len;

void getNext()
{
    int i=0, j=-1;
    len=strlen(pat);
    Next[0]=-1;
    while(i<len)
    {
        if(j == -1 || pat[i] == pat[j]) Next[++i]=++j;
        else j=Next[j];
        //printf("now i=%d j=%d next[%d]=%d pat[%d]=%c\\n",i,j,i,Next[i],i,pat[i]);
    }
}
int main()
{
    while(scanf("%s",pat))
    {
        if(pat[0]==\'.\' && pat[1]==\'\\0\') break;
        getNext();
        if(len%(len-Next[len])==0) printf("%d\\n",len/(len-Next[len]));
        else printf("1\\n");
    }
}

注意:

①当且仅当len%(len-Next[len])==0时,len-Next[len]才是最小循环节长度。

②关于Next数组,我觉得这个图很不错的展示了Next数组存储了啥:

  

以上是关于POJ 2406 - Power Strings - [KMP求最小循环节]的主要内容,如果未能解决你的问题,请参考以下文章

poj 2406 Power Strings

POJ - 2406 Power Strings

POJ——T 2406 Power Strings

poj 2406 Power Strings

poj2406 Power Strings

Poj 2406Power Strings