http://acm.hdu.edu.cn/showproblem.php?pid=1711
这道题就是一个KMP模板。
#include<iostream>
#include<cstring>
using namespace std; const int maxn = +; int n,m; int next[maxn];
int a[maxn], b[maxn]; void get_next()
{
int i = -, j = ;
::next[] = -;
while (j < m)
{
if (i == - || b[i] == b[j])
::next[++j] = ++i;
else
i = ::next[i];
}
} int kmp()
{
int i = , j = ;
while (i < n)
{
if (j == - || a[i] == b[j])
{
i++;
j++;
}
else
j = ::next[j];
if (j == m)
return i;
}
return -;
} int main()
{
//freopen("D:\\txt.txt", "r", stdin);
int t;
cin >> t;
while (t--)
{
cin >> n >> m;
for (int i = ; i < n; i++)
cin >> a[i];
for (int i = ; i < m; i++)
cin >> b[i];
get_next();
int k=kmp();
if (k!=-) cout << k-m+ << endl;
else cout << "-1" << endl;
}
return ;
}