昨天在codeforces看tourist代码是看到了这个Fenwick,看了半天才发下这是个树状数组
突然间就萌生了写一些常用模板封装起来的打算
git仓库链接:https://github.com/abmcar/ACM/tree/master/template
template <typename T>
class Fenwick
{
public:
Fenwick(int _n) : n(_n)
{
fenw.resize(n + 1);
}
void modifty(int x, T val)
{
while (x <= n)
{
fenw[x] += val;
x |= (x + 1);
}
}
T get(int x)
{
T cnt{};
while (x >= 0)
{
cnt += fenw[x];
x = (x & (x + 1)) - 1;
}
return cnt;
}
private:
vector<T> fenw;
int n;
};
食用样例:
//初始化构造
Fenwick<int> fen1(10);
Fenwick<double> fen2(10);
//add值
fen1.modifty(1, 1);
fen1.modifty(3, 3);
fen2.modifty(1, 2);
fen2.modifty(3, 2.2);
//查询
cout << fen1.get(3) << endl
<< fen2.get(3) << endl;
运行结果: