https://uva.onlinejudge.org/index.php
可持久化fhp-treap。像线段树的可持久化一样自上至下,每次新建log(n)个节点即可。
#include<bits/stdc++.h> const int maxn=50015,maxlen=115; using namespace std; int n,cnt; struct Ttreap{ int tot,ver; static const int maxnode=10000015; struct Tnode{ Tnode *c[2]; int key,siz;char ch; void update(){siz=c[0]->siz+c[1]->siz+1;} }T[maxnode],*null,*root[maxn]; int seed(){return 1ll*rand()*rand()%19990211;} void clear(){ tot=ver=0;null=T; null->c[0]=null->c[1]=null;null->siz=0; for (int i=0;i<=n;++i) root[i]=null; } Tnode *newnode(Tnode *x){ if (x==null) return null; Tnode *cur=T+(++tot); *cur=*x;return cur; } Tnode *newnode(char ch){ Tnode *cur=T+(++tot); cur->c[0]=cur->c[1]=null; cur->ch=ch;cur->siz=1;cur->key=seed(); return cur; } Tnode *merge(Tnode *x,Tnode *y){ Tnode *t; if (x==null) return newnode(y); if (y==null) return newnode(x); if (x->key<y->key){t=newnode(x);t->c[1]=merge(x->c[1],y);} else{t=newnode(y);t->c[0]=merge(x,y->c[0]);} t->update();return t; } void split(Tnode *x,Tnode *&a,Tnode *&b,int rank){ if (!rank){a=null;b=newnode(x);} else if (x->siz<=rank){a=newnode(x);b=null;} else if (rank<=x->c[0]->siz){b=newnode(x);split(x->c[0],a,b->c[0],rank);b->update();} else{a=newnode(x);split(x->c[1],a->c[1],b,rank-x->c[0]->siz-1);a->update();} } Tnode *build(char s[]){ static Tnode *stk[maxlen];int top=0; for (int i=1;s[i];++i){ Tnode *cur=newnode(s[i]),*last=null; while (top&&cur->key<stk[top]->key){stk[top]->update();last=stk[top--];} cur->c[0]=last;cur->update(); if (top){stk[top]->c[1]=cur;stk[top]->update();} stk[++top]=cur; } while (top) stk[top--]->update(); return stk[1]; } void insert(int pos,char s[]){ Tnode *a,*b; root[++ver]=build(s); split(root[ver-1],a,b,pos); root[ver]=merge(a,root[ver]); root[ver]=merge(root[ver],b); } void remove(int pos,int l){ ++ver; Tnode *a,*b,*c,*d; split(root[ver-1],a,b,pos-1);split(b,c,d,l); root[ver]=merge(a,d); } void print(Tnode *x){ if (x->c[0]!=null) print(x->c[0]); putchar(x->ch);cnt+=(x->ch==‘c‘); if (x->c[1]!=null) print(x->c[1]); } void query(int v,int pos,int l){ Tnode *a,*b,*c,*d; split(root[v],a,b,pos-1); split(b,c,d,l);print(c);putchar(‘\n‘); } }treap; void insert(){ int p;char q[maxlen]; scanf("%d%s",&p,q+1); q[strlen(q+1)+1]=0; p-=cnt;treap.insert(p,q); } void remove(){ int p,c;scanf("%d%d",&p,&c); p-=cnt;c-=cnt;treap.remove(p,c); } void query(){ int v,p,c;scanf("%d%d%d",&v,&p,&c); v-=cnt;p-=cnt;c-=cnt;treap.query(v,p,c); } int main(){ srand((unsigned)time(NULL)); scanf("%d",&n);treap.clear(); for (int t,i=1;i<=n;++i){ scanf("%d",&t); switch (t){ case 1:insert();break; case 2:remove();break; case 3:query();break; } } return 0; }
my code
时间: 2024-10-06 00:43:46