题目
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
翻译
给定两个数字序列:a[1]、a[2]、…、a[N] 和 b[1]、b[2]、…、b[M] (1 <= M <= 10000,1 <= N <= 1000000)。 你的任务是找到一个数 K,它使得 a[K] = b[1], a[K + 1] = b[2], … , a[K + M - 1] = b[ 米]。 如果存在多个K,则输出最小的一个。
输入
输入的第一行是一个数字T,表示案例的数量。 每个案例包含三行。 第一行是两个数字 N 和 M(1 <= M <= 10000,1 <= N <= 1000000)。 第二行包含 N 个整数,表示 a[1]、a[2]、…、a[N]。 第三行包含 M 个整数,表示 b[1]、b[2]、…、b[M]。 所有整数都在 [-1000000, 1000000] 范围内。
输出
对于每个测试用例,您应该输出一行,其中只包含上述 K。 如果不存在这样的 K,则输出 -1。
样本输入
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
样本输出
6
-1
#include <iostream>
using namespace std;
int Next[10100];
int n[1000100], m[10100];
void getNext(int M) { //获取Next数组,怎么获取的暂时不知
int i = -1, j = 0;
Next[0] = -1;
int len = M;
while (j < len) {
if (i == -1 || m[i] == m[j]) {
i++, j++;
if (m[i] == m[j])Next[j] = Next[i];
else Next[j] = i;
}
else i = Next[i];
}
return;
}
void Kmp(int M, int N) { //KMP算法
bool cnt = 1;
int i = 0, j = 0;
getNext(M);
while (j < N) {
if (i == -1 || m[i] == n[j]) {
i++, j++;
if (i == M) {
cnt = 0;
cout << j + 1 - M << endl; //j+1-M即为开始的位置(如果存在的话)
break;
}
}
else i = Next[i];
}
if (cnt)cout << "-1" << endl;
}
int main() {
int T;
cin >> T;
int M, N;
while (T--) {
memset(Next, 0, sizeof(Next));
cin >> N >> M;
for (int i = 0; i < N; i++) {
cin >> n[i];
}
for (int i = 0; i < M; i++) {
cin >> m[i];
}
Kmp(M, N);
}
return 0;
}