树状数组模板(水)
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群;
线段树要求 幺半群;
……………………………………………………………………………………………………..
随手写一下这个玩意。。。。
感觉很水…..
树状数组比线段树简单,但是由于是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; }
相关文章推荐
- 树状数组模板
- HDU 1556 Color the ball 树状数组-区间更新-模板
- See you~ (hdu1892 二维树状数组模板)
- poj2299Ultra-QuickSort【树状数组求逆序数、离散化】、【归并排序模板】
- 树状数组模板
- 树状数组 (模板)
- 树状数组求逆序数的模板(离散化处理)
- 二维树状数组模板
- 洛谷P3374 【模板】树状数组 1(CDQ分治)
- 树状数组模板
- 洛谷 3380 【模板】二逼平衡树(树状数组套权值线段树)
- 树状数组模板
- poj 3486 A Simple Problem with Integers(树状数组第三种模板改段求段)
- 【二维树状数组--模板】poj 2155 Matrix、poj 1195 Mobile phones
- 【二维树状数组】【模板】poj1195Mobile phones
- 树状数组模板程序
- 树状数组求逆序数(模板)
- 【模板】逆序对(树状数组)
- 【模板】树状数组求逆序对
- 【模板】树状数组