题意:给出模式串和目标串,如果模式串有在目标串出现,输出出现的位置(最小),否则输出-1.
题解:kmp模板题。
#include <stdio.h>
#include <string.h>
const int N = 1000005;
int p[N], t[N], len1, len2, next[N];
void getnext() {
int pp = -1, k = 0;
next[0] = -1;
while (k < len2) {
if (pp == -1 || p[pp] == p[k]) {
k++;
pp++;
next[k] = pp;
}
else
pp = next[pp];
}
}
int kmp() {
int pp = 0, tt = 0;
while (pp < len2 && tt < len1) {
if (pp == -1 || t[tt] == p[pp]) {
pp++;
tt++;
}
else
pp = next[pp];
}
if (pp == len2)
return tt - len2;
else
return -1;
}
int main() {
int cases;
scanf("%d", &cases);
while (cases--) {
scanf("%d%d", &len1, &len2);
for (int i = 0; i < len1; i++)
scanf("%d", &t[i]);
for (int i = 0; i < len2; i++)
scanf("%d", &p[i]);
getnext();
int ans = kmp();
if (ans != -1)
printf("%d\n", ans + 1);
else
printf("%d\n", ans);
}
return 0;
}