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
题目大意 : 一共由T个测试数据, 输入两个数组的长度N, M, 再分别输入两个数组 (从1 到 N 和 1 到 M), 如果数组2是数组1的子集, 则输入第一个匹配的下表, 如果不是,输出 -1
思路 :典型的KMP, 这道题要注意的就是是从1 到 N和 1 到 M输入的, 而不是字符串里的0开始, 所以nxt的初始化也要更改, 可以全部设为1, 然后所有i 和 j都往后移一位就可以了, 直到匹配的长度等于 数组 2 的长度, 输出这时候 i 所在的位置 - 数组2的长度。KMP基础题
AC代码 :
#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;
}