本文分享一下树状数组的实现,原理后面再说
#include <memory>
#include <vector>
template <typename T, typename Factor, typename Allocator = std::allocator<T>>
class BinaryIndexedTree {
public:
BinaryIndexedTree(std::size_t size, const Factor& factor, const Allocator& allocator = Allocator())
: size(size), tree(size + 1, T(), allocator), factor(factor) {}
void update(std::size_t index, const T& value) {
index++; // Convert 0-based index to 1-based index
while (index <= size) {
tree[index] = factor(tree[index], value);
index += lowbit(index); // Move to next node
}
}
T query(std::size_t index) const {
index++; // Convert 0-based index to 1-based index
T result = T();
while (index > 0) {
result = factor(result, tree[index]);
index -= lowbit(index); // Move to parent node
}
return result;
}
T query(std::size_t first, std::size_t last) const {
if (first > last || last >= size) {
throw std::out_of_range("Invalid range");
}
return query(last) - query(first - 1);
}
private:
std::size_t size;
std::vector<T, Allocator> tree;
Factor factor;
std::size_t lowbit(std::size_t n) const {
return n & -n;
}
};