HDU1711
老套路:
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<memory.h>
using namespace std;
int a[1000010],b[1000010];
int Next[1000010],L1,L2,ans;
void _next()
{
int i,k;
Next[1]=0;
for(i=2,k=0;i<=L2;i++){//i不是从1开始
while(k&&b[i]!=b[k+1])k=Next[k];//k不能为0不然一直循环
if(b[i]==b[k+1]) k++;
Next[i]=k;
}
}
void _kmp()
{
_next();
int i,k;
for(i=1,k=0;i<=L1;i++){
while(k&&a[i]!=b[k+1]) k=Next[k];
if(a[i]==b[k+1]) k++;
if(k==L2){
ans=i-L2+1;
return;
}
}
}
int main()
{
int T,i;
scanf("%d",&T);
while(T--){
ans=-1;
scanf("%d%d",&L1,&L2);
for(i=1;i<=L1;i++) scanf("%d",&a[i]);
for(i=1;i<=L2;i++) scanf("%d",&b[i]);
if(L1>=L2)
_kmp();
printf("%d\n",ans);
}
return 0;
}
It is your time to fight!