题目:http://acm.hdu.edu.cn/showproblem.php?pid=1711
题意:给定两个数组,问能不能再第一个数组中匹配得到第二个数组,如果可以,那么输出最早匹配的起始位置,否则输出-1
思路:kmp直接匹配即可,中间写搓了一个地方,晕-_-||
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 10010;
int arr1[N*100], arr2[N], nt[N];
int n, m;
void getnt()
{
int i = 0, j = -1;
nt[0] = -1;
while(i < m)
{
if(j == -1 || arr2[i] == arr2[j])
{
i++, j++;
if(arr2[i] != arr2[j]) nt[i] = j;
else nt[i] = nt[j];
}
else j = nt[j];
}
}
int kmp()
{
getnt();
int i = 0, j = 0;
while(i < n)
{
if(j == -1 || arr1[i] == arr2[j])
i++, j++;
else j = nt[j];
if(j == m)
return i - m + 1;
}
return -1;
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i++)
scanf("%d", &arr1[i]);
for(int i = 0; i < m; i++)
scanf("%d", &arr2[i]);
if(n < m) printf("-1\n");
else printf("%d\n", kmp());
}
return 0;
}