静态数组实现TREAP

#include<stdio.h>
#include<stdlib.h>
struct node{
	int x,w,h,r,l;
};
struct node a[100001];
int e,root=1;

void rotate_left(int v,int u){
	int t=a[u].h;
	a[u].r=a[v].l;a[a[v].l].h=u;
	a[u].h=v;a[v].l=u;
	a[v].h=t;
	if(a[t].l==u)a[t].l=v;
	else a[t].r=v;	
}

void rotate_right(int v,int u){
	int t=a[u].h;
	a[u].l=a[v].r;a[a[v].r].h=u;
	a[u].h=v;a[v].r=u;
	a[v].h=t;
	if(a[t].l==u)a[t].l=v;
	else a[t].r=v;	
}

void insert(int v,int u){
	int p;
	if(!v)return;
	if(u>a[v].x){
		if(!a[v].r){
			a[++e].x=u;
			a[e].w=rand();
			a[e].h=v;
			a[v].r=e;
			p=e;
			while(a[p].h && a[p].w<=a[a[p].h].w){
				if(p==a[a[p].h].r)
					rotate_left(p,a[p].h);
				else	rotate_right(p,a[p].h);
			}
			if(a[p].h==0)root=p;
		}else insert(a[v].r,u);			
	}else{
		if(!a[v].l){
			a[++e].x=u;
			a[e].w=rand();
			a[e].h=v;
			a[v].l=e;
			p=e;
			while(a[p].h && a[p].w<=a[a[p].h].w){
				if(p==a[a[p].h].r)
					rotate_left(p,a[p].h);
				else	rotate_right(p,a[p].h);
			}
			if(a[p].h==0)root=p;
		}else insert(a[v].l,u);	
	}
}
void out(int s){
	if(!s)return;
	out(a[s].l);
	printf("%d ",a[s].x);
	out(a[s].r);
}
int main(){
	int i,j,k,m,n;
	scanf("%d",&n);
	scanf("%d",&k);
	srand(3221);
	a[1].x=k;e=1;
	a[1].w=rand();
	for(i=2;i<=n;i++){
		scanf("%d",&k);
		insert(root,k);
	}
	out(root);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值