-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsegment_tree(lazy).cpp
More file actions
48 lines (40 loc) · 1.05 KB
/
segment_tree(lazy).cpp
File metadata and controls
48 lines (40 loc) · 1.05 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
ll arr[10000];
struct info
{
ll prop, sum;
} tree[10000*4];
void init(int node, int b, int e) {
if(b==e) {
tree[node].sum = arr[b];
return;
}
int mid = b + (e-b)/2;
init(node*2, b, mid);
init(node*2+1, mid+1, e);
tree[node].sum = tree[node*2].sum + tree[node*2+1].sum;
}
void update(int node, int b, int e, int i, int j, ll x) {
if(i>e or j<b)
return;
if(b>=i and e<=j){
tree[node].sum += ((e-b+1)*x);
tree[node].prop += x;
return;
}
int mid = b + (e-b)/2;
update(node*2, b, mid, i, j, x);
update(node*2+1, mid+1, e, i, j, x);
tree[node].sum = tree[node*2].sum + tree[node*2+1].sum + (e-b+1)*tree[node].prop;
}
ll query(int node, int b, int e, int i, int j, ll carry = 0){
if(i>e or j<b)
return 0;
if(b>=i and e<=j)
{
return tree[node].sum + carry * (e-b+1);
}
int mid = (b+e) >> 1;
ll p1 = query(node*2, b, mid, i, j, carry+tree[node].prop);
ll p2 = query(node*2+1, mid+1, e, i, j, carry+tree[node].prop);
return p1 + p2;
}