首先是直接用拓展stl的实现,各种操作直接用rope就可以了,因它的底层就是可持久化平衡树
#include
#include
#include
#include
#include
#include
using namespace std;
using namespace __gnu_cxx;
crope his[200000];
int n,c;
char ch[500000];
int main()
{
scanf("%d",&n);
int lans=0;
int tot=0;
for (int i=1;i<=n;i++) {
scanf("%d",&c);
if (1==c) {
++tot;
his[tot]=his[tot-1];
int pos;
scanf("%d%s",&pos,ch+1);
pos+=lans;
int len=strlen(ch+1);
for (int j=len;j>=1;j--)
his[tot].insert(pos,ch[j]);
}
else if (2==c) {
++tot;
his[tot]=his[tot-1];
int pos,cnt;
scanf("%d%d",&pos,&cnt);
pos+=lans,cnt+=lans;
his[tot].erase(pos-1,cnt);
}
else {
int vis,pos,cnt;
scanf("%d%d%d",&vis,&pos,&cnt);
vis+=lans,pos+=lans,cnt+=lans;
crope tmp=his[vis].substr(pos-1,cnt);
for (int i=0;i
然后是fhq treap的 可持久化,由于考虑到merge的时候只影响到新开的节点和split开的节点,这两类节点有个特点就是和历史版本没有纠葛,因此在merge的时候可以不用复制节点,直接回传
速度上比rope快了10倍左右
#include
#include
#include
#include
#include
#include
const int maxn=100000;
const int maxs=5000000;
using namespace std;
int l[maxs],r[maxs],s[maxs];
int his[maxn];
char C[maxs];
char ch[50000];
int n,ss;
string tmp;
inline int ran()
{
static int x=1;
x+=(x<<2)+1;
return x & (2147483647);
}
int ori(char c)
{
++ss;
l[ss]=r[ss]=0,s[ss]=1;
C[ss]=c;
return ss;
}
int news(int x)
{
++ss;
l[ss]=l[x],r[ss]=r[x],s[ss]=s[x];
C[ss]=C[x];
return ss;
}
void updata(int x)
{
s[x]=s[l[x]]+s[r[x]]+1;
}
int build(char ch[],int L,int R)
{
if (L==R) {
int x=ori(ch[L]);
return x;
}
int mid=(L+R)>>1;
int x=ori(ch[mid]);
if (L<=mid-1) l[x]=build(ch,L,mid-1);
if (mid+1<=R) r[x]=build(ch,mid+1,R);
s[x]=s[l[x]]+s[r[x]]+1;
return x;
}
int merge(int x,int y)
{
if (!x) return y;
if (!y) return x;
if (ran()%(s[x]+s[y])=k) {
int p,q;
int tmp=news(x);
split(l[x],k,p,q);
l[tmp]=q,updata(tmp);
a=p,b=tmp;
return ;
}
int p,q;
int tmp=news(x);
split(r[x],k-(s[l[x]]+1),p,q);
r[tmp]=p,updata(tmp);
a=tmp,b=q;
return ;
}
char find(int x,int k)
{
for (;k;) {
if (k==s[l[x]]+1) return C[x];
if (k<=s[l[x]]) x=l[x];
else k-=s[l[x]]+1,x=r[x];
}
}
int main()
{
scanf("%d",&n);
int lans=0;
int tot=0;
ss=0;
his[0]=0;
for (int i=1;i<=n;i++) {
int c;
scanf("%d",&c);
if (1==c) {
++tot;
int pos;
scanf("%d%s",&pos,ch+1);
pos+=lans;
int len=strlen(ch+1);
int tmp=build(ch,1,len);
int a,b;
split(his[tot-1],pos,a,b);
his[tot]=merge(merge(a,tmp),b);
}
else if (2==c) {
++tot;
int pos,cnt;
scanf("%d%d",&pos,&cnt);
pos+=lans,cnt+=lans;
int a,b,c,d;
split(his[tot-1],pos-1,a,b);
// cout<