forked from Dev-XYS/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Splay.cpp
134 lines (126 loc) · 1.68 KB
/
Splay.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
#include <cstdio>
#define NIL 0
using namespace std;
struct node
{
int key, value;
node *ch[2];
node(int _key = 0, int _value = 0) : key(_key), value(_value) { ch[0] = ch[1] = NIL; }
}*root;
void rotate(node *&u, int dir)
{
node *o = u->ch[dir];
u->ch[dir] = o->ch[dir ^ 1];
o->ch[dir ^ 1] = u;
u = o;
}
inline int compare(node *u, int key)
{
if (key == u->key)
{
return -1;
}
return key < u->key ? 0 : 1;
}
void insert(node *&u, int key, int value)
{
if (u == NIL)
{
u = new node(key, value);
return;
}
int k0 = compare(u, key);
if (k0 == -1)
{
return;
}
if (u->ch[k0] == NIL)
{
u->ch[k0] = new node(key, value);
}
else
{
int k1 = compare(u->ch[k0], key);
if (k1 == -1)
{
return;
}
insert(u->ch[k0]->ch[k1], key, value);
if (k0 == k1)
{
rotate(u, k0);
}
else
{
rotate(u->ch[k0], k1);
}
}
rotate(u, k0);
}
int find(node *&u, int key)
{
if (u == NIL)
{
return -1;
}
int k0 = compare(u, key);
if (k0 == -1)
{
return u->value;
}
if (u->ch[k0] == NIL)
{
return -1;
}
else
{
int k1 = compare(u->ch[k0], key), res;
if (k1 == -1)
{
res = u->ch[k0]->value;
goto END;
}
res = find(u->ch[k0]->ch[k1], key);
if (u->ch[k0]->ch[k1] != NIL)
{
if (k0 == k1)
{
rotate(u, k0);
}
else
{
rotate(u->ch[k0], k1);
}
}
END:
rotate(u, k0);
return res;
}
}
int main()
{
int in, key, value;
while (true)
{
scanf("%d", &in);
if (in == 1)
{
scanf("%d%d", &key, &value);
insert(root, key, value);
}
else if (in == 2)
{
scanf("%d", &key);
printf("%d\n", find(root, key));
}
else if (in == 0)
{
return 0;
}
else
{
printf("No such command!\n");
}
}
return 0;
}