POJ 2752 Seek the Name, Seek the Fame(KMP next数组应用)

Seek the Name, Seek the Fame
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 9895 Accepted: 4748

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

              题目大意:给你一个串,求出它的所有前缀和后缀相同的前缀尾标,即长度。
  
       解题思路:next数组的应用,len可以的,next[len]也是可以的,找规律可以推断next[next[len]]也是可以的。然后规律就出来了,next数组真是强大!!
 
       题目地址:Seek the Name, Seek the Fame

AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char a[400005];
int next[400005],len,res[400005];

void getnext()
{
     int i,j;
     next[0]=0,next[1]=0;
     for(i=1;i<len;i++)
     {
          j=next[i];
          while(j&&a[i]!=a[j])
               j=next[j];
          if(a[i]==a[j])
               next[i+1]=j+1;
           else
               next[i+1]=0;
     }
}

int main()
{
     while(cin>>a)
     {
          len=strlen(a);
          getnext();
          res[0]=len;  //把所有结果保存起来,然后倒序输出.
          int i,j=next[len];
          int t=0;
          while(j!=0)
          {
               res[++t]=j;  
               j=next[j];   //寻找下一个前缀和后缀相同点
          }
          cout<<res[t];
          for(i=t-1;i>=0;i--)
               cout<<" "<<res[i];
          cout<<endl;
     }
}


  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值