-
Notifications
You must be signed in to change notification settings - Fork 439
/
Leftist-Tree.cpp
81 lines (73 loc) · 1.02 KB
/
Leftist-Tree.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
#include <cstdio>
using namespace std;
struct node
{
node *lch, *rch;
int key, dis;
node(int _key = 0, int _dis = 0);
}*root, *nil;
node::node(int _key, int _dis) : key(_key), dis(_dis)
{
lch = rch = nil;
}
void init()
{
nil = new node(0, -1);
root = nil;
}
inline void swap(node *&u, node *&v)
{
node *temp = u;
u = v;
v = temp;
}
void merge(node *&u, node *&v)
{
if (u == nil)
{
u = v;
return;
}
if (v == nil) return;
if (u->key > v->key) swap(u, v);
merge(u->rch, v);
if (u->lch->dis < u->rch->dis) swap(u->lch, u->rch);
u->dis = u->rch->dis + 1;
}
int extract_min()
{
int res = root->key;
merge(root->lch, root->rch);
node *del = root;
root = root->lch;
delete del;
return res;
}
int main()
{
int op, x;
init();
while (true)
{
scanf("%d", &op);
if (op == 1)
{
scanf("%d", &x);
node *o = new node(x, 0);
merge(root, o);
}
else if (op == 2)
{
printf("%d\n", extract_min());
}
else if (op == 0)
{
break;
}
else
{
printf("No such command!\n");
}
}
return 0;
}