Teap树堆

2024-06-07 15:48
文章标签 树堆 teap

本文主要是介绍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;}elsep = 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);elseprintf("%d\n", query(root, k));}return 0;
}

这篇关于Teap树堆的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1039608

相关文章

树学习 ---------树堆(Treap Tree)

树堆,在数据结构中也称Treap,是指有一个随机附加域满足堆的性质的二叉搜索树,其结构相当于以随机数据插入的二叉搜索树。 其基本操作的期望时间复杂度为O(logn)。相对于其他的平衡二叉搜索树,Treap的特点是实现简单,且能基本实现随机平衡的结构。 这个堆树的结构和数据结构中的堆类似,可以排序并且: 显示一

OJ中常用平衡树,Treap树堆详解

文章目录 Treap定义Treap的可行性Treap的构建节点定义旋转左单旋右单旋旋转的代码实现 插入插入的代码实现 删除遍历查找Treap对权值的扩展Treap对size的扩展扩展size域后的节点定义和旋转,插入,删除操作查询第k小的元素求元素的排名 查询后继、前驱Treap类的代码实现Treap的特点 无旋式Treap无旋式Treap 定义无旋式Treap 的特点无旋式Treap 的节