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
2
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 1 3
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 2 1
Sample Output
6
-1
这道题将KMP模板中的两个字符串匹配改成了两个数组,原理还是一样的。
本人并不太清楚KMP的原理,只是在模板的基础上进行了修改。
#include <stdio.h>
using namespace std;
const int N = 1e6;
int Next[N + 5];
int s1[N + 5], s2[N + 5];
int len1, len2;
void get_next()
{
int i, j;
i = 0;
Next[0] = j = -1;//第一个next值为-1
while(i < len2) {
if(j == -1 || s2[i] == s2[j]) Next[++i] = ++j;//如果最长前缀和最长后缀相同
else j = Next[j];//否则回退
}
}
void kmp()
{
int i, j;
i = j = 0;
while(i < len1) {
if(j == -1 || s1[i] == s2[j]) ++i, ++j;
else j = Next[j];
if(j == len2){
printf("%d\n",i - len2 + 1);
break;
}
}
if(j!=len2)
printf("-1\n");
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&len1,&len2);
for(int i=0;i<len1;i++)
scanf("%d",&s1[i]);
for(int i=0;i<len2;i++)
scanf("%d",&s2[i]);
get_next();
kmp();
}
return 0;
}