Skip to content

Commit dbef70e

Browse files
author
ishan.gupta
committed
lazy propagation in segment tree implementation
1 parent 27fd000 commit dbef70e

File tree

1 file changed

+120
-0
lines changed

1 file changed

+120
-0
lines changed

segment-lazy-propagation.cpp

+120
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
using namespace std;
2+
#include <iostream>
3+
#include <bits/stdc++.h>
4+
5+
class ST{
6+
public:
7+
vector<int> seg;
8+
vector<int> lazy;
9+
ST(int n){
10+
seg.resize(4 * n);
11+
lazy.resize(4 * n);
12+
}
13+
14+
void build(int indx, int low, int high, int arr[]){
15+
if(low==high){
16+
seg[indx] = arr[low];
17+
return;
18+
}
19+
int mid = (low + high) >> 1;
20+
build(2 * indx + 1, low, mid, arr);
21+
build(2 * indx + 2, mid + 1, high, arr);
22+
seg[indx] = seg[2 * indx + 1] + seg[2 * indx + 2];
23+
}
24+
25+
void update(int indx, int l, int r,int low, int high, int val){
26+
// update previous pending nodes if any.
27+
if(lazy[indx]!=0){
28+
seg[indx] += (high - low + 1) * lazy[indx];
29+
if(low!=high){
30+
lazy[2 * indx + 1] = lazy[indx];
31+
lazy[2 * indx + 2] = lazy[indx];
32+
}
33+
lazy[indx] = 0;
34+
}
35+
// complete overlap
36+
if(low>=l && high<=r){
37+
seg[indx] += (high-low+1)*val;
38+
if(high!=low){
39+
lazy[2 * indx + 1] += val;
40+
lazy[2 * indx + 2] += val;
41+
}
42+
return;
43+
}
44+
45+
//no overlap
46+
if(high<l || r<low){
47+
return;
48+
}
49+
50+
// partial overlap
51+
int mid = (low + high) >> 1;
52+
update(2 * indx + 1, l, r, low, mid, val);
53+
update(2*indx+2,l,r,mid+1,high,val);
54+
seg[indx] = seg[2 * indx + 1] + seg[2 * indx + 2];
55+
}
56+
57+
int query(int indx, int l, int r, int low, int high){
58+
if(lazy[indx]!=0){
59+
seg[indx] += (high - low + 1) * lazy[indx];
60+
if(low!=high){
61+
lazy[2 * indx + 1] = lazy[indx];
62+
lazy[2 * indx + 2] = lazy[indx];
63+
}
64+
lazy[indx] = 0;
65+
}
66+
67+
//complete overlap
68+
if(low>=l && high<=r){
69+
70+
return seg[indx];
71+
}
72+
73+
//no overlap
74+
if(high<l || r<low){
75+
return 0;
76+
}
77+
78+
// partial overlap
79+
int mid = (low + high) >> 1;
80+
int left = query(2 * indx + 1, l, r, low, mid);
81+
int right = query(2*indx+2,l,r,mid+1,high);
82+
return left + right;
83+
}
84+
};
85+
86+
int main(){
87+
#ifndef ONLINE_JUDGE
88+
freopen("error.txt", "w", stderr);
89+
freopen("input.txt", "r", stdin);
90+
freopen("output_.txt", "w", stdout);
91+
#endif
92+
93+
cin.tie(NULL);
94+
cout.tie(NULL);
95+
ios_base::sync_with_stdio(false);
96+
int n, arr[n];
97+
cin >> n;
98+
for (int i = 0; i < n; i++)
99+
{
100+
cin >> arr[i];
101+
}
102+
int q;
103+
cin >> q;
104+
ST st(n);
105+
st.build(0, 0, n - 1, arr);
106+
while (q--)
107+
{
108+
int typ;
109+
int l, r, val;
110+
cin >> typ;
111+
if(typ==1) {
112+
cin >> l >> r >> val;
113+
st.update(0, l, r, 0, n - 1, val);
114+
}
115+
else {
116+
cin >> l >> r;
117+
cout<<st.query(0,l,r,0,n-1);
118+
}
119+
}
120+
}

0 commit comments

Comments
 (0)