您的位置:首页 > 其它

POJ - 2752 Seek the Name, Seek the Fame (next 数组的应用)

2017-10-18 20:44 399 查看
https://cn.vjudge.net/contest/189927#problem/C

题意:就是问你前后缀相等的长度,从小到大去输出。

思路:nex数组里面存的就是当前的相等的前后缀长度,最长的相等前后缀就是他自己,之后的想澄清前后缀就是nex[len],之后一直输出直到nex[len]为0 就好了上代码:#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
char ch[400050];
int nex[400050],ans[400050];
void pre_kmp()
{
memset(nex , 0 ,sizeof(nex));
int len = strlen(ch) , k = -1 ,i = 0;
nex[0]=-1;
while(i < len)
{
if (k == -1 || ch[i] == ch[k])
{
i++;
k++;
nex[i]=k;
}
else k = nex[k];
}

}
int main()
{
while(scanf("%s",ch)!=EOF)
{
pre_kmp();
int cnt = 0;
int p = strlen (ch);
while(p>=1)
{
ans[cnt++]=p;
p = nex[p];
}
for(int i = cnt -1 ;i >=0 ; i--)
{
if(i == cnt-1)
{
printf("%d",ans[i]);
}
else
printf(" %d",ans[i]);
}
puts("");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: