-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfenwicktree.h
More file actions
71 lines (63 loc) · 1.33 KB
/
fenwicktree.h
File metadata and controls
71 lines (63 loc) · 1.33 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
#include <iostream>
template <typename T>
class BITTree
{
private:
T* tree;
int size;
public:
BITTree(T array[], int size)
{
this->size=size+1;
this->tree=new T[this->size];
for(int i=0;i<this->size;i++)
tree[i]=0;
for(int i=0;i<this->size-1;i++)
update(i,array[i]);
}
~BITTree()
{
delete[] tree;
}
private:
int getParent(int index)
{
return index-(index&(-index));
}
int getNext(int index)
{
return index+(index&(-index));
}
public:
T prefix_sum(int index)
{
if(index<0||index>=this->size-1)
{
std::cout<<"Index out of range"<<std::endl;
return T{};
}
index++;
T sum=T{};
while(index>0)
{
sum+=tree[index];
index=getParent(index);
}
return sum;
}
bool update(int index, T val)
{
if(index<0||index>=this->size-1)
{
std::cout<<"Index out of range"<<std::endl;
return false;
}
index++;
while(index<this->size)
{
tree[index]+=val;
index=getNext(index);
}
return true;
}
};