FHQ treap求调
  • 板块学术版
  • 楼主Little_CartG2_leaf
  • 当前回复9
  • 已保存回复9
  • 发布时间2023/11/17 11:26
  • 上次更新2023/11/17 21:19:01
查看原帖
FHQ treap求调
392157
Little_CartG2_leaf楼主2023/11/17 11:26

rt。

在进行一次 insert 操作后,我进行了 get_k 操作,然后进死循环了,我怀疑我的 get_k 写挂了,有无佬帮忙调一调/kel

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=200024,inf=0x3f3f3f3f;
int n,cnt,root;
struct node{
	int lson,rson,val,siz,pri;
}tre[N];
int randd(){
	return rand()*32768+rand();
}
int crt(int val){
	cnt++;
	tre[cnt].lson=0;
	tre[cnt].rson=0;
	tre[cnt].pri=randd();
	tre[cnt].siz=1;
	tre[cnt].val=val;
	return cnt;
}
void pushup(int x){
	tre[x].siz=tre[tre[x].lson].siz+tre[tre[x].rson].siz+1;
}
void splitv(int root,int val,int &x,int &y){
	if(root==0){
		x=0;
		y=0;
		return;
	}
	if(tre[root].val<=val){
		x=root;
		splitv(tre[root].rson,val,tre[root].rson,y);
	}
	else{
		y=root;
		splitv(tre[root].lson,val,x,tre[root].lson);
	}
	pushup(root);
}
void splits(int root,int siz,int &x,int &y){
	if(root==0){
		x=0;
		y=0;
		return;
	}
	if(tre[tre[root].lson].siz+1<=siz){
		x=root;
		splits(tre[root].rson,siz-tre[tre[root].lson].siz-1,tre[root].rson,y);
	}
	else{
		y=root;
		splits(tre[root].lson,siz,x,tre[root].lson);
	}
	pushup(root);
}
int merge(int x,int y){
	if(!x||!y){
		return x|y;
	}
	if(tre[x].pri<tre[y].pri){
		tre[x].rson=merge(tre[x].rson,y);
		pushup(x);
		return x;
	}
	else{
		tre[y].lson=merge(x,tre[y].lson);
		pushup(y);
		return y;
	}
}
void ins(int val){
	int x,y;
	splitv(root,val-1,x,y);
	root=merge(merge(x,crt(val)),y);
}
void del(int val){
	int x,y,p,q;
	splitv(root,val-1,x,y);
	splitv(y,val,p,q);
	root=merge(merge(x,merge(tre[p].lson,tre[p].rson)),q);
}
int get_rk(int val){
	int x,y,ans;
	splitv(root,val-1,x,y);
	ans=tre[x].siz+1;
	root=merge(x,y);
	return ans;
}
int get_k(int rt,int rk){
	if(tre[tre[rt].lson].siz<=rk){
		return get_k(tre[rt].lson,rk);
	}
	else if(tre[tre[rt].lson].siz+1==rk){
		return tre[rt].val;
	}
	else{
		return get_k(tre[rt].lson,rk-tre[tre[rt].lson].siz-1);
	}
}
int get_pre(int val){
	int rk=get_rk(val)-1;
	return get_k(root,rk);
}
int get_nxt(int val){
	int rk=get_rk(val+1);
	return get_k(root,rk);
}
int op,x;
signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	srand(time(0));
	cin>>n;
	ins(inf);
	ins(-inf);
	for(int i=1;i<=n;i++){
		cin>>op>>x;
		if(op==1){
			ins(x);
		}
		else if(op==2){
			del(x);
		}
		else if(op==3){
			cout<<get_rk(x)<<"\n";
		}
		else if(op==4){
			cout<<get_k(root,x)<<"\n";
		}
		else if(op==5){
			cout<<get_pre(x)<<"\n";
		}
		else if(op==6){
			cout<<get_nxt(x)<<"\n";
		}
	}
}

2023/11/17 11:26
加载中...