forked from nishitpanchal395/projecthactoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSegmentTrees.cpp
More file actions
78 lines (59 loc) · 1.27 KB
/
Copy pathSegmentTrees.cpp
File metadata and controls
78 lines (59 loc) · 1.27 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
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class SegmentTree
{
private:
int size;
vector<int> val;
/* Change this function for updating nodes */
int update(int f, int s)
{
return (f + s);
}
int get(int l, int r, int x, int lx, int rx)
{
if(lx>=r||rx<=l) return 0;
if(lx>=l&&rx<=r)
{
return val[x];
}
int m = (lx + rx)/2;
int a = get(l, r, 2*x + 1, lx, m);
int b = get(l, r, 2*x + 2, m, rx);
return update(a, b);
}
void set(int l, int r, int v, int x, int lx, int rx)
{
if( lx >= r || rx <= l) return;
if( lx >= l && rx <= r)
{
val[x] += v;
return;
}
int m = (lx + rx)/2;
set(l, r, v, 2*x + 1, lx, m);
set(l, r, v, 2*x + 2, m, rx);
val[x] = update(val[2*x + 1], val[2*x + 2]);
}
void init(int n)
{
size = 1;
while(size<=n) size *= 2;
val.assign(2*size, 0LL);
}
public:
SegmentTree(int n)
{
init(n);
}
int get(int l, int r)
{
return get(l, r, 0, 0, size);
}
void set(int l, int v)
{
set(l, l + 1, v, 0, 0, size);
}
};