首页 > 代码库 > poj2752 Seek the Name, Seek the Fame

poj2752 Seek the Name, Seek the Fame

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

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


题目大意给出一个字符串str,求出str中存在多少子串,使得这些子串既是str的前缀,又是str的后缀。从小到大依次输出这些子串的长度。

例如:

ababcababababcabab

即是前缀又是后缀的串有

ab, abab, ababcabab, ababcababababcabab

【输入】

输入多组数据

一组数据行,一个字符串S   1 <= Length of S <= 400000.

【输出】

对于每组数据,输出整数从小到大依次表示这些子串的长度



kmp的next数组的巧妙应用,需要对next数组进行深入理解
技术分享
 1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 using namespace std; 6  7 const int maxn=400005; 8 int Next[maxn]; 9 int ans[maxn];10 char p[maxn];11 12 void get_next()13 {14     int len=strlen(p);15     int j,k;16     Next[0]=-1;17     j=0;k=-1;18     while(j<len)19     {20         if(k==-1||p[j]==p[k])21         {22             j++;k++;23             Next[j]=k;24         }25         else26             k=Next[k];27     }28 }29 30 31 int main()32 {33     while(scanf("%s\n",p)!=EOF)34     {35         memset(Next,0,sizeof(Next));36         memset(ans,0,sizeof(ans));37         get_next();38         for(int i=strlen(p);i;i=Next[i])39             ans[++ans[0]]=i;40         for(int i=ans[0];i>=1;i--)41             printf("%d ",ans[i]);42         cout<<endl;43         memset(p,0,sizeof(p));44     }45     return 0;46 }
View Code

 


技术分享

 

 

poj2752 Seek the Name, Seek the Fame