import java.util.Scanner;
public class Main{
static Scanner input = new Scanner(System.in);
static int[] x = new int[1000000];
static int[] y = new int[10000];
static int[] next = new int[10000];
static int xlength;
static int ylength;
static void CalculateNext(){
next[0] = -1; next[1] = 0;
for(int i=2;i<=ylength-1;i++){
next[i] = y[next[i-1]]==y[i-1]?next[i-1]+1:0;
}
}
static int KMP(){
CalculateNext();
int k = -1;
for(int i=0;i<=xlength-1;i++){
while(k>-1&&y[k+1]!=x[i]){
k=next[k];
}
if(y[k+1]==x[i])k++;
if(k==ylength-1) return i-ylength+1+1;
}
return -1;
}
public static void main(String[] args){
int count = input.nextInt();
for(int i=0;i<=count-1;i++){
xlength = input.nextInt();
ylength = input.nextInt();
for(int j=0;j<=xlength-1;j++){
x[j] = input.nextInt();
}
for(int j=0;j<=ylength-1;j++){
y[j] = input.nextInt();
}
System.out.println(KMP());
}
}
}
KMP-【java模板】
最新推荐文章于 2023-08-12 11:43:41 发布