forked from sandeshghanta/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtreap.cpp
120 lines (120 loc) · 1.87 KB
/
treap.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include<bits/stdc++.h>
using namespace std;
struct node{
int value;
int priority;
node *l;
node *r;
};
bool flag = true;
void split(node *t,node *&l,node *&r,int key){
if (!t){
l = NULL;
r = NULL;
return;
}
if (t->value < key){
split(t->r,t->r,r,key);
l = t;
}
else{
split(t->l,l,t->l,key);
r = t;
}
}
void insert(node *&t, node* it){
if (!t){
t = it;
return;
}
if (t->priority < it->priority){
split(t,it->l,it->r,it->value);
t = it;
}
else{
if (t->value > it->value){
insert(t->l,it);
}
else{
insert(t->r,it);
}
}
}
void merge(node *&t,node *&l,node *&r){
if (!l || !r){
t = l?l:r;
return;
}
if (l->priority > r->priority){
merge(l->r,l->r,r);
t = l;
}
else{
merge(r->l,l,r->l);
t = r;
}
}
void erase(node *&t,int key){
if (!t){
return;
}
if (t->value == key){
node* temp = t;
cout << "printing temp " << temp->value << " " << temp->priority << endl;
merge(t,t->l,t->r);
free(temp);
cout << "printing temp " << temp->value << " " << temp->priority << endl;
}
else{
if (t->value > key){
erase(t->l,key);
}
else{
erase(t->r,key);
}
}
}
node * create(int val){
node* temp = new node();
temp->value = val;
temp->priority = rand();
return temp;
}
void print(node *temp){
cout << "starting print job" << endl;
queue<node *>q;
q.push(temp);
while (q.size() > 0){
node *el = q.front();
q.pop();
cout << el->value << " " << el->priority << endl;
if (el->l){
q.push(el->l);
}
if (el->r){
q.push(el->r);
}
}
cout << "ending print job" << endl;
}
node * init(int value){
node *temp = new node();
temp->value = value;
temp->priority = rand();
return temp;
}
int main(){
int n,i,el;
cout << "Enter the number of nodes ";
cin >> n;
node *root = NULL;
for (i=0;i<n;i++){
cin >> el;
node* temp = init(el);
insert(root,temp);
}
print(root);
erase(root,5);
print(root);
return 0;
}