POJ 2752 KMP Next第二性质

26 篇文章 0 订阅
Seek the Name, Seek the Fame
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 22934 Accepted: 11947

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算法有这么一个性质

性质2:kmp的next不断向前递归的过程可以保证对于每一个当前前缀,都有一段后缀与之对应

那么我们显而易得 我们只要拿整个字符串的长度当作tmp 用tmp去向前递归 根据这一性质 一定会有相同后缀

那么求得的不就是答案了吗?

#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX_N = 400001;
int Next[MAX_N];
int ans[MAX_N];
char mo[MAX_N];
int n2;
void getnext(){
   int i=0,j=-1;
   while(i<n2){
    if(j==-1||mo[i]==mo[j]) {++i,++j,Next[i]=j;}
    else j = Next[j];
   }
   return ;
}
int main(){
    while(~scanf("%s",mo)){
        n2=strlen(mo);
        Next[0] = -1;
        getnext();
        int cnt = 0;
        int tmp = n2;
        while(tmp!=0){
            ans[cnt++] = tmp;
            tmp=Next[tmp];
        }
        for(int i=cnt-1;i>=0;i--)
            i==0?printf("%d\n",ans[i]):printf("%d ",ans[i]);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值