Binary Indexed Tree

Turmoil

2019-08-08 18:54:50

Personal

Binary Indexed Tree

header file

#ifndef _BINARY_INDEXED_TREE_
#define _BINARY_INDEXED_TREE_

#include <cstdio>
#include <cstring>

using namespace std;

const int Binary_Indexed_Tree_SIZE = 10000;
const int Binary_Indexed_Tree_2D_SIZE = 100;

//1 dimensional binary indexed tree
template<class _T>
class Binary_Indexed_Tree
{
private:
    _T node[Binary_Indexed_Tree_SIZE];
    int size;

    int lowbit(int x);
public:
    Binary_Indexed_Tree();
    void reserve(int sz);
    void add(int k, _T addend);
    _T query(int k);    //sum of interval (0, k]
};
//2 dimensional binaryindexed tree
template<class _T>
class Binary_Indexed_Tree_2D
{
private:
    _T node[Binary_Indexed_Tree_2D_SIZE][Binary_Indexed_Tree_2D_SIZE];
    int row, column;

    int lowbit(int x);
public:
    Binary_Indexed_Tree();
    void reserve(int r, int c);
    void add(int x, int y, _T addend);
    _T query(int x, int y); //sum of interval (0, k]
};

//declare 1 dimensional tree
template<class _T>
int Binary_Indexed_Tree<_T>::lowbit(int x)
{
    return x & (-x);
}
template<class _T>
Binary_Indexed_Tree<_T>::Binary_Indexed_Tree()
{
    memset(this -> node, 0, sizeof(this -> node));
    this -> size = 0;
}
template<class _T>
void Binary_Indexed_Tree<_T>::reserve(int sz)
{
    this -> size = sz;
}
template<class _T>
void Binary_Indexed_Tree<_T>::add(int x, _T addend)
{
    for (int i = x; i <= this -> size; i += lowbit(i))
        this -> node[i] += addend;
}
template<class _T>
_T Binary_Indexed_Tree<_T>::query(int x)
{
    _T rv = 0;

    for (int i = x; i <= this -> size; i += lowbit(i))
        rv += this -> node[i];

    return rv;
}
//declare 2 dimensional tree
template<class _T>
int Binary_Indexed_Tree_2D<_T>::lowbit(int x)
{
    return x & (-x);
}
template<class _T>
Binary_Indexed_Tree_2D<_T>::Binary_Indexed_Tree()
{
    memset(this -> node, 0, sizeof(this -> node));
    this -> row = 0;
    this -> column = 0;
}
template<class _T>
void Binary_Indexed_Tree_2D<_T>::reserve(int r, int c)
{
    this -> row = r;
    this -> column = c;
}
template<class _T>
void Binary_Indexed_Tree_2D<_T>::add(int x, int y, _T addend)
{
    for (int i = x; i <= this -> row; i += lowbit(i))
    {
        for (int j = y; j <= this -> column; j++)
            this -> node[i][j] += addend;
    }
}
template<class _T>
_T Binary_Indexed_Tree_2D<_T>::query(int x, int y)
{
    _T rv = 0;

    for (int i = x; i <= this -> row; i += lowbit(i))
    {
        for (int j = y; j <= this -> column; j++)
            rv += this -> node[i][j];
    }

    return rv;
}

#endif