You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include "bits/stdc++.h"
using namespace std;
const int N = 100010, M = 1000010;
int n, m;
int ne[N];
// KMP算法的模板例题. 只不过需要换成int进行操作
int s[M], p[N]; // p串短用n,s串长用m,变量名称不要记忆错误
int main() {
int T;
scanf("%d", &T);
while (T--) {
scanf("%d %d", &m, &n);
for (int i = 1; i <= m; i++) scanf("%d", &s[i]); //原串
for (int i = 1; i <= n; i++) scanf("%d", &p[i]); //模式串
// 求NE数组
for (int i = 2, j = 0; i <= n; i++) {
while (j && p[i] != p[j + 1]) j = ne[j];
if (p[i] == p[j + 1]) j++;
ne[i] = j;
}
// KMP
bool flag = false;
for (int i = 1, j = 0; i <= m; i++) {
while (j && s[i] != p[j + 1]) j = ne[j];
if (s[i] == p[j + 1]) j++;
if (j == n) {
// 由于题目题目描述的数组下标从1开始所以追加1
printf("%d\n", i - n + 1);
flag = true;
//防止多次匹配成功本题要求输出第一个匹配所以需要及时break,并且注释掉 j=ne[j]
break;
// j = ne[j];
}
}
//如果没有匹配成功,则输出-1
if (!flag) printf("%d\n", -1);
}
return 0;
}