AlgoPlus v0.1.0
Loading...
Searching...
No Matches
fenwick_tree.h
1#ifndef FENWICK_TREE_H
2#define FENWICK_TREE_H
3
4#ifdef __cplusplus
5#include <iostream>
6#include <vector>
7#endif
8
12template <typename T> struct fenwick_tree {
13 std::vector<T> tree;
14 int n;
15
20 inline explicit fenwick_tree(const std::vector<T>& v) noexcept : n(int(v.size())) {
21 tree = std::vector<T>(n, 0);
22 for (int i = 0; i < n; i++) {
23 this->update(i, v[i]);
24 }
25 }
26
32 inline T sum(int k) {
33 T sum = 0;
34 for (; k >= 0; k = (k & (k + 1)) - 1) {
35 sum += tree[k];
36 }
37 return sum;
38 }
39
46 inline T sum(int a, int b) { return sum(b) - sum(a - 1); }
47
53 inline void update(int k, int x) {
54 for (; k < n; k = k | (k + 1)) {
55 tree[k] += x;
56 }
57 }
58};
59
60#endif
T sum(int k)
sum query function
Definition fenwick_tree.h:32
T sum(int a, int b)
sum query function(from index a to b)
Definition fenwick_tree.h:46
void update(int k, int x)
update query function
Definition fenwick_tree.h:53
fenwick_tree(const std::vector< T > &v) noexcept
default constructor of fenwick tree class
Definition fenwick_tree.h:20