题目描述:

参考代码:

#include <bits/stdc++.h>
using namespace std;
const int N=1e6+10;
#define end '\n'
#define IOS ios::sync_with_stdio(0)
int nxt[N],t,n,m,p[N],s[N];
void get_next() {
    int j = 0, k = -1;
    nxt[0] = -1;
    while (j < n) {
        if (k == -1 || p[j] == p[k]) {
            nxt[++j] = ++k;
        } else {
            k = nxt[k];
        }
    }
}
int get_id() {
    get_next();
    int i = 0, j = 0;
    while (i < n && j < m) {
        if (j == -1 || s[i] == p[j]) {
            i++;
            j++;
        } else
            j = nxt[j];
    }
    if (j == m)
        return i - j + 1;
    return -1;
}
int main() {
    IOS;
    cin >> t;
    while (t--) {
        memset(nxt, 0, sizeof(nxt));
        cin >> n >> m;
        for (int i = 0; i < n; i++) {
            cin >> s[i];
        }
        for (int j = 0; j < m; j++) {
            cin >> p[j];
        }
        cout << get_id() << end;
    }
    return 0;
}
/*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 6 -1*/