AC code:
# Include <iostream> # include <cstdio> # include <cstdlib> # include <cmath> # include <cstring> # include <string> # include <vector> # include <list> # include <deque> # include <queue> # include <iterator> # include <stack> # include <map> # include <set> # include <algorithm> # include <cctype> using namespace std; typedef long LL; const int N = 10005; const ll ii = 100000000; const int INF = 0x3f3f3f; const double PI = acos (-1.0); int next [N], tlen, wlen; int text [1000009], word [N]; void getnext (int * p) {int j = 0, k =-1; next [0] =-1; while (j <wlen) // len is the length of p {if (k =-1 | p [j] = p [k]) {j ++; k ++; next [j] = k;} else k = next [k];} int kmp (int * text, int * word) // Main string and mode string {// return the first occurrence of the mode string int I = 0, j = 0, k = 0; while (I <tlen) {if (j =-1 | text [I] = word [j]) {I ++; j ++;} else j = next [j]; if (j = wlen) return I-wlen + 1;} return-1;} int main () {int I, j, T; cin> T; while (T --) {scanf ("% d", & tlen, & wlen); for (I = 0; I <tlen; I ++) scanf ("% d", & text [I]); for (I = 0; I <wlen; I ++) scanf ("% d ", & word [I]); getnext (word); int xx = kmp (text, word); printf ("% d \ n", xx);} return 0 ;}