题目描述:
The little cat is so famous, that many couples tramp over hill and dale to Byteland, and asked the little cat to give names to their newly-born babies. They seek the name, and at the same time seek the fame. In order to escape from such boring job, the innovative little cat works out an easy but fantastic algorithm:
Step1. Connect the father’s name and the mother’s name, to a new string S.
Step2. Find a proper prefix-suffix string of S (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 to write 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 described above.
Restrictions: Only lowercase letters may appear in the input. 1 <= Length of S <= 400000.
Output
For each test case, output a single line with integer numbers in increasing order, denoting the possible length of the new baby’s name.
Sample Input
ababcababababcabab
aaaaa
Sample Output
2 4 9 18
1 2 3 4 5
题意:本题也就是给一个字符串,请你求他的前缀字符长度为多少的时候,正好也是他的后缀。
例如:
ababcababababcabab
前两个字符ab,同时他的后缀也是ab
前四个字符abab,同时他的后缀abab
大致这个意思。最后18是因为一个字符串肯定即是这个字符串的前缀和后缀。那么很明显了,就是对next数组的应用了。
next数组的最后一个值,就是符合条件的值。
举个例子:
abcabcabc
这两个字符串连接后的next数组是:
-1 0 0 0 1 2 3 4 5 6(注意:这个求next数组是并未有优化步骤)
我们发现next数组的最后一个值就是他的前缀和后缀相同的最大下标。
然后next[next[9]]就是第二大下标~~就这样一直下去,直到0为止。
#include"stdio.h"
#include"string.h"
void Get_next(char text[],int next[])
{
int i,j,len;
len=strlen(text);
next[0]=-1;
i=0;
j=-1;
while(i<len)
{
if(j==-1||text[i]==text[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
int digit[400001];
int main()
{
char text[400001];
int next[400001];
int i,j,len,k;
while(~scanf("%s",text))
{
Get_next(text,next);
len=strlen(text);
k=0;
int n=next[len];
digit[k++]=n;
while(n>0)
{
n=next[n];
digit[k++]=n;
}
for(int i=k-2;i>=0;i--)
printf("%d ",digit[i]);
printf("%d\n",len);
}
}