您的位置:首页 > 其它

树状数组模板(水)

2018-03-10 16:38 246 查看
最终版本: 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 -= 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
99bf
= bit.sum(5);

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: