-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsegtree.cpp
66 lines (59 loc) · 1.13 KB
/
segtree.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
/* Harsh Pathak - pogba */
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define fastio() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
/*
segment tree api inspired from https://codeforces.com/blog/entry/18051
*/
const int N = 1e5; //N is >= 2n-1
int t[N]; //tree
int n; //num elements
void take_input();
void build_tree();
void print_tree();
void modify_tree(int, int);
int query_tree(int, int);
void print_tree(){
cout << "elements of tree\n";
for (int i = 0; i < n; ++i)
{
cout << t[i + n] << " ";
}
cout << endl;
}
void take_input(){
for (int i = 0; i < n; ++i)
{
cin >> t[n + i];
}
build_tree();
}
void build_tree(){
for(int i = n-1; i >= 1; i--){
t[i] = t[i << 1] + t[i << 1 | 1];
}
}
void modify_tree(int idx, int v){ //0 indexing
t[idx += n] = v;
int i = idx;
while(i > 1){
t[i >> 1] = t[i] + t[i ^ 1];
i >>= 1;
}
}
int query_tree(int l, int r){ //query on [l,r), 0 indexing
l += n;
r += n;
int res = 0;
while(l < r){
if(l & 1) res += t[l++];
if(r & 1) res += t[--r];
l >>= 1;
r >>= 1;
}
return res;
}