AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=1e7;
int s[maxn],p[maxn],nxt[maxn];
int n,m;
void getNext(){
int j=0,k=-1;
nxt[0]=-1;
while(j<m){
if(k==-1||p[k]==p[j]){
k++;
j++;
nxt[j]=k;
}
else k=nxt[k];
}
}
int kmp(){
int j=0,i=0;
getNext();
while(i<n){
if(j==-1||s[i]==p[j]){
i++;
j++;
}
else j=nxt[j];
if(j==m)return i;
}
return -1;
}
int main(){
ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--){
cin>>n>>m;
for(int i=0;i<n;i++)
cin>>s[i];
for(int j=0;j<m;j++)
cin>>p[j];
if(kmp()==-1)cout<<-1<<endl;
else cout<<kmp()-m+1<<endl;
}
}
标签:nxt,HDU,Sequence,int,cin,++,maxn,1711,include From: https://blog.51cto.com/u_15958888/6044773