-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSegment tree.cpp
112 lines (92 loc) · 1.79 KB
/
Segment 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
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
#include <iostream>
#include <algorithm>
#define N 510
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
int n, q, start;
char command;
int X1, X2, Y1, Y2, x, y;
ll v;
ll c[N];
ll treeMax[4 * N];
ll treeMin[4 * N];
void build_tree_max() {
for (int i = start - 1; i > 0; i--)
treeMax[i] = max(treeMax[i * 2], treeMax[i * 2 + 1]);
}
void build_tree_min() {
for (int i = start - 1; i > 0; i--)
treeMin[i] = min(treeMin[i * 2], treeMin[i * 2 + 1]);
}
ll get_max(int l, int r) {
l += start, r += start;
ll maxv = -1000000000;
while (l <= r) {
if (l % 2 != 0) {
maxv = max(maxv, treeMax[l]);
l++;
}
if (r % 2 == 0) {
maxv = max(maxv, treeMax[r]);
r--;
}
r >>= 1; l >>= 1;
}
return maxv;
}
ll get_min(int l, int r) {
l += start, r += start;
ll minv = 100000000;
while (l <= r) {
if (l % 2 != 0) {
minv = min(minv, treeMin[l]);
l++;
}
if (r % 2 == 0) {
minv = min(minv, treeMin[r]);
r--;
}
r >>= 1; l >>= 1;
}
return minv;
}
void update(int x, int v) {
x += start;
treeMax[x] = v;
treeMin[x] = v;
while (x / 2 != 0) {
x /= 2;
treeMax[x] = max(treeMax[2 * x], treeMax[2 * x + 1]);
treeMin[x] = min(treeMin[2 * x], treeMin[2 * x + 1]);
}
}
int main() {
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
cin >> n;
for (int i = 0; i < n; i++) cin >> c[i];
start = 1;
while (start < n) start <<= 1;
for (int i = 0; i < n; i++) {
treeMax[i + start] = c[i];
treeMin[i + start] = c[i];
}
build_tree_max();
build_tree_min();
cin >> q;
while (q--) {
cin >> command;
if (command == 'q') {
cin >> x >> y;
x--, y--;
cout << get_max(x, y) << " " << get_min(x, y) << '\n';
}
else {
cin >> x >> v;
x--;
update(x, v);
}
}
return 0;
}
//http://acm.timus.ru/problem.aspx?space=1&num=1126