-
Notifications
You must be signed in to change notification settings - Fork 0
/
segment_tree.cpp
78 lines (63 loc) · 1.71 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
// Author: Piotr Borowski
// Code prepared for my lecture on segment trees
//
// Segment tree with lazy propagation.
// Allows to:
// - add value v on interval [a, b] in O(logn)
// - get maximum on interval [a, b] in O(logn)
//
#include <bits/stdc++.h>
using namespace std;
const int R = 1 << 18;
int tree[2 * R], lazy[2 * R];
// propagation
void update(int id, int value) {
tree[id] += value;
lazy[id] += value;
}
void push(int id) {
int left = 2 * id;
int right = 2 * id + 1;
update(left, lazy[id]);
update(right, lazy[id]);
lazy[id] = 0;
}
// returns maximum value on interval [begin, end]
int maxi(int begin, int end, int id = 1, int l = 1, int r = R) {
if (begin > r) return -1e9;
if (end < l) return -1e9;
if (begin <= l && end >= r) {
return tree[id];
}
push(id);
int left = 2 * id;
int right = 2 * id + 1;
int middle = (l + r) / 2;
return max(maxi(begin, end, left, l, middle),
maxi(begin, end, right, middle + 1, r));
}
// add value to every position on interval [begin, end]
void add(int begin, int end, int value, int id = 1, int l = 1, int r = R) {
if (begin > r) return;
if (end < l) return;
if (begin <= l && end >= r) {
update(id, value);
return;
}
push(id);
int left = 2 * id;
int right = 2 * id + 1;
int middle = (l + r) / 2;
add(begin, end, value, left, l, middle);
add(begin, end, value, right, middle + 1, r);
tree[id] = max(tree[left], tree[right]);
}
int main() {
add(1, 3, 5);
add(2, 4, 7);
add(3, 5, -2);
cout << maxi(2, 4) << endl;
add(4, 5, 8);
cout << maxi(2, 4) << endl;
return 0;
}