HDU-2752: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:)

kmp小裸题,千万不要优化nxt数组。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
char p[401000];
int len,now,nxt[401000],z[401000],top;
void work_nxt()
{
	int k=-1,j=0;nxt[0]=-1;
	while(j<len)
	{
		if(k==-1||p[j]==p[k])
		{
			j++,k++;
			nxt[j]=k;
		}
		else k=nxt[k];
	}
}
int main()
{
	while(scanf("%s",p)!=EOF)
	{
		len=strlen(p);
		work_nxt();
		top=0;
		now=len;
		while(nxt[now]!=-1)
		{
			z[++top]=nxt[now];
			now=nxt[now];
		}
		for(int i=top;i>=1;i--)
			if(z[i]>0)
			{
				printf("%d ",z[i]);
			}
		printf("%d\n",len);
	}
	return 0;
}

 

发表评论

邮箱地址不会被公开。 必填项已用*标注