Time:2016.07.19
Author:xiaoyimi
转载注明出处谢谢
传送门1
传送门2
思路&&注意:
LCP这个东西可以用后缀数组,扩展kmp什么的来做
这里加上了插入与修改操作
考虑使用hash直接判断,用Splay实时维护节点的子树hash值
询问LCP时,我们可以二分答案,通过Splay的旋转操作在
log2L
的时间内判断出任意两段区间中子串是否相等
个人感觉总复杂度在
O(Mlog2L)
到
O(Mlog22L)
(取决于查询操作的个数)
(可能有错,求大神赐教)
不过我的Splay常数真的很大
一开始用的hash姿势不太好,用的是26进制转化+双hash+取模大质数,结果中间结果必须使用long long不然会WA,但用了longlong又会在BZOJ上T(明明cogs和tyvj上都过了呀(๑ŐдŐ)b)
~~近乎精神AC
最后改成ull自然溢出+47进制才过的……
教训——进制转换时多用质数进制,注意常数的控制
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define M 100005
#define LL unsigned long long
using namespace std;
int m,root,tot;
int fa[M],son[M][2],siz[M],key[M];
LL p[M],hash[M];
char s[M];
int in()
{
char ch=getchar();int t=0;bool f=0;
while (ch>'9'||ch<'0')
{
if (ch=='-') f=1;
ch=getchar();
}
while (ch>='0'&&ch<='9') t=(t<<3)+(t<<1)+ch-48,ch=getchar();
return f?-t:t;
}
void ct(int x)
{
siz[x]=siz[son[x][0]]+siz[son[x][1]]+1;
hash[x]=(hash[son[x][1]]+
p[siz[son[x][1]]]*key[x]+
hash[son[x][0]]*p[siz[son[x][1]]+1]);
}
void rorate(int x,bool f)
{
int y=fa[x];
son[y][!f]=son[x][f];
fa[son[x][f]]=y;
fa[x]=fa[y];
if (fa[y])
if (son[fa[y]][0]==y) son[fa[y]][0]=x;
else son[fa[y]][1]=x;
son[x][f]=y;
fa[y]=x;
ct(y);
ct(x);
}
void splay(int x,int goal)
{
int y;
while (fa[x]!=goal)
{
y=fa[x];
if (fa[y]==goal)
if (son[y][0]==x) rorate(x,1);
else rorate(x,0);
else if (son[fa[y]][0]==y)
{
if (son[y][0]==x) rorate(y,1);
else rorate(x,0);
rorate(x,1);
}
else
{
if (son[y][1]==x) rorate(y,0);
else rorate(x,1);
rorate(x,0);
}
}
if (!goal) root=x;
}
int build(int L,int R)
{
if (L>R) return 0;
int now=++tot,mid=L+R>>1;
key[now]=max(0,s[mid]-'a');
int ls=build(L,mid-1),
rs=build(mid+1,R);
if (ls) fa[ls]=now,son[now][0]=ls;
if (rs) fa[rs]=now,son[now][1]=rs;
ct(now);
return now;
}
int Kth(int k)
{
int x=root;
for (;;)
{
if (siz[son[x][0]]+1==k) return x;
if (siz[son[x][0]]+1>k) x=son[x][0];
else k-=siz[son[x][0]]+1,x=son[x][1];
}
}
bool check(int x,int y,int len)
{
LL p;
splay(Kth(x-1),0);
splay(Kth(x+len),root);
p=hash[son[son[root][1]][0]];
splay(Kth(y-1),0);
splay(Kth(y+len),root);
return p==hash[son[son[root][1]][0]];
}
main()
{
p[0]=1;
for (int i=1;i<=M-5;i++)
p[i]=(LL)p[i-1]*47;
scanf("%s",s+2);
int len=strlen(s+2);
root=build(1,len+2);
m=in();
char ch;int x,y;
while (m--)
{
ch=getchar();
while (ch!='Q'&ch!='I'&&ch!='R') ch=getchar();
if (ch=='Q')
{
x=in()+1;y=in()+1;
if (x>y) swap(x,y);
int L=0,R=tot-y,ans=0;
for (int mid=L+R>>1;L<=R;mid=L+R>>1)
if (check(x,y,mid)) L=mid+1,ans=mid;
else R=mid-1;
printf("%d\n",ans);
}
else if (ch=='I')
{
x=in()+1;
ch=getchar();
while (ch>'z'||ch<'a') ch=getchar();
splay(Kth(x),0);
splay(Kth(x+1),root);
key[++tot]=ch-'a';
siz[tot]=1;
fa[tot]=son[root][1];
son[son[root][1]][0]=tot;
ct(son[root][1]);ct(root);
splay(tot,0);
}
else
{
x=in()+1;
ch=getchar();
while (ch>'z'||ch<'a') ch=getchar();
splay(Kth(x),0);
key[root]=ch-'a';
ct(root);
}
}
}