1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 char W[10005], T[1000005]; 6 int next[10005]; 7 void getfail(char *w, int len){ //失配,求得next[]数组,下标从0到len 8 int i, j; 9 next[0] = -1; i = 0; j = -1; 10 while(i < len){ 11 if(j == -1 || w[i] == w[j]){ 12 i++; j++; next[i] = j; 13 }else 14 j = next[j]; 15 } 16 } 17 18 int KMPMatch(char *w, char *t){ 19 int len1, len2, i,j, ans; 20 i = j = ans = 0; 21 len1 = strlen(w); 22 len2 = strlen(t); 23 getfail(w, len1); 24 while(i < len2){ 25 //cout<<i<<"--"<<j<<endl; 26 if(j == -1 || t[i] == w[j]){ 27 i++; j++; 28 }else 29 j = next[j]; 30 if(j == len1) ans++; 31 } 32 return ans; 33 } 34 35 int main(){ 36 int t; 37 scanf("%d",&t); 38 while(t--){ 39 scanf("%s%s", W, T); 40 printf("%d ", KMPMatch(W, T)); 41 } 42 return 0; 43 }