poj 2752 kmp(next数组模板)

http://poj.org/problem?id=2752

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数组的理解题。首先,next数组存储的是i位置向前next[i]个字符和开头的next[i]个字符完全相同,换句话说,如果i位置往后的i+1位置失配后要将字符串的next[i]位置移动到i位置,继续进行匹配。那么,对于本题而言,ababcababababcabab为例,位置从0~17,17位置的b考虑其next值为8,由于前面有一个零位置,则前缀和后缀相等的长度为9,指针移动到8位置,同理考虑8的next值为3则取长度为4 的前缀,这里需要注意的是对于8位置其前4个和其后4个的字符是相同的,又因为其自身与后缀的8个字符又是完全相同的,我们可以得出 该串的前4个字符和其后四个字符相同,也就是和整个串的后4个字符是相同的。以此类推,前4个,前两个……我们就可以得出结论:从末位置开始每次移动到其next位置,并将next+1记录就得出了答案。详见代码:

#include <string.h>
#include <stdio.h>
const int N=400005;
int next[N],b[N],len;
char a[N];
void  get_next()//kmp算法求next数组模板
{
    int i,j;
    next[0]=j=-1;
    for(i=1;i<len;i++)
    {
        while(j>-1&&a[j+1]!=a[i])
            j=next[j];
        if(a[1+j]==a[i])
            j++;
        next[i]=j;
    }
    /*for(i=0;i<len;i++)
        printf("%d ",next[i]);
    printf("\n");*/
}
int main()
{
    while(~scanf("%s",a))
    {
        len=strlen(a);
        get_next();
        int m=len-1,k=0;
        b[0]=len;//每个串自身都是一个前缀等于后缀的串
        while(next[m]!=-1)
        {
            b[++k]=next[m]+1;
            m=next[m];//移动指针位置
        }
        for(int i=k;i>=0;i--)
           printf(i==0?"%d\n":"%d ",b[i]);
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值