題目連接
題意:給定兩個整數序列,輸出一個模式序列在匹配序列第一次出現的位置。
分析:kmp模版題
#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstring>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <cstdio>
#include <algorithm>
#define INF 0x3f3f3f3f
#define PI acos(-1)
using namespace std;
typedef long long ll;
typedef pair<string, string> P;
const int mod=1e9+7;
const int maxn=1e6+10;
int nx[maxn];
int n,m;
void getnx(int *x){
//int m=x.size();
int i,j;
j=nx[0]=-1;
i=0;
while (i<m){
if (j==-1 || x[i]==x[j]){
i++,j++;
if (x[i]==x[j])
nx[i]=nx[j];
else nx[i]=j;
}
else j=nx[j];
}
}
int kmp(int *s, int *t) {
//int n=s.size();
//int m=t.size();
int i=0,j=0;
getnx(t);
while (i<n && j<m) {
while (-1!=j && s[i]!=t[j]) j=nx[j];
i++;
j++;
}
if (j==m)
return i-j+1;
else return -1;
}
int s[maxn],t[maxn];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
cin>>T;
while (T--){
cin>>n>>m;
for (int i=0; i<n; i++) cin>>s[i];
for (int i=0; i<m; i++) cin>>t[i];
cout<<kmp(s,t)<<endl;
}
return 0;
}