Treap平衡树

#include<stdio.h>  
#include<stdlib.h>  
#include<string.h>  
#include<iostream>  
#include<algorithm>  
using namespace std;  
  
struct node{  
    int x,w;  
    struct node *l,*r,*f;  
    node(){  
        x=0;  
        w=(int)rand()*1.0/32767*2147483647;;  
        l=r=f=NULL;  
    }  
};  
struct node *h,*p,*q,*v,*tmp; 
  
void left(struct node *u){  
    v=u->f;  
    if (v==h)  
        h=u;  
    v->r=u->l;  
    if (u->l!=NULL)  
        u->l->f=v;  
    u->f=v->f;  
    if (v->f!=NULL)  
        if (v==v->f->l)  
            v->f->l=u;  
        else v->f->r=u;  
    v->f=u;  
    u->l=v;  
}  
void right(struct node *u){  
    v=u->f;  
    if (v==h)  
        h=u;  
    v->l=u->r;  
    if (u->r!=NULL)  
        u->r->f=v;  
    u->f=v->f;  
    if (v->f!=NULL)  
        if (v==v->f->l)  
            v->f->l=u;  
        else v->f->r=u;  
    v->f=u;  
    u->r=v;  
}  
void insert(struct node *f,int k){  
    if (k<f->x){  
        if (f->l==NULL){  
            p=new node;  
            p->x=k;  
            p->f=f;  
            f->l=p;  
            while (p->f!=NULL && p->w<p->f->w)  
                if (p==p->f->l)  
                    right(p);  
                else left(p);  
        }else insert(f->l,k);  
    }else{  
        if (f->r==NULL){  
            p=new node;  
            p->x=k;  
            p->f=f;  
            f->r=p;  
            while (p->f!=NULL && p->w<p->f->w)  
                if (p==p->f->l)  
                    right(p);  
                else left(p);  
        }else insert(f->r,k);  
    }  
}  
void out(struct node *f){  
    if (f->l!=NULL) out(f->l);  
    printf("%d ",f->x);  
    if (f->r!=NULL) out(f->r);  
    delete f;  
}
bool find(struct node *f,int k){
	if (k==f->x)
		return 1;
	if (k<f->x){
		if (f->l==NULL)
			return 0;
		else find(f->l,k);
	}else{
		if (f->r==NULL)
			return 0;
		else find(f->r,k);
	}
}
bool del(struct node *f,int k){
	if (k==f->x){
		while (f->l!=NULL || f->r!=NULL){
			if (f->l==NULL || (f->r!=NULL && f->r->w<f->l->w))
				left(f->r);
			else right(f->l);
		}
		return 1;
	}
	if (k<f->x){
		if (f->l==NULL)
			return 0;
		else del(f->l,k);
	}else{
		if (f->r==NULL)
			return 0;
		else del(f->r,k);
	}
}
  
int main(){  
    int i,j,k,m,n;  
    srand(32767);  
    h=new node;  
    h->f=NULL;  
    scanf("%d",&n);  
    scanf("%d",&h->x);  
    for (i=2;i<=n;i++){  
        scanf("%d",&k);  
        insert(h,k);  
    }
	scanf("%d",&m);
	for (i=1;i<=m;i++){
		scanf("%d",&k);
		printf("%d",find(h,k));
	}
	scanf("%d",&m);
	for (i=1;i<=m;i++){
		scanf("%d",&k);
		printf("%d",del(h,k));
	}
    return 0;  
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值