POJ2752 Seek the Name, Seek the Fame —— KMP next数组

题目链接:https://vjudge.net/problem/POJ-2752

 

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

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

Source

 

 

题解:

找出即使前缀又是后缀的子串。

kmp的next数组的利用:对len通过next[]数组进行回溯,直到长度为1。

 

 

代码如下:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cstdlib>
 5 #include <string>
 6 #include <vector>
 7 #include <map>
 8 #include <set>
 9 #include <queue>
10 #include <sstream>
11 #include <algorithm>
12 using namespace std;
13 typedef long long LL;
14 const double eps = 1e-6;
15 const int INF = 2e9;
16 const LL LNF = 9e18;
17 const int MOD = 1e9+7;
18 const int MAXN = 2e6+10;
19 
20 char x[MAXN];
21 int Next[MAXN];
22 
23 void get_next(char x[], int m)
24 {
25     int i, j;
26     j = Next[0] = -1;
27     i = 0;
28     while(i<m)
29     {
30         while(j!=-1 && x[i]!=x[j]) j = Next[j];
31         Next[++i] = ++j;
32     }
33 }
34 
35 int ans[MAXN];
36 int main()
37 {
38     while(scanf("%s", x)!=EOF)
39     {
40         int len = strlen(x);
41         get_next(x, len);
42 
43         int cnt = 0;
44         for(int length = len; length!=0; length = Next[length])
45             ans[++cnt] = length;
46 
47         for(int i = cnt; i>=1; i--)
48             printf("%d ", ans[i]);
49         printf("\n");
50     }
51 }
View Code

 

posted on 2017-11-19 18:34  h_z_cong  阅读(178)  评论(0编辑  收藏  举报

导航