版权声明:本文为博主原创文章,未经博主允许必须转载。 https://blog.csdn.net/qq_35950004/article/details/81611937
带插入动态LCP模板:
// luogu-judger-enable-o2
#include<cstdio>
#include<cstring>
#include<cctype>
#include<algorithm>
#define maxn 150005
#define S 131
#define ULL unsigned long long
using namespace std;
char s[maxn];
int ch[maxn][2] , fa[maxn] , siz[maxn] , cnt , rt;
ULL val[maxn] , Pow[maxn] , v[maxn];
inline void read(int &res){ char ch;for(;!isdigit(ch=getchar()););for(res=ch-'0';isdigit(ch=getchar());res=res*10+ch-'0'); }
inline void up(int x){ if(x) siz[x] = siz[ch[x][0]] + siz[ch[x][1]] + 1 , val[x] = (val[ch[x][0]] * S + v[x]) * Pow[siz[ch[x][1]]] + val[ch[x][1]]; }
inline void Rotate(int x)
{
if(!fa[x] || !x) return;
int y = fa[x] , z = fa[y] , c = (ch[y][1]==x);
(ch[y][c] = ch[x][!c]) && (fa[ch[y][c]] = y);
fa[fa[ch[x][!c] = y]=x]=z;
if(z) ch[z][ch[z][1]==y]=x;
up(y),up(x);
}
inline void Splay(int x,int dst)
{
for(int y,z;(y=fa[x])!=dst;Rotate(x))
if((z=fa[y])!=dst)
{
if((ch[z][1] == y) == (ch[y][1] == x)) Rotate(y);
else Rotate(x);
}
if(dst==0) rt = x;
up(x);
}
inline int Insert(int &r,int loc,int w,int pfa)
{
int ret = 0;
if(!r) siz[ret=r=++cnt]=1,ch[r][0]=ch[r][1]=0,val[r]=v[r]=w,fa[r]=pfa;
else if(loc >= siz[ch[r][0]]+1) ret=Insert(ch[r][1],loc-siz[ch[r][0]]-1,w,r);
else ret=Insert(ch[r][0],loc,w,r);
return (up(r),ret);
}
inline int Modify(int r,int loc,int w)
{
int ret=0;
if(loc > siz[ch[r][0]]+1) ret=Modify(ch[r][1],loc-siz[ch[r][0]]-1,w);
else if(loc<siz[ch[r][0]]+1) ret=Modify(ch[r][0],loc,w);
else ret=r,v[r]=w;
return (up(r),ret);
}
inline int kth(int r,int loc)
{
if(loc > siz[ch[r][0]]+1) return kth(ch[r][1],loc-siz[ch[r][0]]-1);
else if(loc<siz[ch[r][0]]+1) return kth(ch[r][0],loc);
else return r;
}
inline ULL Query(int x,int y)
{
if(x<y)
{
Splay(kth(rt,x),0) , Splay(kth(rt,y),rt);
return (val[ch[ch[rt][1]][0]] * S + v[ch[rt][1]]) + v[rt]*Pow[y-x];
}
else return v[kth(rt,x)];
}
inline int LCP(int a,int b)
{
int L=0,R=min(siz[rt] - a + 1,siz[rt] - b + 1),Mid;
for(;L<R;)
{
Mid=(L+R+1)>>1;
if(Query(a,Mid+a-1) == Query(b,b +Mid-1)) L=Mid;
else R=Mid-1;
}
return L;
}
int main()
{
Pow[0]=1;
for(int i=1;i<=150000;i++) Pow[i] = Pow[i-1] * S;
scanf("%s",s);
for(int len=strlen(s),i=0;i<len;i++)
Splay(Insert(rt,i,s[i],0),0);
int q,x,d;
for(read(q);q--;)
{
scanf("%s",s),read(x);
if(s[0]=='Q') read(d),printf("%d\n",LCP(x,d));
else if(s[0]=='R') scanf("%s",s),d=s[0],Splay(Modify(rt,x,d),0);
else if(s[0]=='I') scanf("%s",s),d=s[0],Splay(Insert(rt,x,d,0),0);
}
}