Skip to content

Commit c7dd029

Browse files
Merge pull request matthewsamuel95#535 from koneko096/master
Add treap data structure
2 parents aedcc52 + 63eb384 commit c7dd029

File tree

2 files changed

+112
-0
lines changed

2 files changed

+112
-0
lines changed

Data Structures/Treap/treap.cpp

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
typedef struct node {
5+
int val,prior,size;
6+
struct node *l,*r;
7+
} node;
8+
9+
typedef node* pnode;
10+
11+
int sz (pnode t) {
12+
return t ? t->size : 0;
13+
}
14+
15+
void upd_sz (pnode t) {
16+
if (t) {
17+
t->size = sz(t->l) + 1 + sz(t->r);
18+
}
19+
}
20+
21+
pnode find (pnode t, int key) {
22+
if (t == NULL || t->val == key) {
23+
return t;
24+
}
25+
26+
return find(t->val < key ? t->r : t->l, key);
27+
}
28+
29+
void split (pnode t, pnode &l, pnode &r, int key) {
30+
if (!t) {
31+
l = r = NULL;
32+
}
33+
else if (t->val <= key) {
34+
split(t->r, t->r, r, key);
35+
l = t;
36+
}
37+
else {
38+
split(t->l, l, t->l, key);
39+
r = t;
40+
}
41+
42+
upd_sz(t);
43+
}
44+
45+
void merge (pnode &t, pnode l, pnode r) {
46+
if (!l || !r) {
47+
t = l?l:r;
48+
}
49+
else if (l->prior > r->prior) {
50+
merge(l->r, l->r, r);
51+
t = l;
52+
}
53+
else {
54+
merge(r->l, l, r->l);
55+
t = r;
56+
}
57+
58+
upd_sz(t);
59+
}
60+
61+
void insert (pnode &t, pnode it) {
62+
if (!t) {
63+
t = it;
64+
}
65+
else if (it->prior > t->prior) {
66+
split(t, it->l, it->r, it->val);
67+
t = it;
68+
}
69+
else {
70+
insert(t->val <= it->val ? t->r : t->l, it);
71+
}
72+
73+
upd_sz(t);
74+
}
75+
76+
void erase (pnode &t, int key) {
77+
pnode p = find(t, key);
78+
if (p == NULL) {
79+
return;
80+
}
81+
82+
pnode temp = t;
83+
merge(t, p->l, p->r);
84+
free(temp);
85+
86+
upd_sz(t);
87+
}
88+
89+
pnode init (int val) {
90+
pnode ret = (pnode)malloc(sizeof(node));
91+
ret->val = val;
92+
ret->size = 1;
93+
ret->prior = rand();
94+
ret->l = ret->r = NULL;
95+
return ret;
96+
}
97+
98+
int main() {
99+
pnode t = init(4);
100+
insert(t, init(19));
101+
insert(t, init(8));
102+
insert(t, init(27));
103+
insert(t, init(20));
104+
insert(t, init(12));
105+
insert(t, init(15));
106+
insert(t, init(6));
107+
insert(t, init(7));
108+
insert(t, init(8));
109+
110+
return 0;
111+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ ACM-ICPC Algorithms is a collection of important algorithms and data structures
5454
* [Singly Linked List](/Data%20Structures/SinglyLinkedList)
5555
* [Stack](/Data%20Structures/Stack)
5656
* [Segment Tree](/Data%20Structures/Segment%20Tree)
57+
* [Treap](/Data%20Structures/Treap)
5758
* [Trie](/Data%20Structures/Trie)
5859
* [Dynamic Programming](/DP)
5960
* [Coin Change](/DP/Coin%20Change%20Problem)

0 commit comments

Comments
 (0)