POJ2406 Power Strings KMP-next数组的循环节

来源:互联网 发布:stereonet软件百度云 编辑:程序博客网 时间:2024/05/21 10:11

题目大意:给定一个字符串,让你找出该字符串的最大循环节。


分析:next数组的循环节问题。一开始我是暴力next数组的每一个值,找出其中满足循环的最大值,后来发现这样做不可行,因为对于aaaaaab这个字符串来说,他的循环节很明显为1,但aaaaaa这个子串的循环节是6,所以找出整个next数组的最大循环节就出错了。其实我们只需找出next[ len ]这一个值的循环节即可,因为这是个后缀,和这个后缀相同的循环体自然包含了整个字符串。


实现代码如下:

#include <cstdio>#include <cstring>#include <iostream>using namespace std;#define maxn 1000005int next[maxn];char str[maxn];int len;void init_next(){    int i=0,j=-1;    next[0]=-1;    while(i<len)    {        if(j==-1||str[i]==str[j])        {            i++;            j++;            next[i]=j;        }        else j=next[j];    }}void solve(){    len=strlen(str);    init_next();    if(len%(len-next[len])==0)      printf("%d\n",len/(len-next[len]));    else puts("1");}int main(){    while(scanf("%s",str)&&str[0]!='.')      solve();    return 0;}


0 0
原创粉丝点击