初学 Kmp ,推荐 严蔚敏教授 的数据结构视频11和12,讲解的很清楚。
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
int N, M, next[10005], S[1000005], T[10005];
void getNext() {
int j = 0, k = -1;
next[0] = -1;
while (j < M) {
if ((-1 == k) || (T[j] == T[k])) {
++j; ++k;
if (T[j] != T[k]) next[j] = k;
else next[j] = next[k];
}else k = next[k];
}
}
int Solve() {
int i = 0, j = 0;
while ((i < N) && (j < M)) {
if ((-1 == j) || (S[i] == T[j])) {
++i; ++j;
}else j = next[j];
}
if (M == j) return (i - M + 1);
else return -1;
}
int main() {
int Case;
scanf("%d", &Case);
while (Case--) {
scanf("%d %d", &N, &M);
for (int i = 0; i < N; ++i) {
scanf("%d", &S[i]);
}
for (int j = 0; j < M; ++j) {
scanf("%d", &T[j]);
}
getNext();
printf("%d\n", Solve());
}
return 0;
}