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
|
struct Node{
int start, end, max;
Node *left, *right;
Node (int start, int end, int max) : start(start), end(end), max(max), left(nullptr), right(nullptr) {};
};
Node* build(vector<int> &A, int start, int end) {
if (start > end) return nullptr;
auto root = new Node(start, end, A[start]);
if (start == end) return root;
int mid = start + ((end - start) >> 1);
root->left = build(A, start, mid);
root->right = build(A, mid + 1, end);
root->max = max(root->left->max, root->right->max);
return root;
}
int query(Node *root, int start, int end) {
if (start == root->start && end == root->end) return root->max;
int mid = root->start + ((root->end - root->start) >> 1);
if (end <= mid) return query(root->left, start, end);
else if (start > mid) return query(root->right, start, end);
return max(query(root->left, start, mid), query(root->right, mid + 1, end));
}
void update(Node *root, int index, int val) {
if (root->start == root->end && root->start == index) {
root->max = val;
return ;
}
int mid = root->start + ((root->end - root->start) >> 1);
if (index <= mid) update(root->left, index, val);
else update(root->right, index, val);
root->max = max(root->left->max, root->right->max);
}
|