#include<bits/stdc++.h> using namespace std; typedef long long LL; typedef maxn = 1000005; #define iss ios::sync_with_stdio(false) int ans = 0; char a[maxn],b[maxn]; int Next[maxn]; void getnext(char b[]){ int i,j,len=strlen(b); Next[0]=-1; for(i=0,j=-1;i<len;) if(j==-1||b[i]==b[j]) Next[++i]=++j; else j=Next[j]; } void kmp(char a[],char b[]){ int i,j,n,len; getnext(b); n=strlen(a); len=strlen(b); for(i=j=0;i<n;){ if(j==-1||a[i]==b[j]) i++,j++; else j=Next[j]; if(j >= len) ++ans,j = Next[j]; } } int main(){ iss; int n; cin>>n; while(n--){ ans = 0; cin>>b>>a; kmp(a,b); cout<<ans<<endl; } }
改进getnext
void getnext(char b[]){ int i,j,len=strlen(b); Next[0]=-1; for(i=0,j=-1;i<len;) if(j==-1||b[i]==b[j]){ ++i; ++j; if(b[i] != b[j]) Next[i] = j; else Next[i] = Next[j]; } else j=Next[j]; }