Skip to content

Commit

Permalink
Create 370.Range-Addition.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Jul 25, 2018
1 parent 19d754c commit 7857f08
Showing 1 changed file with 76 additions and 0 deletions.
76 changes: 76 additions & 0 deletions Segment_Tree/370.Range-Addition/370.Range-Addition.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
class Solution {
class SegNode
{
public:

int begin, end, status;
SegNode* left;
SegNode* right;
SegNode(int a, int b, int s)
{
begin = a;
end = b;
status = s;
left = NULL;
right = NULL;
}

void remove(SegNode* & node)
{
if (node==NULL) return;
remove(node->left);
remove(node->right);
delete node;
node=NULL;
}

int setStatus(int a, int b, int s)
{
if (b<=begin || a>=end)
{
return status;
}
if (a<=begin && end<=b && left==NULL)
{
status += s;
return status;
}
int mid = (end-begin)/2+begin;
if (left==NULL)
{
left = new SegNode(begin,mid,status);
right = new SegNode(mid,end,status);
}
int leftStatus = left->setStatus(a,b,s);
int rightStatus = right->setStatus(a,b,s);
return max(leftStatus,rightStatus);
}
};

public:
vector<int> getModifiedArray(int length, vector<vector<int>>& updates)
{
SegNode* root = new SegNode(0,length,0);

for (int i=0; i<updates.size(); i++)
root->setStatus(updates[i][0],updates[i][1]+1,updates[i][2]);

vector<int>results(length);
DFS(root,results);
return results;
}

void DFS(SegNode* node, vector<int>& results)
{
if (node==NULL)
return;
if (node->left!=NULL)
{
DFS(node->left,results);
DFS(node->right,results);
return;
}
for (int i=node->begin; i<node->end; i++)
results[i] = node->status;
}
};

0 comments on commit 7857f08

Please sign in to comment.