树状数组,区间求和

本文只给出树状数组的实现代码,解决区间求和问题。
注意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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值