静态数组Treap(用随机数维护的二叉搜索树)
2016-08-26 19:51
190 查看
#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; }
相关文章推荐
- 一维静态数组_实例:随机数与排序(附:源码)
- 一维静态数组_实例:寻找随机数最大值及其下标(附:源码)
- 静态数组实现TREAP
- 静态数组实现的二叉搜索树
- 维护集合Ⅰ【无旋Treap数组模板】
- JD 1009:二叉搜索树(静态数组建树)
- 九度 题目1009:二叉搜索树 (静态数组构建二叉树\二叉树的数组实现)
- 二维动态数组定义及二维静态数组与**P的区别
- delphi 动态数组和静态数组首地址的区别
- IOS NS 字符串 数组 字典 文件 动态 静态 操作
- 二位数组塑造二级联动下拉菜单(静态数据)
- 数组(静态初始化-常见问题)
- 静态数组表示的有限状态机
- 题目:把排序数组转换为高度最小的二叉搜索树
- Java语言基础-数组的静态初始化和内存分析
- Java的继承(继承、多态、动态绑定、静态绑定、泛型数组、对象包装器的自动装箱与自动拆箱)
- 把排序数组转换为高度最小的二叉搜索树-LintCode
- 数组工具类中静态的使用与文档注释
- POJ 3415 Common Substrings 后缀数组 + 单调栈维护
- Java生成指定范围的随机数或指定数组中的随机数