poj——2752 KMP||NEX数组的活用,【经典题】

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:) 

题意大致就是给你一个字符串,求在长度相同的情况下,前缀和后缀是否相等,如果相等则记录长度,输出所有满足要求的长度

 

 

思路

这里用到了NXT数组也就是kmp问题中必须的一个数组,这里使用的是next数组的一个性质就是:在next数组的每一位中所储存的是距离i最近的且与m[i]相等的一个值(既:如果next[i]=t,那么m[i]==m[t],且t还意味着从字符开始处向后数t个单位在这个区间里的字符是跟i往前数t个单位的值是完全相同的,且顺序也一样)那么我们就可以直接从len-1的那个位置开始向后遍历,首先取t=next[len-1]然后依次取t=next[t]来遍历,如果m[t]==m[len-1]那么就记录长度,保存进数组中

代码

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

const int maxn=4e5+10;

int nxt[maxn];
char nm[maxn];
int put[maxn];
int len;

void getnxt()
{
    int i=0,j=-1;
    nxt[0]=-1;
    while(i<len)
    {
        if(j==-1||nm[i]==nm[j])
            nxt[++i]=++j;
        else j=nxt[j];
    }
}

int main()
{
    while(scanf("%s",nm)!=EOF)
    {
        len=strlen(nm);
        getnxt();
        int t=nxt[len-1];//先取next[len-1]找到除了本身以外最大长度的前缀,
        int cnt=0;
        while(t!=-1)
        {
            if(nm[t]==nm[len-1])
            {
                put[cnt++]=t+1;
            }
            t=nxt[t];
        }
        for(int i=cnt-1;i>=0;i--)
            printf("%d ",put[i]);
        printf("%d\n",len);
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值