【JSOI 2008】火星人

传送门


Problem

给定一个字符串,有 Q Q Q 个操作,每个操作有 3 3 3 种类型:

  1. 询问两个后缀的最长公共前缀。
  2. 修改字符串的一个位置。
  3. 在两个字符中间插入一个新字符。

Q ≤ 150000 Q\le150000 Q150000
字符串长度始终不超过 1 0 5 10^5 105


Solution

这道题其实不难,但是可能调起来比较痛苦。。。

l c p lcp lcp 可以通过二分+ h a s h hash hash来做,主要问题是两个修改。

考虑到 h a s h hash hash 值可以快速合并,就想到可以用线段树、平衡树等数据结构来维护。但又由于有插入操作,就只有用平衡树了。代码中用的是 S p l a y Splay Splay,也可以用其他的平衡树。


Code

#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 200005
#define ull unsigned long long
using namespace std;
int n,m;
ull Pow[N];
char S[N],op[5],c;
namespace SPLAY{
	ull Hash[N];
	int root,tot,fa[N],val[N],Size[N],son[N][2];
	int Get(int x)  {return x==son[fa[x]][1];}
	void pushup(int x){
		int lc=son[x][0],rc=son[x][1];
		Hash[x]=Hash[lc]*Pow[Size[rc]+1]+val[x]*Pow[Size[rc]]+Hash[rc];
		Size[x]=Size[lc]+Size[rc]+1;
	}
	int build(int l,int r,int father){
		if(l>r)  return 0;
		int mid=(l+r)>>1,x=mid;
		fa[x]=father,Size[x]=1,val[x]=Hash[x]=S[x]-'a'+1;
		son[x][0]=build(l,mid-1,mid);
		son[x][1]=build(mid+1,r,mid);
		pushup(x);return x;
	}
	void Rotate(int x){
		int y=fa[x],z=fa[y];
		int k=Get(x),l=son[x][k^1];
		son[y][k]=l,fa[l]=y;
		son[z][Get(y)]=x,fa[x]=z;
		son[x][k^1]=y,fa[y]=x;
		pushup(y),pushup(x);
	}
	void Splay(int x,int goal=0){
		while(fa[x]!=goal){
			int y=fa[x],z=fa[y];
			if(z!=goal)  Rotate(Get(x)==Get(y)?y:x);
			Rotate(x);
		}
		if(!goal)  root=x;
	}
	int find(int root,int k){
		if(!root)  return 0;
		if(Size[son[root][0]]+1==k)  return root;
		if(Size[son[root][0]]>=k)  return find(son[root][0],k);
		return find(son[root][1],k-Size[son[root][0]]-1);
	}
	void modify(int x,char c){
		x=find(root,x),Splay(x);
		val[x]=c-'a'+1,pushup(x);
	}
	void Insert(int x,char c){
		int pre=find(root,x);
		int suf=find(root,x+1);
		Splay(pre),Splay(suf,pre);
		son[suf][0]=++tot,Size[tot]=1,fa[tot]=suf,val[tot]=Hash[tot]=c-'a'+1;
		pushup(suf),pushup(pre);
	}
	ull check(int x,int y){
		x=find(root,x),Splay(x);
		y=find(root,y+2),Splay(y,x);
		return Hash[son[y][0]];
	}
}
using namespace SPLAY;
int Query(int x,int y){
	int l=0,r=min(n-x,n-y)+1;
	while(l<r){
		int mid=(l+r+1)>>1;
		if(check(x,x+mid-1)==check(y,y+mid-1))  l=mid;
		else  r=mid-1;
	}
	return l;
}
int main(){
	int x,y,i;
	Pow[0]=1;
	for(i=1;i<N;++i)  Pow[i]=Pow[i-1]*131;
	scanf("%s%d",S+2,&m);
	n=strlen(S+2),root=build(1,n+2,0),tot=n+2;
	for(i=1;i<=m;++i){
		scanf("%s%d",op,&x);
		if(op[0]=='R')  scanf(" %c",&c),modify(x+1,c);
		else  if(op[0]=='I')  scanf(" %c",&c),Insert(x+1,c),++n;
		else  scanf("%d",&y),printf("%d\n",Query(x,y));
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值