【BZOJ #3942】【Usaco2015 Feb】—Censoring(哈希)

传送门

从前往后直接哈希就完了

#include<bits/stdc++.h>
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<int,int>
#define fi first
#define se second
#define pb push_back
#define cs const
#define bg begin
#define poly vector<int>
#define chemx(a,b) ((a)<(b)?(a)=(b):0)
#define chemn(a,b) ((a)>(b)?(a)=(b):0)
cs int bas1=1331,mod1=1928177133,bas2=233,mod2=758151833;
cs int N=1000005;
int pw1[N],pw2[N],has1[N],has2[N],n,m,tot,val1,val2;
char s[N],t[N],ans[N];
int main(){
	scanf("%s",s+1);
	scanf("%s",t+1);
	n=strlen(s+1),m=strlen(t+1);
	pw1[0]=pw2[0]=1;
	for(int i=1;i<=n;i++)pw1[i]=1ll*pw1[i-1]*bas1%mod1,pw2[i]=1ll*pw2[i-1]*bas2%mod2;
	for(int i=1;i<=m;i++)val1=(1ll*val1*bas1+t[i]-'a')%mod1,val2=(1ll*val2*bas2+t[i]-'a')%mod2;
	for(int i=1;i<=n;i++){
		ans[++tot]=s[i];
		has1[tot]=(1ll*has1[tot-1]*bas1+ans[tot]-'a')%mod1;
		has2[tot]=(1ll*has2[tot-1]*bas2+ans[tot]-'a')%mod2;
		if(tot>=m&&((has1[tot]-1ll*has1[tot-m]*pw1[m])%mod1+mod1)%mod1==val1&&((has2[tot]-1ll*has2[tot-m]*pw2[m])%mod2+mod2)%mod2==val2)
		tot-=m;
	}
	for(int i=1;i<=tot;i++)putchar(ans[i]);
}
原文地址:https://www.cnblogs.com/stargazer-cyk/p/12328456.html