[怎么总是忘啊!]treap插入、删除、查找
时间:2010-09-11 来源:Sephiroth Lee
//treap 7.30 #include<stdio.h> #include<stdlib.h> #define mmm 1000000 struct ss { int left,right,key,data,count,size; } t[mmm+1]; int n,x,y,tot,tott,root; int b[mmm+1]; void modify(int x) { t[x].size=t[t[x].left].size+t[x].count+t[t[x].right].size; } void leftrotate(int *x) { int te=t[*x].left; t[*x].left=t[te].right; t[te].right=*x; modify(*x); *x=te; modify(*x); } void rightrotate(int *x) { int te=t[*x].right; t[*x].right=t[te].left; t[te].left=*x; modify(*x); *x=te; modify(*x); } void insert(int *x,int y) { if (*x==0) { *x=++tot; t[*x].left=0; t[*x].right=0; t[*x].size=1; t[*x].count=1; t[*x].key=rand()%mmm; t[*x].data=y; } else { if (y==t[*x].data) ++t[*x].count; else if (y<t[*x].data) { insert(&t[*x].left,y); if (t[t[*x].left].key<t[*x].key) leftrotate(x); } else { insert(&t[*x].right,y); if (t[t[*x].right].key<t[*x].key) rightrotate(x); } modify(*x); } } void delete_(int *x,int y) { if (*x==0) return; if (y<t[*x].data) delete_(&t[*x].left,y); else if (y>t[*x].data) delete_(&t[*x].right,y); else { if (t[*x].count>1) --t[*x].count; else if (t[*x].left==0) *x=t[*x].right; else if (t[*x].right==0) *x=t[*x].left; else if (t[t[*x].left].key<t[t[*x].right].key) { leftrotate(x); delete_(&t[*x].right,y); } else { rightrotate(x); delete_(&t[*x].left,y); } } if (*x!=0) modify(*x); } int findkth(int x,int y) { if (y<=t[t[x].left].size) return findkth(t[x].left,y); else if (y<=t[t[x].left].size+t[x].count) return t[x].data; else return findkth(t[x].right,y-t[t[x].left].size-t[x].count); } int main() { freopen("shop.in","r",stdin); freopen("shop.out","w",stdout); scanf("%d",&n); srand(n); for (int i=1;i<=n;++i) { scanf("%d%d",&x,&y); if (x==1){ insert(&root,y); b[++tott]=y; } else if (x==2) printf("%d\n",b[y]); else printf("%d\n",findkth(root,y)); } //while (1); return 0; }
相关阅读 更多 +