213 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 1 313 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 2 1
Sample Output
6-1
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int c[1000001],d[10001],f[10001];
int main()
{
int n,a,b,i,j,t,z;
scanf("%d",&n);
while(n--)
{
z=1;
scanf("%d%d",&a,&b);
for(i=0; i<=a-1; i++)
scanf("%d",&c[i]);
for(i=0; i<=b-1; i++)
scanf("%d",&d[i]);
f[0]=-1;
for(i=1; i<=b-1; i++)
{
j=f[i-1];
while(d[j+1]!=d[i]&&j>=0)
j=f[j];
if(d[j+1]==d[i])
f[i]=j+1;
else
f[i]=-1;
}
i=0;
j=0;
while(i<a)
{
if(c[i]==d[j])
{
i++;
j++;
if(j==b)
{
printf("%d\n",i-b+1);
z=2;
break;
}
}
else
{
if(j==0)
i++;
else
j=f[j-1]+1;
}
}
if(z==1)
printf("-1\n");
memset(c,0,sizeof(c));
memset(d,0,sizeof(d));
memset(f,0,sizeof(f));
}
}