18.12.16 DSA Seek the Name, Seek the Fame

描述

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:)

输入

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.输出For each test case, output a single line with integer numbers in increasing order, denoting the possible length of the new baby's name.

样例输入

ababcababababcabab
aaaaa

样例输出

2 4 9 18
1 2 3 4 5
 1 #include <iostream>
 2 #include <string.h>
 3 #include <algorithm>
 4 #include <stack>
 5 #include <string>
 6 #include <math.h>
 7 #include <queue>
 8 #include <stdio.h>
 9 #include <string.h>
10 #include <set>
11 #include <vector>
12 #include <fstream>
13 #define maxn 400005
14 #define inf 999999
15 #define cha 127
16 using namespace std;
17 
18 int Next[maxn], m;
19 char line[maxn];
20 
21 void findnext() {
22     int i = 0, k = -1;
23     m = strlen(line);
24     line[m] = '-';
25     m++;
26     Next[0] = -1;
27     while (i < m) {
28         while (k >= 0 && line[i] != line[k])
29             k = Next[k];
30         i++, k++;
31         if (i == m)break;
32         Next[i] = k;
33     }
34 }
35 
36 void solve() {
37     int k = Next[m-1];
38     set<int>ans;
39     while (k != 0&&k!=-1) {
40         ans.insert(k);
41         k = Next[k];
42     }
43     set<int>::iterator i1 = ans.begin(), i2 = ans.end();
44     for (; i1 != i2; i1++)
45         printf("%d ", *i1);
46     printf("%d\n", m - 1);
47 }
48 
49 void init() {
50     while (scanf("%s", line) != EOF) {
51         memset(Next, 0, sizeof(Next));
52         findnext();
53         solve();
54     }
55 }
56 
57 int main()
58 {
59     init();
60     return 0;
61 }
View Code

KMP的运用,期中好像考了差不多的?

posted @ 2018-12-16 18:56  TobicYAL  阅读(222)  评论(0编辑  收藏  举报