首页 > 代码库 > POJ 2752 Seek the Name, Seek the Fame

POJ 2752 Seek the Name, Seek the Fame

Seek the Name, Seek the Fame

Time Limit: 2000ms
Memory Limit: 65536KB
This problem will be judged on PKU. Original ID: 2752
64-bit integer IO format: %lld      Java class name: Main
 
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 
 
 1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <climits> 7 #include <vector> 8 #include <queue> 9 #include <cstdlib>10 #include <string>11 #include <set>12 #include <stack>13 #define LL long long14 #define pii pair<int,int>15 #define INF 0x3f3f3f3f16 using namespace std;17 const int maxn = 400100;18 int fail[maxn],ans[maxn],tot;19 char str[maxn];20 void getFail() {21     fail[0] = fail[1] = 0;22     for(int i = 1; str[i]; i++) {23         int j = fail[i];24         while(j && str[j] != str[i]) j = fail[j];25         fail[i+1] = str[i] == str[j]?j+1:0;26     }27 }28 int main() {29     while(gets(str)) {30         getFail();31         int len = strlen(str);32         tot = 0;33         while(len) {34             ans[tot++] = len;35             len = fail[len];36         }37         for(int i = tot-1; i; i--)38             printf("%d ",ans[i]);39         printf("%d\n",ans[0]);40     }41     return 0;42 }
View Code

 

POJ 2752 Seek the Name, Seek the Fame