TREAP平衡树
2016-01-31 16:37
316 查看
#include<cstdio> #include<stdlib.h> using namespace std; struct node{ int x,w,h,r,l; }; struct node a[10001]; int e; void rl(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 rr(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 ins(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) rl(p,a[p].h); else rr(p,a[p].h); } }else ins(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) rl(p,a[p].h); else rr(p,a[p].h); } }else ins(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,root=1; scanf("%d",&n); scanf("%d",&k); srand(2141); a[1].x=k;e=1; a[1].w=rand(); for(i=2;i<=n;i++){ scanf("%d",&k); ins(root,k); } out(1); return 0; }
相关文章推荐
- leetcode 136. Single Number
- iOS开发之JSON格式数据的生成与解析
- $.ajax()方法详解
- android 对sqlite数据库的增删改查等各种操作
- uva 10020 Minimal coverage
- C++之pair与make_pair
- java.net.SocketException: Can't assign requested address
- LeetCode数据库练习题MySql
- QT 实现在一个模块中间显示一个红色提示框,3秒后消失
- [置顶] Rational Rose安装与报错问题
- WPF学习笔记(一):数据绑定之元素到元素绑定
- Wordpress-插件概述
- 广度优先和深度优先
- POJ 3259/USACO 2006 December Gold:Wormholes
- busybox filesystem matrix-gui-2.0 undefined function json_encode()
- UNITY 5.3.2 发行说明 中文版
- 网络——发送email(一个简单荔枝)
- bzoj 2463 [中山市选2009]谁能赢呢?(博弈)
- mysql的内存使用
- 三层登录—c#