HDU1711-Number Sequence
字符串匹配模板题。KMP的话,我觉得算导上的讲解与证明很清晰,代码也很工整简洁,很好理解。
#include<iostream> #include<cstring> #include<cstdio> using namespace std; const int N = 1e6+5; const int M = 1e4+5; int txt[N],pat[M],pf[M]; int n,m; void CPF() { pf[1] = 0; int k = 0; for (int i=2;i<=m;i++) { while (k && pat[k+1]!=pat[i]) k = pf[k]; if (pat[k+1] == pat[i]) k++; pf[i] = k; } } int KMP() { CPF(); int k = 0; for (int i=1;i<=n;i++) { while (k && pat[k+1]!=txt[i]) k = pf[k]; if (pat[k+1] == txt[i]) k++; if (k==m) return i-m+1; } return -1; } int main() { int T; scanf("%d",&T); while (T--) { scanf("%d %d",&n,&m); for (int i=1;i<=n;i++) scanf("%d",&txt[i]); for (int i=1;i<=m;i++) scanf("%d",&pat[i]); printf("%d\n",KMP()); } return 0; }