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
Title effect: a total of a T-test data, input two arrays of length N, M, and then two arrays are input (from 1 to N and 1 to M), if the array is an array 2 of the subset 1, the first input a match in the table, if not, the output of -1
Ideas: Typical KMP, this question should be noted that from 1 to N and 1 to M input, rather than a string of 0 in the beginning, so nxt initialization should change, can all be set to 1, then all i and j are moved back one on it, until the matching length equal to the length of the array 2, where positions i output at this time - the length of the array 2. KMP foundation problems
AC Code:
#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 1e4 + 5;
const int maxm = 1e6 + 5;
int a[maxm], b[maxn], nxt[maxn];
int n, m, T;
void getnext() {
nxt[1] = 0;
int i = 1, j = 0;
while (i <= m) {
if (!j || b[i] == b[j])
nxt[++i] = ++j;
else
j = nxt[j];
}
}
int KMP() {
getnext();
int i = 1, j = 1, sum = 0;
while (i <= n) {
if (!j || a[i] == b[j])
++i, ++j;
else
j = nxt[j];
if (j == m + 1) return i - m;
}
return -1;
}
int main()
{
scanf("%d", &T);
while (T--) {
scanf("%d%d", &n, &m);
memset(nxt, -1, sizeof(nxt));
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
for (int i = 1; i <= m; i++) scanf("%d", &b[i]);
cout << KMP() << endl;
}
return 0;
}