這是一道kmp模板題商佑。
#pragma warning(disable:4996)
#include <stdio.h>
int main(void)
{
// freopen("q.txt", "r", stdin);
int T, t, s, f;
int strLen, featureLen;
unsigned int *stri, *feature, *next;
stri = new unsigned int[1000000];
feature = new unsigned int[10000];
next = new unsigned int[10000];
scanf("%d", &T);
next[0] = 0;
next[1] = 0;
for (t = 0; t < T; t++) {
// input
scanf("%d %d", &strLen, &featureLen);
for (s = 0; s < strLen; s++)
scanf("%d", &stri[s]);
for (f = 0; f < featureLen; f++)
scanf("%d", &feature[f]);
// kmp
// get next
for (s = 1, f = 0; s < featureLen - 1;) {
if (feature[s] == feature[f]) {
next[s + 1] = f + 1;
s++;
f++;
}
else {
if (f == 0) {
next[s + 1] = 0;
s++;
}
else {
f = next[f];
}
}
}
// search
for (s = 0, f = 0; s < strLen;) {
if (stri[s] == feature[f]) {
s++;
f++;
if (f == featureLen)
break;
}
else {
if (f == 0) {
s++;
}
else {
f = next[f];
}
}
}
if (f == featureLen)
printf("%d\n", s - featureLen + 1);
else
printf("-1\n");
}
return 0;
}