来源:POJ3461
KMP一水,学了好几天
代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAXN = 10010;
int nxt[MAXN];
char m[MAXN];
char p[MAXN*100];
int lenm,lenp;
void get_next(){
int i=0,j;
memset(nxt,0,sizeof(nxt));
nxt[0]=j=-1;
while(i<lenm){
if(j==-1||m[i]==m[j]){
i++;j++;
if(m[i]!=m[j]){
nxt[i] = j;
}
else
nxt[i] = nxt[j];
}
else
j = nxt[j];
}
}
int ans=0;
void kmp(){
int i,j;
i=j=0;
while(i<lenp){
if(j==-1||m[j] == p[i]){
i++;
j++;
}
else
j=nxt[j];
if(j==lenm){
ans++;
j = nxt[j];
}
}
}
int main(){
int T;
scanf("%d",&T);
getchar();
while(T--){
gets(m);
gets(p);
lenm = strlen(m);
lenp = strlen(p);
//cout<<m<<endl<<p<<endl;
get_next();
ans = 0;
kmp();
cout<<ans<<endl;
}
return 0;
}