Teap树堆
2016-06-28 20:24
405 查看
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; }
相关文章推荐
- C#中struct和class的区别详解
- 深入剖析C++中的struct结构体字节对齐
- C++ 关于STL中sort()对struct排序的方法
- C# Struct的内存布局问题解答
- Javascript SHA-1:Secure Hash Algorithm
- 深入C++中struct与class的区别分析
- 浅析c与c++中struct的区别
- c++中struct使用注意事项
- 深入解析C#编程中struct所定义的结构
- 浅析内存对齐与ANSI C中struct型数据的内存布局
- php读取二进制流(C语言结构体struct数据文件)的深入解析
- 详解C++程序中定义struct结构体的方法
- Go语言struct类型介绍
- 在Python的struct模块中进行数据格式转换的方法
- Python struct模块解析
- Go语言中struct的匿名属性特征实例分析
- 浏览器运行java插件报错:Algorithm constraints check failed: MD5withRSA
- 优化结构体中元素的布局
- ext关于session失效的处理
- Python 10.4 struct