-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlazyPropagationIntro.cpp
More file actions
90 lines (64 loc) · 1.82 KB
/
lazyPropagationIntro.cpp
File metadata and controls
90 lines (64 loc) · 1.82 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
#include<bits/stdc++.h>
using namespace std;
void buildTree(int ar[], int *tree, int start, int end, int treeIndex) {
if(start == end) {
tree[treeIndex] = ar[start];
return;
}
int mid = (start + end )/2;
buildTree(ar, tree, start, mid, 2*treeIndex);
buildTree(ar, tree, mid+1, end, 2*treeIndex+1);
tree[treeIndex] = min(tree[2*treeIndex], tree[2*treeIndex + 1]);
}
void updateSegmentTreeLazy(int *tree, int *lazy, int low, int high, int curPos, int start, int end, int increment) {
if (low > high) {
return;
}
if(lazy[curPos] != 0) {
tree[curPos] += lazy[curPos];
// If it is not a leaf node, we need to update its children
if(low != high) {
lazy[2*curPos] += lazy[curPos];
lazy[2*curPos + 1] += lazy[curPos];
}
lazy[curPos] = 0;
}
// completely outside the given range
if(start > high || end < low) {
return ;
}
// complete overlap
if(low >= start && high <= end) {
tree[curPos] += increment;
// if not a leaf node, update it in the lazy tree
if(low != high) {
lazy[2*curPos] += increment;
lazy[2*curPos + 1] += increment;
}
return ;
}
// partial overlap
int mid = (low + high)/2;
updateSegmentTreeLazy(tree, lazy, low, mid, 2*curPos, start, end, increment);
updateSegmentTreeLazy(tree, lazy, mid+1, high, 2*curPos + 1, start, end, increment);
tree[curPos] = min(tree[2*curPos], tree[2*curPos + 1]);
}
int main() {
int ar[] = { 1, 3, -2, 4 };
int *tree = new int[12];
buildTree(ar, tree, 0, 3, 1);
int *lazy = new int[12]();
updateSegmentTreeLazy(tree, lazy, 0, 3, 1, 0, 3, 3);
updateSegmentTreeLazy(tree, lazy, 0, 3, 1, 0, 1, 2);
cout << "Segment Tree :" << endl;
for(int i = 1; i < 12; i++) {
cout << tree[i] << endl;
}
cout << "Lazy tree : " << endl;
for(int i = 1; i < 12; i++) {
cout << lazy[i] << endl;
}
delete [] tree;
delete [] lazy;
return 0;
}