题目描述:
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.
输入:
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].
输出:
For each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.
样例输入:
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
样例输出:
6
-1
思路,很明显,这是一道KMP算法的模板题
关于KMP算法,先简单的举个例子
在匹配字符串时,暴力的通常解法:
而KMP在匹配时,与之不同的是,在匹配失败后,回到已经匹配好的下一个继续匹配
减少时间复杂度
KMP算法是一种改进的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R.Pratt提出的,因此人们称它为克努特—莫里斯—普拉特操作(简称KMP算法)。KMP算法的核心是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。具体实现就是通过一个next()函数实现,函数本身包含了模式串的局部匹配信息。KMP算法的时间复杂度O(m+n)。
详细说明请看一个大牛的博客,总的来说讲的还是很详细的,这个算法也确实很容易迷,多看看,多想想就好了
最后,当然是喜闻乐见的上代码环节
code:
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int maxn=1e6+50;
int n,m;
int a[maxn];
int b[maxn];
int nextt[maxn];
void init()
{
int i=0,j=-1;
nextt[0]=-1;
while(i<m)
{
if(j==-1||b[i]==b[j])
{
i++;
j++;
nextt[i]=j;
}
else
{
j=nextt[j];
}
}
}
void kmp()
{
int i=0,j=0;
int flag=0;
init();
while(i<n)
{
if(j==-1||a[i]==b[j])
{
j++;
i++;
}
else j=nextt[j];
if(j==m)
{
flag=1;
printf("%d\n",i-m+1);
break;
}
}
if(flag==0)printf("-1\n");
}
int main()
{
int ttt;
scanf("%d",&ttt);
while(ttt--)
{
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
for(int j=0;j<m;j++)
scanf("%d",&b[j]);
kmp();
}
return 0;
}