POJ2752 Seek the Name Seek the Fame

//4_7_19:	Seek the Name Seek the Fame Cat给婴儿取名字POJ2752
#include 
#include 
#include 
using namespace std;
const int maxc = 400000 + 10;
int  len;
int  suf[maxc];
int  ans[maxc];
char str[maxc];

void KMP()
{
	int i,j = 0,k = -1,count = 0;
	len = strlen(str);
	suf[0] = -1;
	while(j < len)
	{
		if(k == -1 || str[j] == str[k])
		{
			j ++;
			k ++;
			suf[j] = k;
		}
		else	k = suf[k];
	}
	i = len;
	while(suf[i] != 0)
	{
		ans[count++] = suf[i];
		i = suf[i];
	}
	for(i = count - 1;i >= 0;i --)	printf("%d ",ans[i]);
	printf("%d\n",len);
}
int main()
{
	while(scanf("%s",str) != EOF)
		KMP();
	return 0;
}
/*测试结果:通过POJ2752检测
ababcababababcabab
2 4 9 18
aaaaa
1 2 3 4 5
^Z
请按任意键继续. . .
*/

你可能感兴趣的:(数据结构编程实验04)