本文只给出树状数组的实现代码,解决区间求和问题。
注意vector<int> C;中下标为0的元素是没有用到的。
#include<stdio.h>
#include<vector>
using std::vector;
//#include<vld.h>
class BinTree {
private:
int size = -1;
vector<int> C;
public:
BinTree(int size) {
this->size = size;
C.assign(size, 0);
}//BinTree
int lowBit(int x) {
return x&(-x);
}//lowBit
void update(int x, const int &addVal) {
while (x <= size - 1) {
C[x] += addVal;
x += lowBit(x);
}//while
return;
}//update
int getSum(int x) {
int sum(0);
while (x > 0) {
sum += C[x];
x -= lowBit(x);
}//while
return sum;
}//getSum
void printC() {
for (auto iter = C.begin() + 1; iter != C.end(); ++iter) {
printf("%d%c", *iter, (iter == --C.end() ? '\n' : ' '));
}//for iter
return;
}//printC
};
int main() {
BinTree tree(9);
tree.update(5, 1);
tree.update(2, 1);
tree.update(3, 10);
printf("getSum(%d)=%d\n", 6, tree.getSum(6));
printf("getSum(%d)=%d\n", 8, tree.getSum(8));
tree.printC();
return 0;
}//main