SDUT 3043-迷之容器(Treap求第k小数)

题目链接:点击打开链接

动态询问第k小,只有插入和查询两种操作,第一发平衡树。。纪念(sad 不全,没有删除操作,本题没要求嘛)。主要是不会离散化用线段树不会写。。拼死敲了两天Treap

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <cctype>
#include <vector>
#include <cstdio>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#define maxn 1005
#define _ll __int64
#define ll long long
#define INF 0x3f3f3f3f
#define Mod 1<<40+10
#define pp pair<int,int>
#define ull unsigned long long
using namespace std;
int n;
struct node{
	node *ch[2];
	int r,v,s;
	node (){}
	node (int v){ch[0]=NULL;ch[1]=NULL;r=rand();this->v=v;s=1;}
	bool operator <(const node& c)const{
		return r<c.r;
	}
	int cmp(int x)const {
		if(x==v)return -1;
		return x<v?0:1;
	}
	void maintain(){
		s=1;
		if(ch[0]!=NULL)s+=ch[0]->s;
		if(ch[1]!=NULL)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{
		int d=o->cmp(x);
		insert(o->ch[d],x);
		if(o->ch[d]->r>o->r)rotate(o,d^1);
	}
	o->maintain();
}
bool Find(node* o,int x)
{
	while(o!=NULL)
	{
		int d=o->cmp(x);
		if(d==-1)return 1;
		else o=o->ch[d];
	}
	return 0;
}
int find_kth(node* o,int k)
{
	if(o==NULL||k>o->s)return -1;
	int s=(o->ch[0]==NULL?0:o->ch[0]->s);
	if(k==s+1)return o->v;
	else if(k<=s) return find_kth(o->ch[0],k);
	else return find_kth(o->ch[1],k-s-1);
}
void solve()
{
	node *root=NULL;
	char op[2];int x;
	while(n--)
	{
		scanf("%s %d",op,&x);
		if(op[0]=='P')
		{
			if(Find(root,x))continue;
			insert(root,x);
		}
		else
			printf("%d\n",find_kth(root,x));
	}
}
int main()
{
	while(~scanf("%d",&n))
		solve();
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值