这是第一道KMP的题目。
就是字符串匹配问题,KMP其实思想很简单,写出来代码也不是很长!
代码如下:
#include <cstdio>
#include <cstring>
const int N = 1000000;
const int M = 10000;
int n, m, T;
int a[N], b[M], next[M];
void getNext()
{
int j, k;
j = 0; k = -1; next[0] = -1;
while ( j < m ) {
if ( k == -1 || b[j] == b[k] ) next[++j] = ++k;
else
k = next[k];
}
}
int KMP()
{
int i = 0, j = 0;
while ( i < n && j < m ) {
if ( j == -1 || a[i] == b[j] )
i++, j++;
else
j = next[j];
}
if ( j == m ) return i - m + 1;
else return -1;
}
int main()
{
scanf("%d", &T);
while ( T-- ) {
scanf("%d%d", &n, &m);
for ( int i = 0; i < n; ++i ) scanf("%d", &a[i]);
for ( int i = 0; i < m; ++i ) scanf("%d", &b[i]);
getNext();
printf("%d\n", KMP( ));
}
}