板块漂移
P3369 平衡树 用treap写的 下载数据通过 但是评测WA
代码如下
#include<bits/stdc++.h>
#include<ctime>
#include<cstdlib>
#include<utility>
using namespace std;
int id=0,root=0;
int n;
struct node{
int cnt,size,dat,ls,rs;
int rd;
}tree[200005];
void pushup(int x){
tree[x].size=tree[tree[x].ls].size+tree[x].cnt+tree[tree[x].rs].size;
}
int newnode(int n){
tree[++id].size=tree[id].cnt=1;
tree[id].ls=tree[id].rs=0;
tree[id].dat=n;
tree[id].rd=rand();
return id;
}
void rt(int &p){//zig
int t=tree[p].ls;
tree[p].ls=tree[t].rs,tree[t].rs=p;p=t;
pushup(tree[p].rs);pushup(p);
}
void lt(int &p){//zag
int t=tree[p].rs;
tree[p].rs=tree[t].ls,tree[t].ls=p;p=t;
pushup(tree[p].ls);pushup(p);
}
void insert(int &p,int x){//插入
if(!p){
p=newnode(x);
}
else{
if(x==tree[p].dat){
tree[p].cnt++;
}
else if(tree[p].dat>x){
insert(tree[p].ls,x);
if(tree[tree[p].ls].rd>tree[p].rd){
rt(p);
}
}
else{
insert(tree[p].rs,x);
if(tree[tree[p].rs].rd>tree[p].rd){
lt(p);
}
}
}
pushup(p);
}
void del(int &p,int x){//删除
if(!p)return;
if(x==tree[p].dat){
if(tree[p].cnt>1){
tree[p].cnt--;
pushup(p);
}
else{
tree[p].cnt=0;
if(tree[p].ls||tree[p].rs){
if(!tree[p].rs||tree[tree[p].ls].rd>tree[tree[p].rs].rd){
rt(p);
del(tree[p].rs,x);
}
else{
lt(p);
del(tree[p].ls,x);
}
}
else{
p=0;
}
}
}
else if(tree[p].dat>x){
del(tree[p].ls,x);
}
else{
del(tree[p].rs,x);
}
pushup(p);
}
int ask1(int p,int x){//找排名
if(!p)return 1;
if(tree[p].dat==x){
return tree[tree[p].ls].size+1;
}
else if(tree[p].dat>x){
return ask1(tree[p].ls,x);
}
else{
return tree[tree[p].ls].size+tree[p].cnt+ask1(tree[p].rs,x);
}
}
int ask2(int p,int x){//找排名对应的数
if(!p)return 1e9;
if(tree[tree[p].ls].size>=x){
return ask2(tree[p].ls,x);
}
else if(tree[tree[p].ls].size+tree[p].cnt>=x){
return tree[p].dat;
}
else{
return ask2(tree[p].rs,x-tree[tree[p].ls].size-tree[p].cnt);
}
}
int ask3(int p,int x){//找前驱
if(!p)return -1e9;
else if(tree[p].dat>=x){
return ask3(tree[p].ls,x);
}
else{
return max(tree[p].dat,ask3(tree[p].rs,x));
}
}
int ask4(int p,int x){//找后继
if(!p)return 1e9;
else if(tree[p].dat<=x){
return ask4(tree[p].rs,x);
}
else{
return min(tree[p].dat,ask4(tree[p].ls,x));
}
}
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
srand(time(0));
scanf("%d",&n);
while(n--){
int op,x;
scanf("%d%d",&op,&x);
if(op==1){
insert(root,x);
}
else if(op==2){
del(root,x);
}
else if(op==3){
cout<<ask1(root,x)<<endl;
}
else if(op==4){
cout<<ask2(root,x)<<endl;
}
else if(op==5){
cout<<ask3(root,x)<<endl;
}
else if(op==6){
cout<<ask4(root,x)<<endl;
}
}
return 0;
}