您的位置:首页 > 其它

POJ 2752 Seek the Name, Seek the Fame next数组理解加深

2016-03-24 21:38 302 查看
题意:给你一个字符串,寻找前缀和后缀相同的子串(包括原串)、 从小到大排列输出其子串的长度

思路:KMP next 数组应用、



其实就是一个数学推导过程、

首先由next数组 可知s(ab) = s(bd) 此时next[d]=b 而此时 next[b]=f,意味着s(ef)=s(gh)

 s(gh)属于s(ab) s(ab)=s(bd); 所以可以推出 s(gh)属于s(bd) 且s(ef)=s(gh) 所以 s(ef)属于s(cd)

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
const int qq=400000+10;
char node[qq];
int next[qq];
int get[qq];
int len;
void getnext()
{
int i,j;
i=0;j=-1;
next[0]=-1;
while(i<len){
if(j==-1||node[i]==node[j])
next[++i]=++j;
else
j=next[j];
}
return;
}
int main()
{
while(~scanf("%s",node)){
len=strlen(node);
getnext();
int k=len;
int i=0;
while(next[k]!=0){			// 那个公式的推导体现在这里、
get[i++]=next[k];
k=next[k];
}
for(int j=i-1;j>=0;--j)
printf("%d ",get[j]);
printf("%d\n",len);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: