Seek the Name, Seek the Fame (POJ-2752)

题面

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.

样例输入

1ababcababababcabab
2aaaaa

样例输出

12 4 9 18
21 2 3 4 5

提示

思路

求所有公共前缀后缀长度

代码

 1char s[mxn], t[mxn];
 2int nxt[mxn], a[mxn];
 3
 4void getnxt(char* t, int m)
 5{
 6    int i = 0, j = -1; nxt[0] = -1;
 7    while (i < m)
 8    {
 9        if (j == -1 || t[i] == t[j]) {
10            i++, j++;
11            // if (t[i] == t[j])
12            //     nxt[i] = nxt[j]; // next数组优化
13            // else
14                nxt[i] = j;
15        } else
16            j = nxt[j];
17    }
18}
19
20int KMP(char* s, char* t, int n, int m)
21{
22    int i = 0, j = 0, ans = 0;
23    while (i < n)
24    {
25        if (j == -1 || s[i] == t[j]) {
26            i++, j++;
27            if (j >= m) {   // 匹配
28                // ans++;
29                // j = nxt[j];
30                return i-j;
31            }
32        } else
33            j = nxt[j];
34    }
35    // return ans;
36    return -1;
37}
38
39int main()
40{
41    while(scanf("%s", s) == 1)
42    {
43        int n = strlen(s), j=0;
44        getnxt(s, n);
45
46        for(int i=n; i>0; i=nxt[i]){
47            a[j++] = i;
48        }
49        for(int i=j-1; i>=0; i--){
50            printf("%d ", a[i]);
51        }
52        printf("\n");
53    }
54    return 0;
55}