1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 5 int n,m; 6 int a[1000010],b[10010],next[10010]; 7 8 void getnext (int *s,int *next){ 9 next[0]=next[1]=0; 10 for (int i=1;i<m;i++){ 11 int j=next[i]; 12 while (j&&s[i]!=s[j]) 13 j=next[j]; 14 if(b[i]==b[j]) next[i+1]=j+1; 15 else next[i+1]=0; 16 } 17 } 18 19 int kmp (int *a,int *b,int *next){ 20 getnext (b,next); 21 int j=0; 22 for (int i=0;i<n;i++){ 23 while (j&&a[i]!=b[j]) 24 j=next[j]; 25 if (a[i]==b[j]) 26 j++; 27 if (j==m) 28 return i-m+2; 29 } 30 return -1; 31 } 32 33 int main (){ 34 int t; 35 scanf ("%d",&t); 36 while (t--){ 37 scanf ("%d %d",&n,&m); 38 for (int i=0;i<n;i++) 39 scanf ("%d",&a[i]); 40 for (int i=0;i<m;i++) 41 scanf ("%d",&b[i]); 42 int ans=kmp (a,b,next); 43 printf ("%d\n",ans); 44 } 45 return 0; 46 }
HDU1711 最基础的kmp算法,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/CSU3901130321/p/3862213.html