【kmp算法next数组应用】Simpsons’ Hidden Talents HDU - 2594

Think:
1知识点:kmp算法next数组应用
2题意:输入两个串,询问“最长前后缀”,“最长前后缀”定义为:串ans为st1的前缀,st2的后缀,输出“最长前后缀”和“最长前后缀”的长度
3解题思路:连接串st1和st2,求next数组,next[len-1]表示串st的最大公共前后缀,需要判断len与len_st1和len_st2的长度,若len > len_st1 或 len > len_st2,则len = next[len-1];
4反思:
(1):next数组开小了
(2):strcar(st1, st2)函数拼接串st1和串st2时要求st1数组的内存存储空间可以存储长度为len_st1+len_st2的串;
——截图来自百度百科

以下为Time Limit Exceeded代码——next数组开小了以及st1数组开小了

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int max_size = 50414;

int _next[max_size];
char st1[max_size], st2[max_size];

void get_next(char *P, int len_P);

int main(){
    while(~scanf("%s %s", st1, st2)){
        int len1 = strlen(st1);
        int len2 = strlen(st2);
        strcat(st1, st2);
        int len = len1 + len2;

        get_next(st1, len);
        int cir_len = _next[len-1];
        while(cir_len > len1 || cir_len > len2){
            cir_len = _next[cir_len-1];
        }

        for(int i = 0; i < cir_len ; i++)
            printf("%c", st1[i]);
        if(cir_len) printf(" ");
        printf("%d\n", cir_len);
    }
    return 0;
}
void get_next(char *P, int len_P){
    int q, k;
    _next[0] = 0;
    k = 0;
    for(q = 1; q < len_P; q++){
        while(k > 0 && P[q] != P[k]){
            k = _next[k-1];
        }
        if(P[q] == P[k])
            k++;
        _next[q] = k;
    }
    return;
}

以下为Accepted代码

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int size_T = 50414;
const int size_P = size_T << 1;

int _next[size_P];
char st1[size_P], st2[size_T];

void get_next(char *P, int len_P);

int main(){
    while(~scanf("%s %s", st1, st2)){
        int len1 = strlen(st1);
        int len2 = strlen(st2);
        strcat(st1, st2);
        int len = len1 + len2;

        get_next(st1, len);
        int cir_len = _next[len-1];
        while(cir_len > len1 || cir_len > len2){
            cir_len = _next[cir_len-1];
        }

        for(int i = 0; i < cir_len ; i++)
            printf("%c", st1[i]);
        if(cir_len) printf(" ");
        printf("%d\n", cir_len);
    }
    return 0;
}
void get_next(char *P, int len_P){
    int q, k;
    _next[0] = 0;
    k = 0;
    for(q = 1; q < len_P; q++){
        while(k > 0 && P[q] != P[k]){
            k = _next[k-1];
        }
        if(P[q] == P[k])
            k++;
        _next[q] = k;
    }
    return;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值