Number Sequence
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<string>
#include<vector>
#include<iostream>
#include<string>
using namespace std;
#define vec vector<int>
int n,m,N;
int v[6000000];
vec nex(int ne[])
{
vec net(N);
int j;
for(int i=1;i<N;i++)
{
j=net[i-1];
while(ne[i]!=ne[j]&&j>0)
{
j=net[j-1];
}
if(ne[i]==ne[j]) j++;
net[i]=j;
}
return net;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
N=n+m+1;
for(int i=m+1;i<N;i++) scanf("%d",&v[i]);
for(int i=0;i<m;i++) scanf("%d",&v[i]);
v[m]=1000009;
int flag=-1;
vec V=nex(v);
for(int i=m+1;i<N;i++)
{
if(V[i]==m)
{
flag=i-m-m+1;
break;
}
}
printf("%d\n",flag);
}
return 0;
}