题目描述
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
题解
学习参考:https://www.cnblogs.com/SYCstudio/p/7194315.html绝对够清楚。
对于上一题得到的数组,其实并不是做kmp用到的next数组,应该将数组向后移动一位,首位=-1,这样得到的才是next数组,写的时候不要写next[],会编译错误,该题中我用的ne[],所以在KMP中用到的ne[j]表示j之前的字符串的公共前后缀元素长度,同时ne[j]-1=公共元素尾下标(因为题中的数组是从0开始的)。所以我们在只移动b的时候要利用这个数组,找到i之前的字符串的前缀并移动到后缀所在的位置,此时j的位置对应的应该是前缀尾的后1位也就是ne[j],也就是说在只需要移动b数组的时候,只要令j=ne[j]就可以了。在纸上画画会更清楚。
#include<iostream>
#include<cstring>
using namespace std;
int n,m,a[1000005],b[10005],ne[10005];
void thene()
{
int j=-1;
ne[0]=-1;
for(int i=0;i<m-1;i++)
{
if(j==-1||b[j]==b[i])
{
j++;
ne[i+1]=j;
}
else j=ne[j];
}
}
int kmp()
{
int i=0,j=0;
while(i<n&&j<m)
{
if(j==-1||a[i]==b[j])
{
i++;
j++;
}
else
j=ne[j];
}
if(j==m)
return i-j+1;
else
return -1;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n>>m;
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<m;i++)
cin>>b[i];
thene();
cout<<kmp()<<endl;
}
return 0;
}