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

来源:互联网 发布:ndcg优化 编辑:程序博客网 时间:2024/06/05 05:39

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

Seek the Name, Seek the Fame
Time Limit: 2000MS Memory Limit: 65536KTotal 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

ababcababababcababaaaaa

Sample Output

2 4 9 181 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;}elsej=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;}


0 0