You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: data_structure/seg_tree_lazy_update.cpp
+22-33Lines changed: 22 additions & 33 deletions
Original file line number
Diff line number
Diff line change
@@ -1,64 +1,53 @@
1
1
vi arr, t, lazy; // arr is numbers to build seg tree with, if its size is 'n' then t and lazy size should be 4 * n (2 * n)
2
2
3
-
voidbuild(int node, int a, int b) // call build(1, 0, n - 1) for n elements
4
-
{
5
-
if(a>b) return;
6
-
if (a==b)
7
-
{
8
-
t[node]=arr[a];
9
-
return;
3
+
voidbuild(int node, int a, int b){ // call build(1, 0, n - 1) for n elements
4
+
if(a > b) return;
5
+
if (a == b){
6
+
t[node] = arr[a]; return;
10
7
}
11
8
12
9
build(node*2, a, (a+b)/2);
13
10
build(node*2+1,(a+b)/2+1,b);
14
11
15
-
t[node]=t[node*2]+t[node*2+1]; // update here in case of change of operation, for example min
12
+
t[node] = t[node * 2] + t[node * 2+1]; // update here in case of change of operation, for example min
16
13
}
17
14
18
-
ull query(int node, int a, int b, int i, int j) // call query(1, 0, n - 1, i, j) to get query of i..j for seg tree of n elements
19
-
{
20
-
if(a>b||a>j||b<i) return0;
21
-
if (lazy[node] !=0 )
22
-
{
15
+
ull query(int node, int a, int b, int i, int j){ // call query(1, 0, n - 1, i, j) to get query of i..j for seg tree of n elements
16
+
if(a>b || a>j || b<i) return0;
17
+
if (lazy[node] !=0 ){
23
18
t[node]+=lazy[node]*(b-a+1); // it is possible to update the tree in ways other that increasing a range.
24
19
// for example it is possible to change all the elements of a range to a number, for example all numbers in range of i..j to 11
25
20
// just underestand the way lazy works and change lazy arr value and interaction between lazy and real tree array, like t[node] = lazy[node] * (b - a + 1)
26
-
if (a!=b)
27
-
{
28
-
lazy[node*2]+=lazy[node];
29
-
lazy[node*2+1]+=lazy[node];
21
+
if (a!=b){
22
+
lazy[node*2] += lazy[node];
23
+
lazy[node*2+1] += lazy[node];
30
24
}
31
25
lazy[node]=0;
32
26
}
33
27
34
-
if (a>=i && b<=j) return t[node];
28
+
if (a >= i && b <= j) return t[node];
35
29
36
30
ull q1=query(node*2, a, (a+b)/2, i, j);
37
31
ull q2=query(node*2+1, (a+b)/2+1, b, i, j);
38
32
39
-
return q1+q2; // update here in case of change of operation, for example min
33
+
return q1 + q2; // update here in case of change of operation, for example min
40
34
}
41
35
42
-
voidupdate(int node, int a, int b, int i, int j, int inc)
43
-
{
44
-
if(a>b) return;
45
-
if (lazy[node]!=0)
46
-
{
47
-
t[node]+=lazy[node]*(b-a+1);
48
-
if (a!=b)
49
-
{
36
+
voidupdate(int node, int a, int b, int i, int j, int inc){
0 commit comments