KMP算法模板
1 #include <cstdio> 2 #include <cstring> 3 using namespace std; 4 #define N 10010 5 #define M 1000010 6 7 char S[M], T[N]; 8 int next[N]; 9 10 void Get_next() 11 { 12 int i=0, j=-1; 13 next[0] = -1; 14 int lt = strlen(T); 15 while(i<lt) 16 { 17 if(j==-1 || T[i]==T[j]) 18 next[++i] = ++j; 19 else j = next[j]; 20 } 21 } 22 23 int KMP() 24 { 25 int i=0, j=0, cnt=0; 26 int ls = strlen(S), lt=strlen(T); 27 Get_next(); 28 while(i<ls && j<lt) 29 { 30 if(S[i]==T[j] || j==-1) 31 i++, j++; 32 else 33 j = next[j]; 34 if(j==lt) //得到一个子串 35 { 36 cnt++; 37 j = next[j]; 38 } 39 } 40 return cnt; 41 } 42 43 int main() 44 { 45 int n; 46 while(~scanf("%d", &n)) 47 { 48 for(int i=0; i<n; i++) 49 { 50 scanf("%s%s", T, S); 51 printf("%d\n", KMP()); 52 } 53 } 54 return 0; 55 }