hdu1711(ac自动机思想)
#include <iostream> #include <cstdio> #include <cstring> #include <string> #include <algorithm> using namespace std; const int maxn = 1000010; const int maxm = 10010; //Accepted 1711 484MS 4260K 1569 B C++ Achiberx int a[maxn], b[maxn]; int n, m; int next[maxm]; void getNext(){ next[0] = 0; next[1] = 0; if(m<3) return; int j = 0; for(int i = 1; i < m; i++) { j = next[i]; if(b[i]==b[j]) { next[i+1] = j+1; continue; } else { while(j>0) { j = next[j]; if(b[i]==b[j]) { next[i+1] = j+1; break; } } } } } int match() { int j = 0; for(int i =0; i < n; i++) { while(j && a[i]!=b[j]) { j = next[j]; } if(a[i]==b[j]) j++; if(j==m) { return i-m+2; } } return 0; } int main() { int T; scanf("%d", &T); for(int v = 0; v < T; v++) { scanf("%d%d", &n, &m); for(int i = 0; i < n; i++) { scanf("%d", &a[i]); } for(int j = 0; j < m; j++) { scanf("%d", &b[j]); } getNext(); int res = match(); if(res) { printf("%d\n", res); } else{ printf("-1\n"); } } return 0; } /*********************** 5 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 ***********************/