**
原文:
**
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
题意描述:
在第1个子串中找第二个子串找到就输出所在位置的下标,没找到输出-1
解题思路:
将第二个子串的相同前缀和后缀信息存入next数组,然后与第一个子串进行匹配,直到匹配到最后一个数就行;
AC代码:
#include<stdio.h>
int next[100050];
int s[1000050],p[100050];
int n,m;
void Get_next()
{
int i=1,j=0;
next[0]=-1;
while(i<m)
{
if(j==-1||p[i]==p[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
void kmp()
{
int i=0,j=0;
while(i<n&&j<m)
{
if(j==-1||s[i]==p[j])
{
i++;
j++;
}
else
j=next[j];
}
if(j==m)//遍历到第二个数组的最后一个数
//(该数组是从1开始所以在输出的时候需要加1)
return i-j+1;
else
return -1;
}
int main()
{
int t,i,k;
scanf("%d", &t);
while(t--)
{
scanf("%d %d", &n,&m);
//分别输入两个数组
for(i=0; i<n; i++)
scanf("%d", &s[i]);
for(i=0; i<m; i++)
scanf("%d", &p[i]);
//依次调用两个函数寻找子串在母串中的位置
Get_next();
k=kmp();
printf("%d\n", k);
}
return 0;
}
翻译:
给定两个数字序列:A[1],A[2],……,A[N]和B[1],B[2],……,b[m](1<=m<=10000,1<=n<=1000000)。您的任务是找到一个数字k,使a[k]=b[1],a[k+1]=b[2],……,a[k+m-1]=b[m]。如果存在多个k,则输出最小的k。
输入
输入的第一行是一个数字t,它指示案例的数量。每箱包含三行。第一行是两个数字n和m(1<=m<=10000,1<=n<=1000000)。第二行包含n个整数,表示[1]、[2]、……,A[N]。第三行包含m个整数,表示b[1]、b[2]、……,B[米]。所有整数都在范围内[-1000000,1000000]。
产量
对于每个测试用例,您应该输出一行,其中只包含上面描述的k。如果不存在这样的k,则输出-1。
样本输入
2
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2 2 2
1 2 3 1 3
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2 2 2
1 2 3 2 1
样品输出
6
- 1