poj-2752-Seek the Name, Seek the Fame

来源:互联网 发布:如何优化一个网站 编辑:程序博客网 时间:2024/06/03 17:22

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
kmp算法
这道题就是求即使前缀,又是后缀的所有子串的长度
kmp算法中next数组的应用

对于一个字符串s,如果s满足s[next[n-1]] == s[n-1],则s[0…next[n-1]]满足条件
若一个s的子串也满足条件,则这个子串也是s[0…next[n-1]]的子串
。。。
这样一直递归下去,就求出最后的解了

/*    Name: poj 2752    Author: long long ago    Date: 17/03/16 17:14    Description: http://poj.org/problem?id=2752  kmp*/#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#define N 400010using namespace std;int next[N];char s[N];int ans[N], cnt;void pre_kmp(int len){    int i, j;    j = next[0] = -1;    i = 0;    while(i < len){        while(j != -1 && s[i] != s[j])  j = next[j];        next[++i] = ++j;    }}void solve(int len){    int i, j, t;    cnt = 0;    pre_kmp(len);    t = next[len-1];    while(t != -1){        if (s[t] == s[len-1])   ans[cnt++] = t+1;        t = next[t];    }}int main(){#ifndef ONLINE_JUDGE     freopen("1.txt", "r", stdin);#endif      int i, j, k, len;    while(~scanf("%s", s)){        len = strlen(s);        solve(len);        for (i = cnt-1; i >= 0; i--){            cout << ans[i] << " ";        }        cout << len << endl;    }    return 0;}
0 0
原创粉丝点击