您的位置:首页 > 其它

poj 2406 KMP算法中next的一个性质

2013-01-20 10:23 176 查看
问题是:如何快速找出S的最小循环周期(循环节)呢?

Len是s的长度

给出结论:如果len%(len-next[len-1])==0,则字符串中必存在最小循环节,且循环次数即为 len/(len-next[len-1])

所以这题知道了上述结论,写出NEXT即可求得循环周期。

#include <iostream>
#include <string.h>
using namespace std;

char b[1000000];
int next[1000000]; //数组一开始没开大,runtime error了...- -、

int main()
{
int temp,i;

while (cin>>b)
{
if (b[0]=='.')
break;
int len=strlen(b);

memset(next, 0, sizeof(next));
for (i = 1; i < len; i++)
{
temp = next[i - 1];
while (temp && b[temp] != b[i])
temp = next[temp - 1];
if (b[temp] == b[i])
next[i] = temp + 1;
else
next[i] = 0;
}

if (len%(len-next[len-1])==0)
cout<<len/(len-next[len-1])<<endl;
else
cout<<1<<endl;

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: