// hdu 1711 KMP模板题 // 贴个KMP模板吧~~~ #include <cstdio> #include <cstring> #include <algorithm> #include <iostream> using namespace std; const int MAX_N = 1000008; const int MAX_M = 10008; int T[MAX_N]; int p[MAX_M]; int f[MAX_M]; int n,m; void getfail(){ f[0] = f[1] = 0; for (int i=1;i<m;i++){ int j = f[i]; while(j && p[j]!=p[i]) j = f[j]; f[i+1] = (p[i]==p[j]) ? j+1 : 0; } } int cmp(){ int j = 0; for (int i=0;i<n;i++){ while(j && T[i] != p[j]) j = f[j]; if (T[i] == p[j]) j++; if (j==m){ return i-m+1+1; } } return -1; } int KMP(){ getfail(); return cmp(); } void input(){ scanf("%d%d",&n,&m); for (int i=0;i<n;i++){ scanf("%d",&T[i]); }; for (int i=0;i<m;i++){ scanf("%d",&p[i]); } printf("%d\n",KMP()); } int main(){ int t; // freopen("1.txt","r",stdin); scanf("%d",&t); while(t--){ input(); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-05 09:06:20