您的位置:首页 > 其它

poj 2406 还是KMP的简单应用

2012-04-04 11:24 363 查看
记住KMP是多计算一位的。其中next[i]为不为自身的最大首尾重复子串长度。

位移j=i-next[i]可以看作是构成字符串s的字串(如果i%j==0,存在这样的构成),相应的重复次数也就是n/d。

a b c d *

next:-1 0 0 0 0 这时j=i-next[i]; 结果是j==i;于是得到i/j=1.

a b c a *

next:-1 0 0 0 1 这时j=i-next[i]; 结果是i%j!=0.但是结果还是1。所以这题要考虑如果i%j!=0时也要输出1.即自身。这只是字串等于自身的一种情况。上面的那种情况也是一种

#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

#define N 1000001
int next
;

void get_next(char *s)
{
int i=0,j=-1,len=strlen(s);
next[i]=j;
while(i<len)
{
while(j>=0 && s[i]!=s[j]) j=next[j];
i++; j++;
next[i]=j;
}
}

int main()
{
char str
;
int i,j;
freopen("acm.txt","r",stdin);
while(scanf("%s",str)!=EOF && str[0]!='.')
{
get_next(str);
i=strlen(str);
j=i-next[i];
if(i%j==0)
printf("%d\n",i/j);
else
printf("1\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: