-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfenwick_tree.cpp
More file actions
58 lines (52 loc) · 1.06 KB
/
fenwick_tree.cpp
File metadata and controls
58 lines (52 loc) · 1.06 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
// add(int indx, int val) : update element at indx with val
// query(int indx) : gives ans of [0, indx]
//0 based indexing
/* 0101
0100
0011
0010
0001
0000
make all trailing 1 , 0 to go down
make first 0 from right 1 to go up
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5 + 4;
const ll n = 1<<31;
int f_tree[N];
int query (int indx) {
int ans = 0;
while (indx >= 0) {
ans += f_tree[indx];
indx = (((indx)&(indx+1))-1);
}
return ans;
}
void add (int indx, int val) {
while (indx <= n) {
f_tree[indx] += val;
indx = (indx|(indx+1));
}
}
//1 based indexing
// val = (FIRST BIT POSITION FROM RIGHT)
// make first 1 from right 0 to go down (indx - val)
// add position number of first 1 from right (int power of 2) to go up (indx + val)
int query (int indx) {
int ans = 0;
while (indx > 0) {
ans += f_tree[indx];
indx -= (((indx)&(-indx)));
}
return ans;
}
void add (int indx, int val) {
while (indx <= n) {
f_tree[indx] += val;
indx += (((indx)&(-indx)));
}
}
// 2D BIT
// For 2D Bit -> create BIT for each id