一道裸的KMP题,用模板直接上就行
#include <iostream> #include <cstdio> using namespace std; int Next[10005],a[1000000+5],b[10000+5]; int i,j,n,m; void getNext() { Next[1] = 0;Next[0] =0; for(i = 1;i<m;i++) { j = Next[i]; while(j&&b[i]!=b[j])j = Next[j]; if(b[i] == b[j])Next[i+1] = j+1; else Next[i+1] = 0; } } void find() { getNext(); int i; int j = 0; for(i = 0;i<n;i++) { while(j&&a[i]!=b[j]){j = Next[j];} if(a[i] == b[j])j++; if(j == m){printf("%d\n",i-m+2);return;} } cout<<"-1"<<endl; } int main() { int t; scanf("%d",&t); while(t--) { cin>>n>>m; for(i = 0;i<n;i++) scanf("%d",&a[i]); for(i = 0;i<m;i++) scanf("%d",&b[i]); getNext(); find(); } return 0; }