-
Notifications
You must be signed in to change notification settings - Fork 0
/
segment_tree.cpp
66 lines (61 loc) · 1.32 KB
/
segment_tree.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
#include <bits/stdc++.h>
using namespace std;
#define mp make_pair
#define pb push_back
#define mod 1000000007
#define int long long int
#define N 100005
void fast(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
}
int tree[4*N];
int a[N];
void build(int node, int start, int end)
{
if(start == end){
tree[node] = a[start];
}
else{
int mid = (start + end) / 2;
build(2*node, start, mid);
build(2*node+1, mid+1, end);
tree[node] = tree[2*node] + tree[2*node+1];
}
}
void update(int node, int start, int end, int idx, int val)
{
if(start == end){
a[idx] += val;
tree[node] += val;
}
else{
int mid = (start + end) / 2;
if(start <= idx and idx <= mid){
update(2*node, start, mid, idx, val);
}
else{
update(2*node+1, mid+1, end, idx, val);
}
tree[node] = tree[2*node] + tree[2*node+1];
}
}
int query(int node, int start, int end, int l, int r)
{
if(r < start or end < l){
return 0;
}
if(l <= start and end <= r){
return tree[node];
}
int mid = (start + end) / 2;
int p1 = query(2*node, start, mid, l, r);
int p2 = query(2*node+1, mid+1, end, l, r);
return (p1 + p2);
}
main()
{
fast();
}
// 29 september 2019 div2 A