HDU1686 KMP
题意:一个字符串在另一个字符串中出现的次数
View Code
1 #include<stdio.h> 2 #include<string.h> 3 const int maxn = 10005; 4 const int maxm= 1000005; 5 int lena,lenb; 6 char a[ maxm ],b[ maxn ]; 7 int next[ maxn ]; 8 int ans; 9 void getNext(){ 10 int j,k; 11 j=0,k=-1; 12 next[0]=-1; 13 while( j<lenb ){ 14 if( k==-1||b[j]==b[k] ) 15 j++,k++,next[ j ]=k; 16 else k=next[ k ]; 17 } 18 } 19 int kmp(){ 20 getNext(); 21 int i,j; 22 i=j=0; 23 while( i<lena&&j<lenb ){ 24 if( j==-1||a[i]==b[j] ) 25 i++,j++; 26 else j=next[j]; 27 if( j==lenb ){ 28 ans++; 29 j=next[j]; 30 } 31 } 32 return ans; 33 } 34 int main(){ 35 int t; 36 scanf("%d",&t); 37 while(t--){ 38 scanf("%s",b); 39 scanf("%s",a); 40 lena=strlen(a),lenb=strlen(b); 41 ans=0; 42 printf("%d\n",kmp()); 43 } 44 return 0; 45 }
keep moving...