【BZOJ3620】—似乎在梦中见过的样子(Kmp)

传送门

由于据说 n 2 n^2 n2可以过

暴力枚举每个为开头,就和动物园这道题一样了

#include
using namespace std;
const int RLEN=1<<20|1;
inline char gc(){
     
    static char ibuf[RLEN],*ib,*ob;
    (ob==ib)&&(ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
    return (ob==ib)?EOF:*ib++;
}
#define gc getchar
inline int read(){
     
    char ch=gc();
    int res=0,f=1;
    while(!isdigit(ch))f^=ch=='-',ch=gc();
    while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=gc();
    return f?res:-res;
}
#define ll long long
#define re register
#define pii pair
#define fi first
#define se second
#define pb push_back
#define cs const
#define bg begin
#define poly vector
#define chemx(a,b) ((a)<(b)?(a)=(b):0)
#define chemn(a,b) ((a)>(b)?(a)=(b):0)
cs int mod=1e9+7;
inline int add(int a,int b){
     return (a+=b)>=mod?a-mod:a;}
inline void Add(int &a,int b){
     (a+=b)>=mod?a-=mod:0;}
inline int dec(int a,int b){
     return (a-=b)<0?a+mod:a;}
inline void Dec(int &a,int b){
     (a-=b)<0?a+=mod:0;}
inline int mul(int a,int b){
     return 1ll*a*b%mod;}
inline void Mul(int &a,int b){
     a=1ll*a*b%mod;}
inline int ksm(int a,int b,int res=1){
     for(;b;b>>=1,Mul(a,a))(b&1)&&(Mul(res,a),1);return res;}
inline int Inv(int x){
     return ksm(x,mod-2);}
cs int N=15005;
int fail[N],k,ans;
inline void calc(char *s){
     
	int len=strlen(s+1);
	for(int i=0,j=2;j<=len;j++){
     
		while(i&&s[i+1]!=s[j])i=fail[i];
		if(s[i+1]==s[j])i++;
		fail[j]=i;
	}
	for(int i=0,j=2;j<=len;j++){
     
		while(i&&s[i+1]!=s[j])i=fail[i];
		if(s[i+1]==s[j])i++;
		while(i*2>=j)i=fail[i];
		if(i>=k)ans++;
	}
}
char s[N];int n;
int main(){
     
	scanf("%s",s+1);
	n=strlen(s+1);
	k=read();
	for(int i=1;i<=n-2*k;i++)calc(s+i-1);
	cout<<ans;
}

你可能感兴趣的:(KMP)