Skip to content

Instantly share code, notes, and snippets.

@robivirt
Created February 19, 2019 13:49
Show Gist options
  • Select an option

  • Save robivirt/ab35ed4d00ab1e6cfc15a45c64d5e466 to your computer and use it in GitHub Desktop.

Select an option

Save robivirt/ab35ed4d00ab1e6cfc15a45c64d5e466 to your computer and use it in GitHub Desktop.
#include<iostream>
#include<vector>
using namespace std;
const int INF = 2e9;
struct node
{
int left, right, add;
int max;
node * child_left, * child_right;
};
node * build(int left, int right, vector<int> & a){
if(left > right)
return NULL;
node * res = new node;
res->left = left;
res->right = right;
res->add = 0;
if(left == right)
{
res->child_left = NULL;
res->child_right = NULL;
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 = max(res->child_left->max, res->child_right->max);
}
return res;
}
int query(int left, int right, node * root)
{
if(right < root->left || left > root->right)
return -INF;
if(root->left>=left && root->right <= right)
return root->max + root->add;
return max(query(left, right, root->child_left),
query(left, right, root->child_right))+
root->add;
}
void update(node * root, int left, int right, int delta)
{
if(right < root->left || left > root->right)
return;
if(root->left == root->right){
root->add += delta;
return;}
update(root->child_left, left, right, delta);
update(root->child_right, left, right, delta);
root->max = max(root->child_left->max + root->child_left->add, root->child_right->max + root->child_right->add);
}
typedef node * pnode;
int main(){
vector<int> a = {2, 8, 1, 5, 2, 4};
pnode root = build(0, a.size() - 1, a);
cout << root->max;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment