题目链接
题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1711
题意
裸KMP算法
时间复杂度
O(m+n)
代码如下(G++)
#include <iostream>
#include "string.h"
using namespace std;
int a[1000010];
int b[10010];
int next0[10010];
int T,N,M;
void get_next(){
int i = 0;int j = -1;
next0[0] = -1;
while(i < M){
if(j == -1||b[i] == b[j]){
i++;j++; next0[i] = j;
}else{
j = next0[j];
}
// cout << i << " " << j << endl;
}
}
int KMP(){
int i = 0;int j = 0;
while(i < N && j < M){
if(j == -1 or a[i] == b[j])
++i,++j;
else
j = next0[j];
}
if(M == j) return i-j;
else return -2;
}
int main() {
ios::sync_with_stdio(false);
cin >> T;
while(T--){
cin >> N >> M;
for(int i = 0;i < N; ++i) cin >> a[i];
for(int j = 0;j < M; ++j) cin >> b[j];
get_next();
cout << KMP()+1 << endl;
}
return 0;
}