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