HDU 1711 Number Sequence
在nnext数组保存前面的字符的前缀与后缀的最大匹配,即nnext[i]保存的是当i匹配不成功时应带回朔到的位置
#include <iostream> #include <cstdio> #include <cstring> using namespace std; #define maxn 1000050 int s1[maxn]; int s2[maxn]; int nnext[maxn]; void Getnext(int n2) { int i=1; int j=0; nnext[i]=j; while(i<=n2) { if(j==0||s2[i]==s2[j]) nnext[++i]=++j; else j=nnext[j]; } } int Kmp(int n1,int n2) { Getnext(n2); int i=1,j=1; while(i<=n1) { if(j==0||s1[i]==s2[j]) { i++; j++; } else j=nnext[j]; if(j==n2+1) return i-n2; } return -1; } int main() { int t,n1,n2; scanf("%d",&t); while(t--) { scanf("%d%d",&n1,&n2); for(int i=1;i<=n1;i++) scanf("%d",&s1[i]); for(int i=1;i<=n2;i++) scanf("%d",&s2[i]); int ans=Kmp(n1,n2); printf("%d\n",ans); } return 0; }