Files
python/TangDou/AcWing/Statemachine/HDU-1711-KMP.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

43 lines
1.4 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}