1 #include<stdio.h> 2 #include<string.h> 3 int a[1000005],b[1000005],next[100005]; 4 int main() 5 { 6 int t,i,j,n,m; 7 while (~scanf("%d",&t)) 8 while (t--) 9 { 10 scanf("%d%d",&n,&m); 11 for (i=1;i<=n;i++) scanf("%d",&a[i]); 12 for (i=1;i<=m;i++) scanf("%d",&b[i]); 13 //先求next数组 14 i=1; next[1]=0; j=0; 15 while (i<=m) 16 { 17 if (j==0||b[i]==b[j]) {i++; j++; 18 if (b[i]!=b[j]) next[i]=j; else next[i]=next[j]; } 19 else j=next[j]; 20 } 21 //KMP 22 i=1; j=1; 23 while (i<=n&&j<=m) 24 { 25 if (j==0||a[i]==b[j]) {i++; j++; } 26 else j=next[j]; 27 } 28 //OK 29 if (j>m) printf("%d\n",i-m); 30 else printf("-1\n"); 31 } 32 return(0); 33 }
http://acm.hdu.edu.cn/showproblem.php?pid=1711