Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- struct node {
- int left;
- int right;
- int max;
- node * child_left;
- node * child_right;
- };
- node * build(int left, int right, std::vector<int> & a){
- node * res = new node;
- res->left = left;
- res->right = right;
- if (left == right){
- res->child_left = nullptr;
- res->child_right = nullptr;
- res->max = a[left];
- } else {
- int mid = (left + right) / 2;
- res->child_left = build(left, mid, a);
- res->child_right = build(mid + 1, right, a);
- res->max = std::max(res->child_left->max, res->child_right->max);
- }
- return res;
- }
- int query(node * root, int left, int right){
- if (right < root->left || left > root->right){
- return -1;
- }
- if (left <= root->left && root->right <= right){
- return root->max;
- }
- int ans1 = query(root->child_left, left, right);
- int ans2 = query(root->child_right, left, right);
- return std::max(ans1, ans2);
- }
- void update(node * root, int i, int val){
- if (i < root->left || i > root->right){
- return;
- }
- if (root->left == root->right){
- root->max = val;
- return;
- }
- update(root->child_left, i, val);
- update(root->child_right, i, val);
- root->max = std::max(root->child_right->max, root->child_left->max);
- }
- int main() {
- int n = 100;
- std::vector<int> a(n + 1);
- for (int i = 1; i < n + 1; ++i){
- a[i] = i % 10;
- }
- node * root = build(1, n, a);
- std::cout<<query(root, 23, 35)<<std::endl;
- update(root, 29, 5);
- std::cout<<query(root, 23, 35)<<std::endl;
- update(root, 31, 100);
- std::cout<<query(root, 23, 35)<<std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement