1 #include<cstdio> 2 #include<cstring> 3 #include<iostream> 4 #include<algorithm> 5 using namespace std; 6 #define MAXN 20222200 7 int next[MAXN]; 8 char s[MAXN],p[MAXN]; 9 int read(){ 10 register int f=1,x=0; 11 register char ch=getchar(); 12 while(ch>‘9‘||ch<‘0‘){if(ch==‘-‘) f=-1;ch=getchar();} 13 while(ch>=‘0‘&&ch<=‘9‘)x=x*10+ch-‘0‘,ch=getchar(); 14 return x*f; 15 } 16 void get_next(){ 17 int i=0,j=-1; 18 next[0]=-1; 19 int len=strlen(p); 20 while(i<len){ 21 if(j==-1||p[i]==p[j]){ 22 i++;j++; 23 next[i]=j; 24 } 25 else j=next[j]; 26 } 27 } 28 int kmp(){ 29 get_next(); 30 int i=0,j=0,ans=0; 31 int len=strlen(s); 32 int m=strlen(p); 33 while(i<len&&j<m){ 34 if(j==-1||s[i]==p[j]){ 35 i++;j++; 36 } 37 else j=next[j]; 38 if(j==m) ans++,j=next[j]; 39 } 40 return ans; 41 } 42 int main() 43 {//kmp求子串出现次数 44 int n=read(); 45 while(n--){ 46 scanf("%s%s",p,s); 47 printf("%d\n",kmp()); 48 } 49 return 0; 50 }
原文:http://www.cnblogs.com/shenben/p/5459921.html