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

版权声明:转载请标明出处 https://blog.csdn.net/weixin_41190227/article/details/86575024

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

题目大意 : 给出一个字符串str,求出str中存在多少子串,使得这些子串既是str的前缀,又是str的后缀。从小到大依次输出这些子串的长度。

思路:从Next数组的最后开始往前循环找或者递归找,最后再输出字符串本身的长度就可以了。

/*
@Author: Top_Spirit
@Language: C++
*/
//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std ;
typedef unsigned long long ull ;
typedef long long ll ;
const int Maxn = 4e5 + 10 ;
const int INF = 0x3f3f3f3f ;
const double PI = acos(-1.0) ;
const ull seed = 133 ;

string s ;
int len ;
int Next[Maxn] ;

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

int ans[Maxn] ;

int main (){
    while(cin >> s) {
        len = s.size() ;
        getNext() ;
        int k = 0 ;
        for (int i = len; i!= 0; ){
            ans[k++] = Next[i] ;
            i = Next[i] ;
        }
        sort(ans, ans + k - 1) ;
        for (int i = 0; i < k - 1; i++){
            cout << ans[i] << " " ;
        }
        cout << len << endl ;
    }
    return 0 ;
}

猜你喜欢

转载自blog.csdn.net/weixin_41190227/article/details/86575024