POJ-2752(KMP(Seek the Name, Seek the Fame))

POJ-2752()(KMP)(Seek the Name, Seek the Fame)

Seek the Name, Seek the Fame
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 15833   Accepted: 8039

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


題意:判斷前綴和後綴是否相等,若相等,則輸出前綴的字符長度。注意;字符串本身可以看做後綴和前綴相等。這題主要是利用nest數組的優勢,判斷c[nest[len-1]]是否與c[len-1]相等,若相等則說明c{0,1,2...nest[len-1]},是符合題意的子串,該子串的長度爲y+1。(令y=nest[len-1]),用數組記錄下來,再繼續往下查找,y=nest[y],繼續判斷c[y]是否與c[len-1]相等,若符合題意,該子串的長度爲y+1,用數組記錄下來長度。一直遞歸下去,直到nest[y]=-1,結束遞歸。(因當nest[y]=0時,判斷第一個字符與最後一個字符是否相等,當nest[y]=-1時,說明此輪比較已經完成。

My  soution:

/*2016.4.12*/

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char c[400010];
int nest[400010],len,cnt[400010];
void getnest()
{
	int i=0,j=-1,k;
	nest[0]=-1;
	len=strlen(c);
	while(i<len)
	{
		if(j==-1||c[i]==c[j])
		{
			i++,j++;
			nest[i]=j;
		}
		else
		j=nest[j];	
	}
	return ;
}
void solve()
{
	int i=1,j,k,y,x;
	getnest();
	x=len-1;y=nest[x];
	while(y!=-1)
	{
		if(c[x]==c[y])
		cnt[i++]=y+1;//記錄子串長度 
		y=nest[y];//遞歸 
	}
	cnt[0]=len;//字符串本身也滿足前綴、後綴相等 
	for(j=i-1;j>0;j--)
	printf("%d ",cnt[j]);
	printf("%d\n",cnt[0]);	
}
int main()
{
	int i,j;
	while(scanf("%s",c)!=EOF)
	{
	    solve();
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章