hdu 1711 kmp

http://acm.hdu.edu.cn/showproblem.php?pid=1711

判断b是不是a字串,输出b在a位置下标

kmp模板题

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <queue>
#include <map>
#include <iostream>
#include <algorithm>
using namespace std;
#define RD(x) scanf("%d",&x)
#define RD2(x,y) scanf("%d%d",&x,&y)
#define RD3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define clr0(x) memset(x,0,sizeof(x))
#define eps 1e-9
const double pi = acos(-1.0);
typedef long long LL;
const int modo = 1e9 + 7;
const int maxn = 1e6 + 5,maxm = 1e4 + 5;
int a[maxn],b[maxm],next[maxm];
int n,m;
void setnext()
{
    int i = 0,j = -1;
    next[i] = j;
    while(i < m){
        if(j == -1 || b[i] == b[j]){
            i++;j++;
            next[i] = j;
        }
        else{
            j = next[j];
        }
    }
    return ;
}
int kmp()
{
    int i = 0,j = 0;
    setnext();
    while(i < n){
        if(j == -1 || a[i] == b[j]){
            ++i,++j;
            if(j == m)
                return i - m + 1;
        }
        else
            j = next[j];
    }
    return -1;
}
int main() {
    int _;RD(_);
    while(_--){
        RD2(n,m);
        for(int i = 0;i < n;++i){
            RD(a[i]);
        }
        for(int i = 0;i < m;++i)
            RD(b[i]);

        printf("%d
",kmp());
    }

    return 0;
}


原文地址:https://www.cnblogs.com/zibaohun/p/4046788.html