forked from jahid-hridoy/Code_Templates
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSegment_Tree_Point_Update
More file actions
46 lines (42 loc) · 1.12 KB
/
Segment_Tree_Point_Update
File metadata and controls
46 lines (42 loc) · 1.12 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
const int MAX = 1e5 + 10;
int a[MAX], tree[MAX * 4];
void build(int at, int L, int R) {
if (L == R) {
tree[at] = a[L];
return;
}
int mid = (L + R) / 2;
int left = 2 * at;
int right = 2 * at + 1;
build(left, L, mid);
build( right, mid + 1, R);
tree[at] = tree[left] + tree[right];
}
//call it using build(1, 0, arraySize-1);
void update(int at, int L, int R, int pos, int val) {
if (pos > R || pos < L) return;
if (L == R) {
tree[at] = val;
return;
}
int mid = (L + R) / 2;
int left = at * 2;
int right = at * 2 + 1;
update(left, L, mid, pos, val);
update(right, mid + 1, R, pos, val);
tree[at] = tree[left] + tree[right];
}
//call it using update(1,0,arraySize-1,l,r,val);
int query(int at, int L, int R, int l, int r) {
if (l > R || r < L) return 0;
if (L >= l && R <= r) {
return tree[at];
}
int mid = (L + R) / 2;
int left = at * 2;
int right = at * 2 + 1;
int x = query(left, L, mid, l, r);
int y = query(right, mid + 1, R, l, r);
return x + y;
}
//call it using query(1,0,arraySize-1,l,r);