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.
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
题意:输入两组数字:s,t找出第一个s中和t匹配的位置,
思路:KMP模板题。。。。。
下面附上代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1000005;
const int M=10005;
int Next[N],s[N],t[M];
int KMP(int *s,int n,int *t,int m)
{
int i=0,j=0;
while(i<n)
{
if(j==-1||s[i]==t[j])
{
++i,++j;
if(j==m)
return i-m+1;
}
else
j=Next[j];
}
return -1;
}
void Getnext(int *t,int l)
{
int i=0,j=-1;
Next[i]=-1;
while(i<l)
{
if(j==-1||t[i]==t[j])
Next[++i]=++j;
else
j=Next[j];
}
}
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",&s[i]);
for(int i=0;i<m;i++)
scanf("%d",&t[i]);
Getnext(t,m);
printf("%d\n",KMP(s,n,t,m));
}
return 0;
}