Problem 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
这题就是kmp模板题,下面附上代码。
#include<iostream>
typedef long long ll;
using namespace std;
int a[10000],b[1000000];
int Next[10000];//next[x]表示长度为x+1的数列的最大公共前后缀的长度减一(可能有点拗口,但是这样定义是为了kmp方便起见)
void getnext(int *a,int lena)//获取next数组的值
{ Next[0]=-1;//一个数的时候一定不存在
int k=-1;
for(int i=1;i<=lena-1;i++)
{ while(k>-1&&a[k+1]!=a[i])//k>-1说明当前子数列还存在最长公共前后缀 ,且不匹配。
{k=Next[k];//回溯操作
}
if(a[k+1]==a[i]) k++;//匹配的话就加一,这其实是一个递推加上递归的操作,具体的话可以画草图体会一下。
Next[i]=k;
}
}
int kmp(int *a,int lena,int *b,int lenb)
{ getnext(a,lena);//调用函数获取next数组
int k=-1;
for(int i=0;i<lenb;i++)
{ while(k>-1&&a[k+1]!=b[i])//这里的操作和next一样。
{k=Next[k];//回溯操作
}
if(a[k+1]==b[i]) k++;
if(k==lena-1)//说明已经完全匹配了
{ return i-lena+1;
//i=i-lena+1;
//k=-1;
}
}
return -1;//不存在
}
int main()
{ int t,n,m;
scanf("%d",&t);
while(t--)
{ scanf("%d%d",&n,&m);
for(int i=0;i<n;i++) scanf("%d",&b[i]);
for(int i=0;i<m;i++) scanf("%d",&a[i]);
int ans=kmp(a,m,b,n);
printf("%d\n",ans==-1?ans:ans+1);
}
}
kmp 算法可以说是完美解决了字符串匹配问题,将效率提升到了极限。