MCPcopy Create free account
hub / github.com/acm-clan/algorithm-stone / BinaryIndexedTree

Class BinaryIndexedTree

templates/binary-index-tree.cpp:6–55  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4#include <string.h>
5
6class BinaryIndexedTree {
7public:
8 int n;
9 std::vector<int> tree;
10
11 int Lowbit(int x)
12 {
13 return x & -x;
14 }
15
16 int Query(int x)
17 {
18 int ans = 0;
19 for (int i = x; i > 0; i -= Lowbit(i)) {
20 ans += tree[i];
21 }
22 return ans;
23 }
24
25 void Add(int x, int u)
26 {
27 for (int i = x; i <= n; i += Lowbit(i)) {
28 tree[i] += u;
29 }
30 }
31
32 std::vector<int> vec;
33
34 BinaryIndexedTree(std::vector<int>& nums)
35 {
36 n = nums.size();
37 vec.assign(nums.begin(), nums.end());
38 // tree = new int[n + 1]();
39 tree.resize(n+1);
40 for (int i = 0; i < n; ++i) {
41 Add(i + 1, vec[i]);
42 }
43 }
44
45 void UpdateValue(int index, int val)
46 {
47 Add(index + 1, val - vec[index]);
48 vec[index] = val;
49 }
50
51 int SumRange(int left, int right)
52 {
53 return Query(right + 1) - Query(left);
54 }
55};
56
57void test_perf(){
58 int n = 100000;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected