字符串哈希+二分--poj2758Checking the Text

去年寒假讲的题···
传送门
因为插入很少所以可以每次暴力重构
查询就用二分+哈希查询 l c p lcp lcp
好多细节···题目里查询的是原数列的 x , y x,y x,y坑了不少人

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#define maxn 51005
#define LL long long
using namespace std;
int n,m,pos[maxn],pre[maxn],pren;
LL has[maxn],pw[maxn];
char s[maxn];
const int bas=127,mod=1e9+7;

inline void build(int x){
	for(int i=x;i<=n;i++)
		has[i]=(has[i-1]*bas%mod+s[i])%mod;
}

inline bool check(int len,int x,int y){
	LL tmp1=has[x+len-1]-has[x-1]*pw[len]%mod;
	LL tmp2=has[y+len-1]-has[y-1]*pw[len]%mod;
	tmp1=(tmp1%mod+mod)%mod; tmp2=(tmp2%mod+mod)%mod;
	return tmp1==tmp2;
}

inline int query(int x,int y){
	int l=0,r=n-max(x,y)+1,res=0;
	while(r>=l){
		int mid=(l+r)>>1;
		if(check(mid,x,y)) res=mid,l=mid+1;
		else r=mid-1;
	} return res;
}

int main(){
	scanf("%s",s+1); n=strlen(s+1); pren=n;
	for(int i=1;i<=n;i++) pos[i]=i; pw[0]=1;
	for(int i=1;i<=51000;i++) pw[i]=pw[i-1]*bas%mod;
	build(1);
	scanf("%d",&m);
	while(m--){
		char ch[5]; scanf("%s",ch);
		if(ch[0]=='I'){
			scanf("%s",ch); int p; scanf("%d",&p);
			p=min(n+1,p); n++;
			for(int i=pren;pos[i]>=p;i--) pos[i]++;
			for(int i=n;i>=p+1;i--)
				s[i]=s[i-1];
			s[p]=ch[0]; build(p);
		}
		else{
			int x,y; scanf("%d%d",&x,&y);
			int ans=query(pos[x],pos[y]);
			printf("%d\n",ans);
		}
	}
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值