Teap树堆

Treap

http://hihocoder.com/problemset/problem/1325
树堆,是二叉搜索树和堆的结合,是为了平衡二叉搜索树,使得平均复杂度为O(logn)。通过随机数来用堆的性质调整树结构。
这里写图片描述
左旋
这里写图片描述
右旋
这里写图片描述

#include<cstdio>
#include<cmath>
#include<cstdlib>

using namespace std;

struct _node
{
    struct _node * left;
    struct _node * right;
    int key;
    int priority;
    _node(int k):left(NULL), right(NULL), key(k), priority(rand()){};
};

//左旋
void leftRotate(struct _node *& a)
{
    struct _node * b = a->right;
    a->right = b->left;
    b->left = a;
    a = b;
}

//右旋
void rightRotate(struct _node *& a)
{
    struct _node * b = a->left;
    a->left = b->right;
    b->right = a;
    a = b;
}

//插入
void insert(struct _node *& root, int key)
{
    if(!root)
    {
        root = new _node(key);
        return;
    }
    if(key < root->key)
    {
        insert(root->left, key);
        if(root->priority > root->left->priority)
                rightRotate(root);
    }
    else
    {
        insert(root->right, key);
        if(root->priority > root->right->priority)
            leftRotate(root);
    }
}


//查询
int query(struct _node * root, int key)
{
    struct _node * p = root;
    int res = 0;
    while(p)
    {
        if(p->key == key) return key;
        else if(p->key < key)
        {
            res = p->key;
            p = p->right;
        }
        else
            p = p->left;
    }
    return res;
}


int main(void)
{
    int n,c,k;
    scanf("%d",&n);
    struct _node * root = NULL;
    while(n--)
    {
        scanf("%c%c%d", &c,&c,&k);
        if(c == 'I')
            insert(root, k);
        else
            printf("%d\n", query(root, k));
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值