关于使用平衡树动态求解中位数

本文介绍了如何利用C++中的Treap(自平衡二叉搜索树)数据结构实现动态求解中位数问题,包括插入操作和查询给定位置的中位数节点值。
摘要由CSDN通过智能技术生成

洛谷直达

关于使用平衡树动态求解中位数

当然stl set<int>也可以

#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <string.h>
using namespace std;
const int N=2e4;
struct node 
{
	node *lf=NULL,*rt=NULL;
	const int rawk=rand();
	int date,siz=1,cnt=1;
	node(const int x){date=x;}
};
struct treap
{
	protected:
	node *root=NULL;
	inline void pu(node *cur){
		if(cur==NULL){return;}
		int temp=cur->cnt;
		temp+=cur->lf==NULL? 0: cur->lf->siz;
		temp+=cur->rt==NULL? 0: cur->rt->siz;
		cur->siz=temp;
	}
	void zig(node *&cur){
		if(cur==NULL){return;}
		node *temp=cur->lf;
		cur->lf=temp->rt;
		temp->rt=cur;
		pu(cur),pu(temp);
		cur=temp;
	}
	void zag(node *&cur){
		if(cur==NULL){return;}
		node *temp=cur->rt;
		cur->rt=temp->lf;
		temp->lf=cur;
		pu(cur),pu(temp);
		cur=temp;
	}
	void insert_sx(node *&cur,int x){
		if(cur==NULL){cur=new node(x);return;}
		if(cur->date>x){
			insert_sx(cur->lf,x);
			if(cur->rawk>cur->lf->rawk){zig(cur);}
		}
		else if(cur->date<x){
			insert_sx(cur->rt,x);
			if(cur->rawk>cur->rt->rawk){zag(cur);}
		}
		else{++cur->cnt;}
		pu(cur);
	}
	node *rankval_sx(node *cur,int rk){
		int temp=cur->lf==NULL? 0:cur->lf->siz;
		if(rk<=temp){return rankval_sx(cur->lf,rk);}
		if(rk<=temp+cur->cnt){return cur;}
		return rankval_sx(cur->rt,rk-temp-cur->cnt);
	}
	public:
	void insert(int x){insert_sx(root,x);}
	node *rankval(int rk){return rankval_sx(root,rk);}
}t;
int n,G,now;
char cz[10];
int main()
{
	scanf("%d",&now);G=now;
	--now;
	while(G--)
	{
		scanf("%d",&n);
		t.insert(n);
	}
	scanf("%d",&G);
	while(G--)
	{
		scanf("%s",cz);
		if(strcmp(cz,"add")==0)
		{scanf("%d",&n);t.insert(n);now++;}
		else
		{printf("%d\n",t.rankval((now/2)+1)->date);}
	}
	
	

    return 0;
}



















  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值