-
Notifications
You must be signed in to change notification settings - Fork 249
/
Copy pathCartesianTree.cpp
123 lines (107 loc) · 2.51 KB
/
CartesianTree.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
/*************************************************************************************
Cartesian tree. Can be used as a balanced binary search tree.
O(logN) on operation.
Based on problem 2782 from informatics.mccme.ru:
http://informatics.mccme.ru/mod/statements/view3.php?chapterid=2782
*************************************************************************************/
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <utility>
#include <iomanip>
using namespace std;
const int mod = 1000 * 1000 * 1000;
struct node {
int x, y;
node *l, *r;
node(int new_x, int new_y) {
x = new_x; y = new_y;
l = NULL; r = NULL;
}
};
typedef node * pnode;
void merge(pnode &t, pnode l, pnode r) {
if (l == NULL)
t = r;
else if (r == NULL)
t = l;
else if (l->y > r->y) {
merge(l->r, l->r, r);
t = l;
}
else {
merge(r->l, l, r->l);
t = r;
}
}
void split(pnode t, int x, pnode &l, pnode &r) {
if (t == NULL)
l = r = NULL;
else if (t->x > x) {
split(t->l, x, l, t->l);
r = t;
}
else {
split(t->r, x, t->r, r);
l = t;
}
}
void add(pnode &t, pnode a) {
if (t == NULL)
t = a;
else if (a->y > t->y) {
split(t, a->x, a->l, a->r);
t = a;
}
else {
if (t->x < a->x)
add(t->r, a);
else
add(t->l, a);
}
}
int next(pnode t, int x) {
int ans = -1;
while (t != NULL) {
if (t->x < x)
t = t->r;
else {
if (ans == -1 || ans > t->x)
ans = t->x;
t = t->l;
}
}
return ans;
}
int n, ans, x;
char qt, prev_qt;
pnode root = NULL, num;
int main() {
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
scanf("%d\n", &n);
for (int i = 1; i <= n; i++) {
scanf("%c %d\n", &qt, &x);
if (qt == '+') {
if (prev_qt == '?')
x = (x + ans) % mod;
num = new node(x, rand());
add(root, num);
}
else {
ans = next(root, x);
printf("%d\n", ans);
}
prev_qt = qt;
}
return 0;
}