直接贴代码吧
1 #include<cstdio> 2 #include<cstring> 3 char P[10004],T[1000006]; 4 int f[10004]; 5 int n,m; 6 void getfail() 7 { 8 f[0] = 0; 9 f[1] =0; 10 for(int i=1; i<m; ++i) 11 { 12 int j=f[i]; 13 while(j && P[i] != P[j]) j = f[j]; 14 f[i+1] = P[i]==P[j] ? j+1:0; 15 } 16 } 17 int KMP() 18 { 19 int cnt=0; 20 getfail(); 21 int j=0; 22 for(int i=0; i<n; ++i) 23 { 24 while(j && P[j] != T[i]) j=f[j]; 25 if(P[j] == T[i]) ++j; 26 if(j == m) 27 { 28 j=f[m]; 29 ++cnt; 30 } 31 } 32 return cnt; 33 } 34 int main() 35 { 36 freopen("in.txt","r",stdin); 37 int t; 38 scanf("%d",&t); 39 while(t--) 40 { 41 scanf("%s%s",P,T); 42 n=strlen(T); 43 m = strlen(P); 44 getfail(); 45 for(int i=0; i<=m; ++i) 46 printf("%d ",f[i]); 47 } 48 return 0; 49 }