POJ 2752 Seek the Name, Seek the Fame

对字符串建一个next表,然后逆推即可。

#include<iostream>
#include<cstdio>
#include<cstring>
#define maxn 400005
using namespace std;
char p[maxn];
int next[maxn],t[maxn],l,tot=0;
void make_next()
{
memset(next,0,sizeof(next));
next[1]=0;
int cnt=0;
for (int i=2;i<=l;i++)
{
while (cnt>0 && p[i-1]!=p[cnt])
cnt=next[cnt];
if (p[i-1]==p[cnt]) cnt++;
next[i]=cnt;
}
}
void find()
{
t[++tot]=l;
int cnt=next[l];
while (cnt>0)
{
t[++tot]=cnt;
cnt=next[cnt];
}
for (int i=tot;i>=1;i--)
{
printf("%d ",t[i]);
t[i]=0;
}
printf(" ");
tot=0;
}
int main()
{
while (scanf("%s",p)!=EOF)
{
l=strlen(p);
make_next();
find();
}
return 0;
}

原文地址:https://www.cnblogs.com/ziliuziliu/p/5183436.html