poj2752(KMP)

来源:互联网 发布:录制视频软件加快 编辑:程序博客网 时间:2024/05/18 06:40
Seek the Name, Seek the Fame
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 10065 Accepted: 4835

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

Source

POJ Monthly--2006.01.22,Zeyuan Zhu
 
本题要求给定的字符串的有哪些子串既是前缀又是后缀,输出这样的字符串的长度。
既是前缀又是后缀,可以联想到KMP算法中的next[]数组,保存的是末尾的与开头的最长匹配,然后依据next[][数组滑动,得到所有的,注意第一个与最后一个另作判断。
#include<iostream>#include<cstring>#include<cstdio>#include<vector>using namespace std;const int MAXN=400000+100;char str[MAXN];//W为模式串,T为主串int next[MAXN];vector<int>Vec;//KMP算法中计算next[]数组void getNext(char *p){    int j,k,len=strlen(p);    j=0;    k=-1;    next[0]=-1;    while(j<len)    {        if(k==-1||p[j]==p[k])        {            next[++j]=++k;        }        else k=next[k];    }}int main(){int len,i,tmp;while(~scanf("%s",str)){getNext(str);len=strlen(str);Vec.clear();tmp=len;while(!(tmp==0||tmp==-1)){Vec.push_back(tmp);tmp=next[tmp];}if(str[0]==str[len])Vec.push_back(1);for(i=Vec.size()-1;i>0;i--)printf("%d ",Vec[i]);printf("%d\n",Vec[0]);}return 0;}

原创粉丝点击