KMP入门(匹配)

时间:2021-02-09 01:37:39

Description

Given two sequences of numbers : a[1], a[2], ...... , a[N], and b[1], b[2], ...... , b[M] (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make a[K] = b[1], a[K + 1] = b[2], ...... , a[K + M - 1] = b[M]. If there are more than one K exist, output the smallest one.

Input

The first line of input is a number T which indicate the number of cases. Each case contains three lines. The first line is two numbers N and M (1 <= M <= 10000, 1 <= N <= 1000000). The second line contains N integers which indicate a[1], a[2], ...... , a[N]. The third line contains M integers which indicate b[1], b[2], ...... , b[M]. All integers are in the range of [-1000000, 1000000].

Output

For each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.

Sample Input

2
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 1 3
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 2 1

Sample Output

6
-1 解题思路:题目大意:判断第一个串中是否存在第二个串,存在则输出最小的匹配起始位置,不存在则输出-1。
利用fail数组,KMP.
#include<iostream>
#include<cstdio>
#include<cstring> using namespace std; int N[],M[],fail[];
int n,m;
void KMP(); int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(int i=;i<=n;i++)
scanf("%d",&N[i]);
for(int i=;i<=m;i++)
scanf("%d",&M[i]);
KMP();
}
return ;
} void KMP()
{
memset(fail,,sizeof(fail));
fail[]=-;//初始化fail数组
for(int i=;i<=m;i++)
{
int p=fail[i-];
//如果不满足要求则一直fail直到p=0
while(p>=&&M[p+]!=M[i])
p=fail[p];
fail[i]=p+;
}
int ans=;
for(int i=,p=;i<=n;i++)
{
while(p>=&&M[p+]!=N[i])
p=fail[p];
if(++p==m)
{
ans=i-m+;
p=fail[p];
break;
}
}
if(ans) printf("%d\n",ans);
else printf("-1\n");
}