You need to find the first matching position of array B in array A. If not, output-1.
Idea: Direct KMP algorithm (algorithm specific idea this ox write good http://blog.csdn.net/v_july_v/article/details/7041827)
AC code:
# Include <cstdio> # include <cstring> # include <stdlib. h >#include <iostream> using namespace STD; # define maxn 1000005int B [10005]; int A [maxn]; int next [maxn]; int n, m; /* void getnext () {next [0] =-1; int K =-1; Int J = 0; while (j <m) {If (k =-1 | B [J] = B [k]) {++ K; ++ J; next [J] = K ;} else {k = next [k] ;}}*/void getnext () {next [0] =-1; int K =-1; Int J = 0; while (j <m) {If (k =-1 | B [J] = B [k]) {++ J; ++ K; if (B [J]! = B [k]) next [J] = K; else next [J] = next [k];} else {k = next [k] ;}} int kmpsearch () {int I = 0, j = 0; while (I <n & J <m) {If (j =-1 | A [I] = B [J]) {I ++; j ++;} else J = next [J];} if (j = m) return I-j + 1; else return-1;} int main () {int I, j, T; scanf ("% d ", & T); While (t --) {scanf ("% d", & N, & M); for (I = 0; I <n; I ++) scanf ("% d", & A [I]); for (I = 0; I <m; I ++) scanf ("% d ", & B [I]); getnext (); printf ("% d \ n", kmpsearch ();} return 0 ;}