treap模版,treap

來源:互聯網
上載者:User

treap模版,treap

#include <cstdio>#include <cstring>#include <cstdlib>using namespace std;struct Node{Node *ch[2];int r;int v;int s;Node(int v): v(v) {ch[0] = ch[1] = NULL; r = rand(); s = 1;}bool operator < (const Node& rhs) const{return r < rhs.r;}int cmp(int x) const{if(x == v) return -1;return x < v ? 0 : 1;}void maintain(){s = 1;if(ch[0] != NULL) s += ch[0]->s;if(ch[1] != NULL) s += ch[1]->s;}};void rotate(Node* &o, int d){Node* k = o->ch[d^1]; o->ch[d^1] = k->ch[d]; k->ch[d] = 0;o->maintain(); k->maintain(); o = k;}void insert(Node* &o, int x){if(o == NULL){o = new Node(x);}else{int d = (x < o->v ? 0 : 1);insert(o->ch[d], x);if(o->ch[d] > o) rotate(o, d^1);}}void remove(Node* &o, int x){int d= o->cmp(x);if(d == -1){Node* u = o;if(o->ch[0] != NULL && o->ch[1] != NULL){int d2 = o->ch[0] > o->ch[1] ? 1 : 0;rotate(o, d2); remove(o->ch[d2], x);}else{if(o->ch[0] == NULL) o = o->ch[1];else o = o->ch[0];delete u;}}elseremove(o->ch[d], x);if(o != NULL) o->maintain();}


平衡樹 pascal 模板

{treap,在SBT之前我一直用的,不過這個模板應付noi/acm足夠了。。。加註釋真費勁。。。。}
var
//l[i],r[i],v[i]:i號結點的左兒子、右兒子,關索引值
//hr[i]:i號節點的優先值(treap所有子樹中,根的hr必須是最小的)
//s[i]:i號節點為根的子樹節點總數
l,r,hr,s,v:array[0..2000000]of longint;
n,root,m:longint;procedure init;//初始化
begin
readln(n);
m:=0;
//randomize; fillchar(s,sizeof(s),0);
fillchar(l,sizeof(l),0);
fillchar(r,sizeof(r),0);
root:=0;
end;//旋轉是平衡二叉樹的精髓,它不會改變bst的性質(左子樹<=根<=右子樹)
//左旋使樹的左子樹深度+1,右子樹深度-1
//右旋使樹的右子樹深度+1,左子樹深度-1
procedure l_rotate(var x:longint);//左旋以x為根的子樹(注意var參數及意義)
var
y:longint;
begin
y:=r[x]; //儲存x的右兒子到y中
r[x]:=l[y]; //將y的左兒子作為x的右兒子
l[y]:=x; //x作為y的左兒子
s[y]:=s[x]; //維護旋轉後的子樹大小
s[x]:=s[l[x]]+s[r[x]]+1;
x:=y; //y為根
end;procedure r_rotate(var x:longint);//右旋以x為根的子樹
var
y:longint;
begin
y:=l[x];
l[x]:=r[y];
r[y]:=x;
s[y]:=s[x];
s[x]:=s[l[x]]+s[r[x]]+1;
x:=y;
end;//插入(遞迴,if key<=root,則插入到左子樹,否則到右子樹,直到盡頭再建立節點)
procedure insert(var k,key:longint);
begin
if k=0 then//已到盡頭,建立節點並寫入key及隨機值hr
begin
inc(m);
v[m]:=key;
s[m]:=1;
hr[m]:=random(maxlongint);
k:=m;//修改k,使父節點指向當前節點(修改前從父節點指向0)
exit;
end;
inc(s[k]);
if key<=v[k] then//若key<=根則插入到左子樹,否則到右子樹
begin
insert(l[k],key);//若l[k]=0,到下層則建立節點並修改l[k]=m
if hr[l[k]]>hr[k] then //旋轉
r_rotate(k);
......餘下全文>>
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.