-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2111.cpp
More file actions
executable file
·81 lines (74 loc) · 1.66 KB
/
Copy path2111.cpp
File metadata and controls
executable file
·81 lines (74 loc) · 1.66 KB
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 <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
struct node {
int data;
node *left, *right;
node(int dt):data(dt), left(nullptr), right(nullptr) {}
};
void insert(node* &rt, int p) {
if(rt == nullptr) {
rt = new node(p);
} else if(rt->data < p) {
insert(rt->right, p);
} else if(rt->data > p) {
insert(rt->left, p);
}
}
void del(node* &rt, int key) {
if(rt->data < key) {
del(rt->right, key);
return;
} else if(rt->data > key) {
del(rt->left, key);
return;
}
if(rt->left == nullptr && rt->right == nullptr) {
delete rt;
rt = nullptr;
} else if(rt->left && rt->right == nullptr) {
rt = rt->left;
} else if(rt->left == nullptr && rt->right) {
rt = rt->right;
} else {
node* tmp = rt->right;
while(tmp->left) tmp = tmp->left;
rt->data = tmp->data;
del(rt->right, rt->data);
}
}
int min(int x, int y) {
return x < y ? x : y;
}
int query(node* rt, int x) {
int ans = 2e9;
while(rt != nullptr) {
if(rt->data < x) {
ans = min(ans, x - rt->data);
rt = rt->right;
} else if(rt->data > x) {
ans = min(ans, rt->data - x);
rt = rt->left;
} else return 0;
}
return ans;
}
node *root;
int M, op, x;
int main() {
scanf("%d", &M);
for(int i = 0;i < M;++ i) {
scanf("%d%d", &op, &x);
if(op == 0) {
printf("%d\n", query(root, x));
} else if(op == 1) {
insert(root, x);
} else {
del(root, x);
}
}
}