1 // hdu 1686 KMP模板 2 3 // 没啥好说的,KMP裸题,这里是MP模板 4 5 #include <cstdio> 6 #include <iostream> 7 #include <cstring> 8 #include <algorithm> 9 10 using namespace std; 11 12 const int MAX_N = 1000008; 13 const int MAX_M = 10008; 14 char T[MAX_N]; 15 char p[MAX_M]; 16 int f[MAX_M]; 17 int n,m; 18 19 void getfail(){ 20 f[0] = f[1] = 0; 21 for (int i=1;i<m;i++){ 22 int j = f[i]; 23 while(j && p[i]!=p[j]) 24 j = f[j]; 25 f[i+1] = (p[i]==p[j]) ? j + 1 : 0; 26 } 27 } 28 29 int cmp(){ 30 int cnt = 0; 31 int j = 0; 32 for (int i=0;i<n;i++){ 33 while(j && T[i] != p[j]) 34 j = f[j]; 35 if (T[i] == p[j]) 36 j++; 37 if (j==m){ 38 cnt++; 39 } 40 } 41 return cnt; 42 } 43 44 int KMP(){ 45 getfail(); 46 return cmp(); 47 } 48 49 void input(){ 50 scanf("%s%s",p,T); 51 n = strlen(T); 52 m = strlen(p); 53 printf("%d\n",KMP()); 54 } 55 56 int main(){ 57 int t; 58 //freopen("1.txt","r",stdin); 59 scanf("%d",&t); 60 while(t--){ 61 input(); 62 } 63 }
时间: 2024-10-14 06:53:43