poj2752 Seek the Name, Seek the Fame

Description

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

给一个串s,使它的长度为k的前缀和后缀相同,输出所有k
还是KMP……不过有点坑……原来想倒着做结果发现不对……最后灵机一动才想出做法
先求出s的next数组,然后j=n while (j){ans[++len]=j j=next[j]}这样就行了
这个还是要会到next的定义上去。
next[i]是当前这个匹配不成功的时候可以往前跳到的最长的状态。一开始j=n,然后每次求出一个j,那么j都是n往前跳到的某一个合法状态。
#include<cstdio>
#include<cstring>
char s[1000010];
int next[1000010];
int l,j;
int ans[1000010],len;
int main()
{
	while (~scanf("%s",s+1))
	{
		l=strlen(s+1);j=0;
		memset(next,0,sizeof(next));
		for (int i=2;i<=l;i++)
		{
			while (j>0 && s[j+1]!=s[i])j=next[j];
			if (s[j+1]==s[i])j++;
			next[i]=j;
		}
		j=l;len=0;
		while (j!=0)
		{
			ans[++len]=j;
			j=next[j];
		}
		for (int i=len;i;i--)printf("%d ",ans[i]);
		printf("
");
	}
	return 0;
}
——by zhber,转载请注明来源
原文地址:https://www.cnblogs.com/zhber/p/4162941.html