-
Notifications
You must be signed in to change notification settings - Fork 0
/
segmentTreeWithLazyPropagation.cpp
103 lines (82 loc) · 2.45 KB
/
segmentTreeWithLazyPropagation.cpp
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
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAX = 100005;
struct data {
LL sum, lazyVal;
bool lazyFlag;
} tree[MAX*4];
int n;
void buildTree(int node, int beg, int endd) {
if(beg == endd) {
tree[node].sum = tree[beg].sum;
return;
}
int left = node*2;
int right = node*2+1;
int mid = (beg+endd)/2;
buildTree(left, beg, mid);
buildTree(right, mid+1, endd);
tree[node].sum = tree[left].sum+tree[right].sum;
}
void pushDown(int node, int left, int right, int beg, int mid, int endd) {
tree[left].sum += tree[node].lazyVal*(mid-beg+1);
tree[right].sum += tree[node].lazyVal*(endd-mid);
tree[left].lazyVal += tree[node].lazyVal;
tree[right].lazyVal += tree[node].lazyVal;
tree[left].lazyFlag = true;
tree[right].lazyFlag = true;
tree[node].lazyVal = 0;
tree[node].lazyFlag = false;
}
void update(int node, int beg, int endd, int x, int y, LL val) {
if(x > y) return;
if(beg == x && endd == y) {
tree[node].sum += val*(endd-beg+1);
tree[node].lazyVal += val;
tree[node].lazyFlag = true;
return;
}
int left = node*2;
int right = node*2+1;
int mid = (beg+endd)/2;
if(tree[node].lazyFlag) pushDown(node, left, right, beg, mid, endd);
update(left, beg, mid, x, min(y, mid), val);
update(right, mid+1, endd, max(x, mid+1), y, val);
tree[node].sum = tree[left].sum + tree[right].sum;
}
LL query(int node, int beg, int endd, int x, int y) {
if(x > y) return 0ll;
if(beg == x && endd == y) return tree[node].sum;
int left = node*2;
int right = node*2+1;
int mid = (beg+endd)/2;
if(tree[node].lazyFlag) pushDown(node, left, right, beg, mid, endd);
LL l = query(left, beg, mid, x, min(y, mid));
LL r = query(right, mid+1, endd, max(x, mid+1), y);
return l+r;
}
int main() {
int test, kase=1, q, com, x, y;
LL val;
scanf("%d", &test);
while(test--) {
printf("Case %d:\n", kase++);
scanf("%d %d", &n, &q);
memset(tree, 0, sizeof(tree));
while(q--) {
scanf("%d", &com);
if(com == 0) {
scanf("%d %d %lld", &x, &y, &val);
x++, y++;
update(1, 1, n, x, y, val);
}
else {
scanf("%d %d", &x, &y);
x++, y++;
printf("%lld\n", query(1, 1, n, x, y));
}
}
}
return 0;
}