首页 > 其他 > 详细

kuangbin专题十六:KMP & 扩展KMP & Manacher

时间:2021-04-17 22:47:40      阅读:35      评论:0      收藏:0      [点我收藏+]

HDU1711 Number Sequence

思路:kmp模板。

技术分享图片
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>

using namespace std;
const int maxm = 1e4 + 5;
const int maxn = 1e6 + 5;
int T, n, m;

int a[maxn], b[maxm];
int Next[maxm];

void genNext(){
    Next[0] = -1;
    int j = -1;
    for(int i = 1; i < m; i++){
        while(j != -1 && b[i] != b[j+1]) j = Next[j];
        if(b[i] == b[j+1]) j++;
        Next[i] = j;
    }
}

int kmp(){
    int j = -1;
    for(int i = 0; i < n; i++){
        while(j != -1 && a[i] != b[j+1]) j = Next[j];
        if(a[i] == b[j+1]) j++;

        if(j == m-1)
            return i - m + 2;
    }
    return -1;
}

int main(){
    scanf("%d", &T);
    while(T--) {
        scanf("%d%d", &n, &m);
        for(int i = 0; i < n; i++) scanf("%d", a+i);
        for(int i = 0; i < m; i++) scanf("%d", b+i);

        genNext();
        printf("%d\n", kmp());
    }
    return 0;
}
View Code

 

HDU1686 Oulipo

思路:kmp模板。

技术分享图片
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn = 1e6 + 5;
const int maxm = 1e4 + 5;

char W[maxm], T[maxn];
int Next[maxm];

int Tn, n, m;

void genNext() {
    Next[0] = -1;
    int j = -1;
    for (int i = 1; i < m; i++){
        while(j != -1 && W[i] != W[j+1]) j = Next[j];
        if(W[i] == W[j+1]) j++;
        Next[i] = j;
    }
}

int kmp(){
    int j = -1, res = 0;
    for(int i = 0; i < n; i++){
        while(j != -1 && T[i] != W[j+1]) j = Next[j];
        if(T[i] == W[j+1]) j++;

        if (j == m-1)
            res++, j = Next[j];
    }
    return res;
}

int main(){
    scanf("%d", &Tn);
    while(Tn--){
        scanf("%s", W);
        scanf("%s", T);
        m = strlen(W), n = strlen(T);

        genNext();
        printf("%d\n", kmp());
    }
    return 0;
}
View Code

 

HDU2087 剪花布条

 

kuangbin专题十六:KMP & 扩展KMP & Manacher

原文:https://www.cnblogs.com/arch/p/14672046.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!