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
题意概括 :
给出两个数组,判断第二个数组是否包含在第一个数组里,如果是,则输出第二个数组中第一个字符在第一个字符串中出现的位置。
解题思路 :
首先求出第二个数组的next数组,然后与第一个数组进行匹配,当第二个数组的下标等于第二个数组长度时结束循环,或者当第一个数组找到最后一个时结束循环,如果找到了第二个数组,则用当前第一个数组的下标的值减去第二个数组的长度然后加一。找不到输出-1。
#include<stdio.h>
#include<string.h>
int a[1000010],b[10010],next[10010];
int n,m;
void get_next(int b[])
{
int i,j;
i = 1;
j = 0;
next[0] = 0;
while(i < m)
{
if(j == 0&&b[i] != b[j])
{
i ++;
}
if(j > 0&&b[i] != b[j])
{
j = next[j-1];
}
if(b[i] == b[j])
{
next[i] = j+1;
i ++;
j ++;
}
}
}
int KMP(int a[],int b[])
{
int i,j,find;
i = 0;
j = 0;
find = -1;
while(i <= m&&j < n)
{
if(i == 0&&b[i] != a[j])
{
j ++;
}
if(i > 0&&b[i] != a[j])
{
i = next[i-1];
}
if(b[i] == a[j])
{
i ++;
j ++;
}
if(i == m)
{
find = j-m+1;
break;
}
}
return find;
}
int main()
{
int T,k,i,j;
scanf("%d",&T);
while(T --)
{
memset(next,0,sizeof(next));
scanf("%d %d",&n,&m);
for(i = 0;i < n;i ++)
{
scanf("%d",&a[i]);
}
for(j = 0;j < m;j ++)
{
scanf("%d",&b[j]);
}
get_next(b);
k = KMP(a,b);
printf("%d\n",k);
}
return 0;
}