树状数组模板(水)

树状数组详解与应用

最终版本: 2018-3-12
树状数组比线段树简单,但是由于是Abel群,所以可以做一些优化工作,
最后写起来比线段树多一些吧。
树状数组模板库:
https://github.com/rsy56640/rsy_little_lib/tree/master/library_for_algorithm/Binary_Indexed_Tree
线段树模板库:
https://github.com/rsy56640/rsy_little_lib/tree/master/library_for_algorithm/SegmentTree

树状数组要求 Abel群;
线段树要求 幺半群;

随手写一下这个玩意。。。。
感觉很水…

#include <iostream> 
#include <vector>
using namespace std;

class Binary_Indexed_Tree
{

public:

	//ctor
	Binary_Indexed_Tree(const vector<int>& Vec)
	{
		int size = Vec.size();
		_Vec.resize(size);
		for (int i = 0; i < size; ++i)
		{
			_Vec[i] = 0;
			int _low_bit = low_bit(i + 1);
			for (int j = i - _low_bit + 1; j <= i; ++j)
				_Vec[i] += Vec[j];
		}

	}


	//sum the previous n num
	//S_(n-1)= A0+...+A_(n-1)
	//S_(n-1)=C_(n-1) + S_(n - 1 - low_bit(n));
	const int sum(int n) const
	{
		int result = 0;
		n--;
		while (n >= 0)
		{
			result += _Vec[n];
			n -= low_bit(n + 1);
		}
		return result;
	}


	//modify the pos as val
	//modify C_n,
	//then n += low_bit(n+1);
	void modify_val(int pos, int val)
	{
		int size = _Vec.size();
		int diff = sum(pos + 1) - sum(pos) - val;
		while (pos < size)
		{
			_Vec[pos] -= diff;
			pos += low_bit(pos + 1);
		}
	}



	//add the pos with diff
	void modify_diff(int pos, int diff)
	{
		int size = _Vec.size();
		while (pos < size)
		{
			_Vec[pos] += diff;
			pos += low_bit(pos + 1);
		}
	}


private:

	vector<int> _Vec;

	const int low_bit(int x) const noexcept
	{
		return x & (-x);
	}

};


int main()
{

	vector<int> v = { 1,2,7,5,8 };

	Binary_Indexed_Tree bit(v);

	int x = bit.sum(3);
	bit.modify_val(2, 1);
	int y = bit.sum(4);
	bit.modify_diff(3, 14);
	int z = bit.sum(5);


	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值