您的位置:首页 > 其它

[替罪羊树 模板题] BZOJ 3224 Tyvj 1728 普通平衡树

2017-01-29 22:06 435 查看
替罪羊树的模板题

关于删除 有人说按照BST的方法删 那样讨论太烦啦

直接打个标记表示已被删 下次重构的时候丢掉就好了

#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;

inline char nc(){
static char buf[100000],*p1=buf,*p2=buf;
if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }
return *p1++;
}

inline void read(int &x){
char c=nc(),b=1;
for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}

const int N=200005;

#define ab 0.75
struct node{
node *ch[2];
int key,size,cover,ext;
void update() { size=ch[0]->size+ch[1]->size+ext,cover=ch[0]->cover+ch[1]->cover+1; }
bool bad() { return ch[0]->cover>=cover*ab+5 || ch[1]->cover>=cover*ab+5; }
}Mem
,*null,*root;
node *Stack
; int pnt;
node *lst
; int len;
inline void Init(){
root=null=Mem; null->size=null->cover=0; null->ch[0]=null->ch[1]=null;
for (int i=1;i<N;i++) Stack[++pnt]=Mem+i;
}
inline node *New(int key){
node *t=Stack[pnt--];
t->ch[0]=t->ch[1]=null; t->size=t->cover=t->ext=1; t->key=key;
return t;
}
inline void travel(node *p){
if (p==null) return;
travel(p->ch[0]); if (p->ext) lst[++len]=p; else Stack[++pnt]=p; travel(p->ch[1]);
}
inline node *divide(int l,int r){
if (l>r) return null;
int mid=(l+r)>>1;
lst[mid]->ch[0]=divide(l,mid-1); lst[mid]->ch[1]=divide(mid+1,r); lst[mid]->update();
return lst[mid];
}
inline void rebuild(node *&p){
len=0; travel(p); p=divide(1,len);
}
inline node **insert(node *&p,int key){
if (p==null){ p=New(key); return &null; }
p->size++; p->cover++;
node **ret=insert(p->ch[key>=p->key],key);
if (p->bad()) ret=&p;
return ret;
}
inline void erase(node *p,int k){
p->size--;
if (p->ext && k==p->ch[0]->size+1) return void(p->ext=0);
if (k<=p->ch[0]->size) erase(p->ch[0],k); else erase(p->ch[1],k-p->ch[0]->size-p->ext);
}

inline int Kth(int k){
node *p=root;
while (p!=null){
if (p->ext && k==p->ch[0]->size+1) return p->key;
else if (p->ch[0]->size>=k) p=p->ch[0];
else k-=p->ch[0]->size+p->ext,p=p->ch[1];
}
}
inline int Rank(int val){
node *p=root; int ret=1;
while (p!=null)
if (p->key>=val)
p=p->ch[0];
else
ret+=p->ch[0]->size+p->ext,p=p->ch[1];
return ret;
}
inline void Insert(int val){
node **p=insert(root,val);
if (*p!=null) rebuild(*p);
}
void Erase_kth(int k){
erase(root,k);
if (root->size<ab*root->cover) rebuild(root);
}
void Erase(int k){
Erase_kth(Rank(k));
}

int main(){
int Q,order,x;
freopen("t.in","r",stdin);
freopen("t.out","w",stdout);
Init();
read(Q);
while (Q--){
read(order),read(x);
if (order==1) Insert(x);
else if (order==2) Erase(x);
else if (order==3) printf("%d\n",Rank(x));
else if (order==4) printf("%d\n",Kth(x));
else if (order==5) printf("%d\n",Kth(Rank(x)-1));
else if (order==6) printf("%d\n",Kth(Rank(x+1)));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: