poj 2752 Seek the Name, Seek the Fame(kmp)

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以后 倒序一遍即可

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#define ll long long int
using namespace std;
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
int moth[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int dir[4][2]={1,0 ,0,1 ,-1,0 ,0,-1};
int dirs[8][2]={1,0 ,0,1 ,-1,0 ,0,-1, -1,-1 ,-1,1 ,1,-1 ,1,1};
const int inf=0x3f3f3f3f;
const ll mod=1e9+7;
int dp[400000+7];
void getnext(string s){
    dp[1]=0;
    for(int i=2,j=0;i<=s.length();i++){
        while(j>0&&s[i-1]!=s[j]) j=dp[j];
        if(s[i-1]==s[j]) j++;
        dp[i]=j;
    }
}
int main(){
    ios::sync_with_stdio(false);
    string s;
    while(cin>>s){
        getnext(s);
        stack<int> ss;
        int len=s.length();
        int tt=len;
        ss.push(len);
        while(1){
            if(dp[len]==0) break;
            ss.push(dp[len]);
            len=dp[len];
        }
        while(!ss.empty()){
            if(ss.top()!=tt)
            cout<<ss.top()<<" ";
            else cout<<ss.top();
            ss.pop();
        }
        cout<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wmj6/p/10496641.html