欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Seek the Name, Seek the Fame

程序员文章站 2022-05-02 17:40:04
...

题目:

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


分析:

题意要求我们找出以各个首字符为开头的前缀与尾字符为结尾的后缀相匹配的长度,并且用升序输出。
我们由“Next 数组”的应用知道:Next[i]表示的是第i-1位为截止的重复出现的字符串的长度。那么直接在Next[i+1]这个数就是要求的最长的那个字符串,然后不停地向前回溯,每次回溯就是这个字符串的子字符串(结尾相同)的长度,直到回溯为0截止。


代码:

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;

int Next[4000005];
int ans[4000005];
char a_str[4000005];
int len;

void get_next(){
    int j = 0, k = -1;
    Next[0] = -1;
    while(j < len){
        if(k == -1 || a_str[j] == a_str[k]){
            k++;
            j++;
            Next[j] = k;
        }
        else
            k = Next[k];
    }
}

int main(){
    while(scanf("%s", a_str) != EOF) {
        len = strlen(a_str);
        get_next();
        int k = len;
        int j = 0;
        while(k != -1){
            ans[j++] = k;
            k = Next[k];
        }
        for(int i = j - 2; i >= 0; i--){
            (i != 0) ? (printf("%d ", ans[i])) : (printf("%d\n", ans[i]));
        }
    }
    return 0;
}