<pre name="code" class="html">#include<iostream>
using namespace std;
const int MAXN=1000000+10;
const int MAXM=10000+10;
int t[MAXN],p[MAXM],nex[MAXN];
void MakeNext(int M){
nex[0]=-1;
int i=0,j=-1;
while(i<M){
if(j==-1||p[i]==p[j]){
i++;
j++;
if(p[i]!=p[j]) nex[i]=j;
else nex[i]=nex[j];
}
else j=nex[j];
}
}
int kmp(int n,int m){
int i=0,j=0;
while(i<n&&j<m){
if(t[i]==p[j]||j==-1) i++,j++;
else j=nex[j];
}
if(j==m) return i-m+1;
else return -1;
}
int main(){
int n,m,c;
scanf("%d",&c);
while(c--){
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++) scanf("%d",&t[i]);
for(int i=0;i<m;i++) scanf("%d",&p[i]);
if(m>n) printf("-1\n");
else {
MakeNext(m);
printf("%d\n",kmp(n,m));
}
}
return 0;
}
tjut 1711
最新推荐文章于 2016-11-04 22:02:44 发布