hdu1711
大概这就是裸的
k
m
p
kmp
kmp 吧。
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e6+6;
int a[N], b[N], nxt[N];
int n, m;
void getNext(int *p)
{
int j = 1, k = 0;
nxt[1] = 0;
while (j <= m) {
if (k == 0 || p[j] == p[k]) {
++j;
++k;
if (p[j] != p[k]) nxt[j] = k;
else nxt[j] = nxt[k];
}
else k = nxt[k];
}
}
int kmp(int *a, int *b)
{
getNext(b);
int i = 1, j = 1;
while (i <= n && j <= m) {
if (j == 0 || a[i] == b[j]) {
++i;
++j;
}
else j = nxt[j];
}
if (j > m) return i-j+1;
return -1;
}
int main()
{
int T;
scanf("%d", &T);
while (T--) {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) scanf("%d", a+i);
for (int j = 1; j <= m; ++j) scanf("%d", b+j);
printf("%d\n", kmp(a, b));
}
return 0;
}