Number Sequence
Time Limit: 10000/5000 MS (Java/others) memory limit: 32768/32768 K (Java/Others)
Total submission (s): 10571 accepted submission (s): 4814
Problem descriptiongiven 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.
Inputthe 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,100 0000].
Outputfor each test case, You shoshould output one line which only contain K described above. If no such K exists, output-1 instead.
Sample Input
213 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 1 313 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 2 1
Sample output
6-1
# Include <iostream>
# Include <cstdio>
Using namespace STD;
Const int maxn1 = 1000010;
Const int maxn2 = 10010;
Int n, m;
Int A [maxn1];
Int B [maxn2];
Int next [maxn2];
Int main ()
{
Int KMP (int * a, int * B, int * Next );
Int T, I;
Cin> T;
While (t --)
{
Cin> N> m;
For (I = 0; I <n; I ++)
{Scanf ("% d", & A [I]);}
For (I = 0; I <m; I ++)
{Scanf ("% d", & B [I]);}
Int ans = KMP (a, B, next );
Cout <ans <Endl;
}
Return 0;
}
// This function is used to find the next array matching the string s string
Void getnext (int * s, int * Next)
{
Next [0] = next [1] = 0;
For (INT I = 1; I <m; I ++) // m is the length of the matching string s
{
Int J = next [I];
While (J & S [I]! = S [J])
J = next [J];
Next [I + 1] = s [I] = s [J]? J + 1:0;
}
}
// This function is used to evaluate the value of the matching position. If the matching fails, the return value is-1.
Int KMP (int * a, int * B, int * Next)
{
Getnext (B, next );/////////
Int J = 0;
For (INT I = 0; I <n; I ++)
{// N is the length of string 1
While (J & A [I]! = B [J])
J = next [J];
If (A [I] = B [J])
J ++;
If (j = m) // m is the length of string 2
Return I-m + 2;
}
Return-1;
}