Description
The little cat is so famous, that manycouples tramp over hill and dale to Byteland, and asked the little cat to givenames to their newly-born babies. They seek the name, and at the same time seekthe fame. In order to escape from such boring job, the innovative little catworks out an easy but fantastic algorithm:
Step1. Connect the father's name and themother's name, to a new string S.
Step2. Find a proper prefix-suffix string ofS (which is not only the prefix, but also the suffix of S).
Example: Father='ala', Mother='la',we have S = 'ala'+'la' = 'alala'. Potential prefix-suffix strings of S are{'a', 'ala', 'alala'}. Given the string S, could you help the little cat towrite a program to calculate the length of possible prefix-suffix strings of S?(He might thank you by giving your baby a name:)
Input
The input contains a number of test cases.Each test case occupies a single line that contains the string S describedabove.
Restrictions: Only lowercase lettersmay appear in the input. 1 <= Length of S <= 400000.
Output
For each test case, output a single linewith integer numbers in increasing order, denoting the possible length of thenew baby's name.
SampleInput
ababcababababcabab
aaaaa
SampleOutput
2 4 9 18
1 2 3 4 5
解题思路:
先计算KMP中next数组的值,则从字符串的长度len开始记录答案,令i=len,每回将i=next[i],直到i=0(0不为答案)。
代码:(请不要直接拷贝哦)
#include <cstdio>
#include <cstring>
char st[400005];
int len,next[400005],ans[400005];
using namespace std;
inline void get_next()//KMP中求next数组的值
{
next[0]=-1;
int j=-1,i=0;
while (i<len)
if ((j==-1)||(st[i]==st[j])) next[++i]=++j;
else j=next[j];
}
int main()
{
while(~scanf("%s",st))//数据量不定时的另外一种写法,也可以写作"while (scanf("%s",st)!=EOF)"
{
len=strlen(st);//求长度
get_next();
int i=len,t=0;
while (i!=0) ans[t++]=i,i=next[i];//记录答案,利用next数组可以节约查询时间
for (i=t-1;i>0;i--) printf("%d ",ans[i]);
printf("%d\n",len);
}
return 0;
}