forked from Dev-XYS/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Non-Rotating-Treap.cpp
142 lines (131 loc) · 1.76 KB
/
Non-Rotating-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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <utility>
using namespace std;
struct node
{
node *lch, *rch;
int key, pr;
node(int _key);
}*root, *nil;
node::node(int _key = 0) : lch(nil), rch(nil), key(_key), pr(rand()) { }
void init()
{
nil = new node;
root = nil;
}
pair<node*, node*> split(node *u, int x)
{
if (u == nil)
{
return make_pair(nil, nil);
}
if (x <= u->key)
{
pair<node*, node*> res = split(u->lch, x);
u->lch = res.second;
return make_pair(res.first, u);
}
else
{
pair<node*, node*> res = split(u->rch, x);
u->rch = res.first;
return make_pair(u, res.second);
}
}
node* merge(node *u, node *v)
{
if (u == nil)
{
return v;
}
else if (v == nil)
{
return u;
}
if (u->pr > v->pr)
{
u->rch = merge(u->rch, v);
return u;
}
else
{
v->lch = merge(u, v->lch);
return v;
}
}
int find(node *u, int x)
{
if (u == nil)
{
return 0;
}
if (u->key == x)
{
return 1;
}
if (x < u->key)
{
return find(u->lch, x);
}
else
{
return find(u->rch, x);
}
}
int find(int x)
{
return find(root, x);
}
void insert(int x)
{
if (find(root, x) == 1)
{
return;
}
node *u = new node(x);
pair<node*, node*> rts = split(root, x);
rts.first = merge(rts.first, u);
root = merge(rts.first, rts.second);
}
void print_tree(node *u)
{
if (u != nil)
{
printf("(");
print_tree(u->lch);
printf("%d", u->key);
print_tree(u->rch);
printf(")");
}
}
int main()
{
char op[10];
int x;
init();
while (true)
{
scanf("%s", op);
if (strcmp(op, "insert") == 0)
{
scanf("%d", &x);
insert(x);
}
else if (strcmp(op, "find") == 0)
{
scanf("%d", &x);
printf("%d\n", find(x));
}
else if (strcmp(op, "exit") == 0)
{
break;
}
else
{
printf("Command not found.\n");
}
}
return 0;
}