在大话数据结构上看到的代码。
貌似效率不是很高 提交页面用时比这个少的一大堆
#include<iostream>
#include<cstdio>
using namespace std;
int S[1000010],T[10010],next[10010],N,M;
void GetNext()
{
int i=1,j=0; next[1]=0;
while(i<M)
{
if(j==0 || T[i]==T[j])
{
++i;++j;
if(T[i]!=T[j]) next[i]=j;
else next[i]=next[j];
}
else j=next[j];
}
}
int KMP()
{
int i=1,j=1;
while(i<=N&&j<=M)
{
if(j==0 || S[i]==T[j])
{
i++;j++;
}
else
{
j=next[j];
}
}
if(j>M) return i-M;
else return -1;
}
int main()
{
int i,j,t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&N,&M);
for(i=1;i<=N;i++) scanf("%d",&S[i]);
for(i=1;i<=M;i++) scanf("%d",&T[i]);
GetNext();
// for(i=1;i<=M;i++) printf("%d",next[i]);
printf("%d\n",KMP());
}
return 0;
}