poj 3481 Double Queue(Treap,模板题)

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define mian main
using namespace std;

struct Node{
	int r, val, name;
	Node* ch[2];
	int cmp(int x) const{
		if(x == val)	return -1;
		return x < val ? 0 : 1;
	}
};

void rotate(Node*& o, int d){      // d=0左旋,d=1右旋
	Node* k =  o->ch[d^1];
	o->ch[d^1] = k->ch[d];
	k->ch[d] = o;
	o = k;
}

void insert(Node*& o, int name, int val){
	if(o == NULL){
		o = new Node();
		o->ch[0] = o->ch[1] = NULL;
		o->val = val;
		o->name = name;
		o->r = rand();
	}
	else{
		int d = o->cmp(val);
		insert(o->ch[d], name, val);
		if(o->ch[d]->r > o->r)
			rotate(o, d^1);
	}
}

void remove(Node*& o, int x){
	int d = o->cmp(x);
	if(d == -1){
		if(o->ch[0] == NULL)
			o = o->ch[1];
		else
		if(o->ch[1] == NULL)
			o = o->ch[0];
		else{
			int d2 = (o->ch[0]->r > o->ch[1]->r ? 1 : 0);
			rotate(o, d2);
			remove(o->ch[d2], x);
		}
	}
	else
		remove(o->ch[d], x);
}

int find_max(Node* o, int& name){
	if(o == NULL)
		return -1;
	while(o->ch[1] != NULL)
		o = o->ch[1];
	name = o->name;
	return o->val;
}

int find_min(Node* o, int& name){
	if(o == NULL)
		return -1;
	while(o->ch[0] != NULL)
		o = o->ch[0];
	name = o->name;
	return o->val;
}


int main(){
	//freopen("ztest.txt","r",stdin);
	int n;
	Node* root = NULL;
	while(scanf("%d", &n) && n){
		if(n == 2)
		{
			int name;
			int maxv = find_max(root, name);
			if(maxv == -1)
				printf("0\n");
			else{
				printf("%d\n",name);
				remove(root, maxv);
			}
		}
		if(n == 3)
		{
			int name;
			int minv = find_min(root, name);
			if(minv == -1)
				printf("0\n");
			else{
				printf("%d\n",name);
				remove(root, minv);
			}
		}
		if(n == 1)
		{
			int name, val;
			scanf("%d%d", &name, &val);
			insert(root, name, val);
		}
	}
	return 0;
}
			
			
	

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值