Indexed Tree with template
구현2017. 3. 22. 14:38
#include <cstdio> #include <functional> using namespace std; template <typename _T> class IndexedTree { private: size_t m; _T *A; function<_T(const _T &, const _T &)> F; public: IndexedTree(size_t n, function<_T(const _T &, const _T &)> f) { for (m = 1; m < n; m <<= 1); A = new _T[m << 1]; F = f; } void Update(size_t idx, _T val) { idx |= m; A[idx] = val; while (idx >>= 1) A[idx] = F(A[idx << 1], A[idx << 1 | 1]); } _T Query(size_t L, size_t R) { _T Lval = _T(), Rval = _T(); L |= m; R |= m; while (L <= R) { if (L & 1) Lval = F(Lval, A[L++]); if (!(R & 1)) Rval = F(A[R--], Rval); L >>= 1; R >>= 1; } return F(Lval, Rval); } }; int a[10] = { 6, 2, 3, 8, 4, 5, 1, 9, 7, 10 }; int main() { IndexedTree<int> IT(10, [](auto u, auto v) { return u + v; }); for (int i = 0; i < 10; i++) IT.Update(i, a[i]); printf("%d %d : %d\n", 2, 6, IT.Query(2, 6)); printf("%d %d : %d\n", 3, 8, IT.Query(3, 8)); return 0; }
'구현' 카테고리의 다른 글
Stable Radix Sort (0) | 2016.10.21 |
---|