Skip to content

Commit 2eda475

Browse files
authored
Create Lazy Propagation
Lazy Propagation using Binary Indexed Tree.
1 parent a6a138b commit 2eda475

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

Lazy Propagation

+104
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
#define intmax 1000000
5+
#define endl "\n"
6+
#define add(a,b) a+b
7+
8+
typedef long long ll ;
9+
10+
ll tree[intmax];
11+
ll lazy[intmax];
12+
13+
void update(ll node , ll start , ll end, ll l ,ll r, ll value)
14+
{
15+
16+
17+
if(lazy[node]!= 0)
18+
{
19+
tree[node]+= (end-start +1)*lazy[node];
20+
if(start != end)
21+
{
22+
lazy[node*2]+= lazy[node];
23+
lazy[node*2+1]+= lazy[node];
24+
}
25+
lazy[node]=0;
26+
}
27+
if(start>end || r <start || l>end)
28+
return;
29+
if(l<= start && end<= r)
30+
{
31+
tree[node]+=(end-start +1) *value;
32+
if(start != end)
33+
{
34+
lazy[node*2]+=value;
35+
lazy[node*2+1]+= value;
36+
}
37+
return;
38+
}
39+
ll mid = (start+end)/2;
40+
update(node*2,start,mid,l,r,value);
41+
update(node*2+1,mid+1,end,l, r,value);
42+
tree[node]=tree[node*2]+tree[node*2+1];
43+
}
44+
45+
ll query (ll node , ll start, ll end , ll l, ll r)
46+
{
47+
if(r<start || l> end ||start >end)
48+
{
49+
return 0;
50+
}
51+
if(lazy[node]!= 0)
52+
{
53+
tree[node]+=(end-start+1)*lazy[node];
54+
if(start != end)
55+
{
56+
lazy[node*2]+= lazy[node];
57+
lazy[node*2+1]+=lazy[node];
58+
}
59+
lazy[node]= 0;
60+
}
61+
if(l<= start && end <= r)
62+
{
63+
return tree[node];
64+
}
65+
ll mid = (start+end)/2;
66+
ll p1 = query(2*node, start ,mid , l, r);
67+
ll p2 = query(2*node +1, mid +1 , end, l , r);
68+
return (add(p1,p2));
69+
}
70+
71+
int main()
72+
{
73+
ios_base::sync_with_stdio(false);
74+
cin.tie(NULL);
75+
cout.tie(NULL);
76+
ll t;
77+
cin >> t;
78+
79+
while(t--){
80+
memset(tree, 0, sizeof(tree));
81+
memset(lazy, 0, sizeof(lazy));
82+
ll n , q;
83+
cin >> n>> q;
84+
while(q--)
85+
{
86+
87+
int ch ;
88+
cin >> ch;
89+
if(ch == 1)
90+
{
91+
ll l ,r;
92+
cin >> l >>r;
93+
cout<<query(1,0,n-1,l-1,r-1)<<endl;
94+
}
95+
else
96+
{
97+
ll l , r, value;
98+
cin >> l>>r>>value;
99+
update(1,0,n-1,l-1, r-1,value);
100+
}
101+
}
102+
}
103+
return 0;
104+
}

0 commit comments

Comments
 (0)