首页 > 代码库 > hdu--1711--kmp应用在整形数组--Number Sequence

hdu--1711--kmp应用在整形数组--Number Sequence

/*
    Name: hdu--1711--Number Sequence
    Author: shen_渊 
    Date: 16/04/17 19:58
    Description: 第一次知道,KMP能用在整形数组 o(╯□╰)o 
*/

#include<cstring>
#include<iostream>
using namespace std;
int kmp();
void getFail();
int n,m;
int s1[1000009],s2[10009];
int f[10009];
int main()
{
//    freopen("in.txt","r",stdin);
    ios::sync_with_stdio(false);
    int T;
    cin>>T;
    while(T--){
        memset(s1,0,sizeof(0));
        memset(s2,0,sizeof(0));
        memset(f,0,sizeof(0));
        cin>>n>>m;
        for(int i=0; i<n; ++i)cin>>s1[i];
        for(int i=0; i<m; ++i)cin>>s2[i];
        if(n < m)cout<<"-1\n";
        else cout<<kmp()<<endl;
    }
    return 0;
}
void getFail(){
    f[0] = 0;f[1] = 0;
    for(int i=1; i<m; i++){
        int j = f[i];
        while(j && s2[i] != s2[j]) j = f[j];
        f[i+1] = s2[i] == s2[j] ? j+1:0;
    }
}
int kmp() {
    getFail();
    int j=0;
    for(int i=0; i<n; ++i){
        while(j && s2[j] != s1[i]) j=f[j];
        if(s2[j] == s1[i]) j++;
        if(j == m) return i-m+2;
    }
    return -1;
}

 

hdu--1711--kmp应用在整形数组--Number Sequence