Number Sequence
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 21891 Accepted Submission(s): 9350
Problem Description
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算法。
下面是AC代码:
#include<cstdio>
#include<string.h>
int s1[10000001],s2[10001];
int next1[10001];
void next_c(int len2)
{
int j;
next1[0]=-1;
for(int i=1;i<len2;i++)
{
j=next1[i-1];
while(s2[j+1]!=s2[i]&&j>=0)
{
j=next1[j];
}
if(s2[j+1]==s2[i])
next1[i]=j+1;
else next1[i]=-1;
}
}
int kmp(int len1,int len2)
{
int i=0,j=0;
while(i<len1&&j<len2)
{
if(s1[i]==s2[j])
{
i++;
j++;
}
else if(j==0) i++;
else j=next1[j-1]+1;
}
return j==len2?i-len2+1:-1;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int a,b;
scanf("%d%d",&a,&b);
for(int i=0;i<a;i++)
scanf("%d",&s1[i]);
for(int i=0;i<b;i++)
scanf("%d",&s2[i]);
next_c(b);
printf("%d\n",kmp(a,b));
}
return 0;
}