码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-03-22 22:37:47      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:targe   integer   line   rip   empty   efi   ace   space   esc   

题目链接: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求最小循环节]

标签:targe   integer   line   rip   empty   efi   ace   space   esc   

原文地址:https://www.cnblogs.com/dilthey/p/8626835.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!