-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSegmentTreeLazy.cc
More file actions
84 lines (77 loc) · 1.83 KB
/
SegmentTreeLazy.cc
File metadata and controls
84 lines (77 loc) · 1.83 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
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
#include <bits/stdc++.h>
using namespace std;
/* Segment Tree/ Interval Tree
* Stores information in a Heap
* Modification, lookup in O(logn)
* Provides Tools to update intervals
* All intervals are [ , )
*/
struct LazySegmentTree{
vector<int> Seg;
vector<int> lazy;
int n;
void build(vector<int>& v, int m){
n = m;
Seg = lazy = vector<int> (4*n,0);
build(v, 1, 0, n);
}
void build( vector<int>& v, int id,int left, int right){
if(left + 1 >= right){
Seg[id] = v[left];
return;
}
int mid = (left + right)/2;
build(v, id * 2, left, mid);
build(v, id * 2 + 1, mid, right);
Seg[id] = Seg[id*2] + Seg[id*2 + 1];
}
int find(int x, int y){
return find(x, y, 1, 0, n);
}
int find(int x, int y, int id, int left, int right){
if (lazy[id] != 0) {
Seg[id] += (right-left)*lazy[id];
if (left + 1 < right) {
lazy[2*id] += lazy[id]; // Lazy propagation
lazy[2*id + 1] += lazy[id];
}
lazy[id] = 0;
}
if(left >= y or right <= x){
return 0;
}
if(left >= x and right <= y){
return Seg[id];
}
int mid = (left + right)/2;
return find(x, y, 2*id, left, mid) + find(x, y, 2*id + 1, mid, right);
}
int updateinterval(int p, int x, int y){
updateinterval(p, 1, x, y, 0, n);
}
void updateinterval (int p, int id, int x, int y, int left, int right) {
if (lazy[id] != 0) {
Seg[id] += (right-left)*lazy[id];
if (x + 1 < y) {
lazy[2*id] += lazy[id];
lazy[2*id + 1] += lazy[id];
}
lazy[id] = 0;
}
if(left >= y or right <= x){
return;
}
if(left >= x and right <= y){
Seg[id] += (right-left)*p;
if (left + 1 < right) {
lazy[2*id] += p;
lazy[2*id + 1] += p;
}
return;
}
int mid = (left + right)/2;
updateinterval (p, 2*id, x, y, left, mid);
updateinterval (p, 2*id + 1, x, y, mid, right);
Seg[id] = Seg[2*id] + Seg[2*id + 1];
}
};