Problem Description
Given two sequences of numbers : a[1], a[2], ...... , a[N], and b[1], b[2], ...... , b[M] (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make a[K] = b[1], a[K + 1] = b[2], ...... , a[K + M - 1] = b[M]. If there are more than one K exist, output the smallest one.
Input
The first line of input is a number T which indicate the number of cases. Each case contains three lines. The first line is two numbers N and M (1 <= M <= 10000, 1 <= N <= 1000000). The second line contains N integers which indicate a[1], a[2], ...... , a[N]. The third line contains M integers which indicate b[1], b[2], ...... , b[M]. All integers are in the range of [-1000000, 1000000].
Output
For each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.
Sample Input
Sample Output
-
Solution
kmp模版题目
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
inline int read(){
int x=,c=getchar(),f=;
for(;c<||c>;c=getchar())
if(!(c^))
f=-;
for(;c>&&c<;c=getchar())
x=(x<<)+(x<<)+c-;
return x*f;
}
int sub_l,tar_l,sub[],tar[],p[];
inline void pre(){
for(int i=,j=;i<=sub_l;i++){
while(j&&sub[j+]^sub[i])
j=p[j];
if(!(sub[j+]^sub[i]))
j++;
p[i]=j;
}
}
inline void kmp(){
int ans=-;
for(int i=,j=;i<=tar_l;i++){
while(j&&sub[j+]^tar[i])
j=p[j];
if(!(sub[j+]^tar[i]))
j++;
if(!(j^sub_l)){
ans=i-sub_l+;
break;
}
}
printf("%d\n",ans);
}
int main(){
int T=read();
while(T--){
tar_l=read(),sub_l=read();
memset(p,,sizeof(p));
for(int i=;i<=tar_l;i++)
tar[i]=read();
for(int j=;j<=sub_l;j++)
sub[j]=read();
pre(); kmp();
}
return ;
}