首先是下标从 \(1\sim n\) ,使用 \(lowbit(x)=x\&\ –x\)
template<typename T>
class Fenwick{
public:
vector<T>fenw;
int n;
Fenwick(int _n):n(_n){
fenw.resize(n+1);
}
void modify(int x,T w){
while(x<=n){
fenw[x]+=w;
x+=(x&-x);
}
}
T get(int x){
T res{};
while(x>0){
res+=fenw[x];
x-=(x&-x);
}
return res;
}
};
之后是 \(0\sim n–1\) 的版本,原理与 \(lowbit\) 大致相同
template<typename T>
class fenwick{
public:
vector<T>fenw;
int n;
fenwick(int _n):n(_n){
fenw.resize(n);
}
void modify(int x,T w){
while(x<n){
fenw[x]+=w;
x|=(x+1);
}
}
T get(int x){
T res{};
while(x>=0){
res+=fenw[x];
x=(x&(x+1))-1;
}
return res;
}
};
标签:template,树状,int,res,Fenwick,fenw,数组,写法,fenwick
From: https://www.cnblogs.com/sunmk/p/18548839