洛谷 P3369 【模板】普通平衡树 仿刘汝佳风格代码的treap

本文深入解析Treap数据结构的基本操作与实现细节,通过一道模板题进行实战练习,提供仿刘汝佳风格的代码示例,帮助读者理解Treap的旋转、插入、删除、查找等核心算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

P3369

Treap基本操作,当做模板题练练手了,看了好多题解代码,发现没有刘汝佳风格的代码,就决定写一份仿刘汝佳代码。

#include<cstdio>
#include<cstdlib> 
#include<algorithm>
using namespace std;
const int inf=1e9;
struct Node *null;
struct Node
{
	Node *ch[2];
	int r;
	int v;
	int w;//多出来的w是记录相同的数的个数 
	int s;
	Node(int v):v(v){ch[0]=ch[1]=null;r=rand();s=w=1;}
	bool operator<(const Node& rhs)const{
		return r<rhs.r;
	}
	int cmp(int x)const{
		if(x==v)return -1;
		return x<v?0:1;
	}
	void maintain()
	{
		s=w;
		s+=ch[0]->s;
		s+=ch[1]->s;
	}
};
void rotate(Node* &o,int d)
{
	Node *k=o->ch[d^1];o->ch[d^1]=k->ch[d];
	k->ch[d]=o;o->maintain();k->maintain();
	o=k;
}
void insert(Node* &o,int x)
{
	if(o==null) o=new Node(x);
	else if(o->v==x)
	o->w++,o->maintain();
	else
	{
		int d=(x<o->v?0:1);
		insert(o->ch[d],x);
		if(o->ch[d]->r>o->r)rotate(o,d^1);
	}
	o->maintain();
}
void remove(Node* &o,int x){
	int d=o->cmp(x);
	if(d==-1){
		if(o->w>1)
		{
			o->w--;
			o->maintain();
			return;
		}
		Node* u=o;
		if(o->ch[0]!=null&&o->ch[1]!=null)
		{
			int d2=(o->ch[0]->r>o->ch[1]->r?1:0);
			rotate(o,d2);remove(o->ch[d2],x);
		}else{
			if(o->ch[0]==null)
			o=o->ch[1];
			else o=o->ch[0];
			delete u;
		}
	}
	else
	remove(o->ch[d],x);
	if(o!=null)o->maintain();
}
int kth(Node* o,int k)
{
	if(o==null||k<=0||k>o->s)return 0;
	int s=(o->ch[0]==null?0:o->ch[0]->s);
	if(k>s&&k<=s+o->w)return o->v;
	else if(k<=s)return kth(o->ch[0],k);
	else return kth(o->ch[1],k-s-o->w);
}
int rank(Node* o,int k,int sum)
{
	if(o==null)return sum+1;
	if(o->v==k)return o->ch[0]->s+1+sum;
	else if(k<o->v)return rank(o->ch[0],k,sum);
	else return rank(o->ch[1],k,sum+o->ch[0]->s+o->w);
}
int ans;
void pre(Node *o,int k)
{
	if(o==null)return;
	if(o->v<k)
	{
		ans=max(ans,o->v);
		pre(o->ch[1],k);
	}
	else
	pre(o->ch[0],k);	
}
void next(Node *o,int k)
{
	if(o==null)return;
	if(o->v>k)
	{
		ans=min(ans,o->v);
		next(o->ch[0],k); 
	}
	else
	next(o->ch[1],k);
}
int main()
{
	int q,op,x;
	scanf("%d",&q);
	null=new Node(0);
	null->s=null->w=0;
	Node *root=null;
	while(q--) 
	{
		scanf("%d%d",&op,&x);
		if(op==1) insert(root,x);
		else if(op==2) remove(root,x);
		else if(op==3) printf("%d\n",rank(root,x,0));
		else if(op==4) printf("%d\n",kth(root,x));
		else if(op==5) ans=-inf,pre(root,x),printf("%d\n",ans);
		else ans=inf,next(root,x),printf("%d\n",ans);
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长沙橘子猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值