标签:
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 22568 Accepted Submission(s): 9639
#include<iostream> #include<cstdio> #include<cstring> #include<stdlib.h> #include<algorithm> #include<cmath> using namespace std; int n,m; int N[1000005],M[10005],Pi[10005]; void preFix() { memset(Pi,0,sizeof(Pi)); int k=0; for(int q=2;q<=m;q++) { while(k>0&&M[k+1]!=M[q]) k=Pi[k]; if(M[k+1]==M[q]) k++; Pi[q]=k; } } int KMP() { preFix(); int q=0; for(int i=1;i<=n;i++) { while(q>0&&M[q+1]!=N[i]) q=Pi[q]; if(M[q+1]==N[i]) q++; if(q==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",&N[i]); for(int j=1;j<=m;j++) scanf("%d",&M[j]); int ans=KMP(); printf("%d\n",ans); } return 0; }
标签:
原文地址:http://www.cnblogs.com/jasonlixuetao/p/5905636.html