Seek the Name, Seek the Fame

Time Limit: 2000MS Memory Limit: 65536K

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

题意:

题目有个mo串,题目要求我们求出有多少个在mo串中前缀和后缀相等的字串,递增输出。

思路:

实际上就是求next数组,比如第一个例子中2, 4的时候当出现4的时候mo[4] = c但是前缀是abab,后缀也是abab,然后再2时候是前缀是ab,后缀是ab,所以就出现了2的前缀的等于4后缀的后缀(就是等于4后缀abab中的后面的ab),同理就可以得出其实虽然ab只是2位置上前缀和后缀相等,但对于整个是不影响的。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
const int maxn = 4e+5 + 10;
string mo;
int Next[maxn];
vector<int> v;
void GetNext() {
    int i = 0, j = -1;
    while (i < mo.size()) {
        if (j == -1 || mo[j] == mo[i]) Next[++i] = ++j;
        else j = Next[j];
    }
}
int main() {
    ios::sync_with_stdio(false);
    while (cin >> mo) {
        v.clear();
        Next[0] = -1;
        GetNext();
        int j = Next[mo.size()];
        while (j > 0) {
            v.push_back(j);
            j = Next[j];
        }
        for (int i = v.size() - 1; i >= 0; i--) {
            printf("%d ", v[i]);
        }
        printf("%d\n", mo.size());
    }
    return 0;
}