Repository navigation
Expand file tree
/
Copy pathsegment_tree.sa
More file actions
95 lines (80 loc) · 2.41 KB
/
Copy pathsegment_tree.sa
File metadata and controls
95 lines (80 loc) · 2.41 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Segment Tree Implementation in C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class SegmentTree {
private:
vector<int> tree;
vector<int> arr;
int n;
void build(int start, int end, int node) {
if (start == end) {
tree[node] = arr[start];
} else {
int mid = (start + end) / 2;
build(start, mid, 2 * node + 1);
build(mid + 1, end, 2 * node + 2);
tree[node] = min(tree[2 * node + 1], tree[2 * node + 2]);
}
}
int query(int start, int end, int l, int r, int node) {
if (r < start || end < l) {
return INT_MAX;
}
if (l <= start && end <= r) {
return tree[node];
}
int mid = (start + end) / 2;
return min(query(start, mid, l, r, 2 * node + 1),
query(mid + 1, end, l, r, 2 * node + 2));
}
void update(int start, int end, int idx, int val, int node) {
if (start == end) {
arr[idx] = val;
tree[node] = val;
} else {
int mid = (start + end) / 2;
if (idx <= mid) {
update(start, mid, idx, val, 2 * node + 1);
} else {
update(mid + 1, end, idx, val, 2 * node + 2);
}
tree[node] = min(tree[2 * node + 1], tree[2 * node + 2]);
}
}
public:
SegmentTree(const vector<int>& input) {
arr = input;
n = arr.size();
tree.resize(4 * n);
build(0, n - 1, 0);
}
int query(int l, int r) {
return query(0, n - 1, l, r, 0);
}
void update(int idx, int val) {
update(0, n - 1, idx, val, 0);
}
void display() {
cout << "Segment Tree: ";
for (int i = 0; i < tree.size(); i++) {
if (tree[i] != INT_MAX) {
cout << tree[i] << " ";
}
}
cout << endl;
}
};
int main() {
vector<int> arr = {1, 3, 2, 7, 9, 11};
SegmentTree st(arr);
st.display();
cout << "Minimum in range [1, 4]: " << st.query(1, 4) << endl;
cout << "Minimum in range [0, 5]: " << st.query(0, 5) << endl;
cout << "Minimum in range [2, 3]: " << st.query(2, 3) << endl;
st.update(2, 0);
cout << "After updating index 2 to 0:" << endl;
cout << "Minimum in range [1, 4]: " << st.query(1, 4) << endl;
return 0;
}