很早就懂线段树的思想,可是一直没去写过,今天写了一个,借鉴一点watashi的存储写法。
#include <iostream>
#include <algorithm>
using namespace std;
class SegTree{
private:
int m;
long long *tr;
int *d;
inline int L(int i){return i<<1;}
inline int R(int i){return i<<1|1;}
void pushDown(int p,int pl,int pr){
if(pl == pr) return;
if(d[p]){
int len = (pr - pl + 1)>>1;
int lc = L(p),rc = R(p);
tr[lc] += len*d[p];
tr[rc] += len*d[p];
d[lc] = d[p];
d[rc] = d[p];
d[p] = 0;
}
}
void _update(int p,int pl,int pr,int l,int r,int x){
if(pl==l && pr==r){
tr[p] += (pr-pl+1)*x;
d[p] += x;
} else {
pushDown(p,pl,pr);
int pm = (pl+pr)>>1;
int lc = L(p), rc = R(p);
if(r<=pm) _update(lc,pl,pm,l,r,x);
else if(l>pm) _update(rc,pm+1,pr,l,r,x);
else{
_update(lc,pl,pm,l,pm,x);
_update(rc,pm+1,pr,pm+1,r,x);
}
tr[p] = tr[lc] + tr[rc];
}
}
long long _query(int p,int pl,int pr,int l,int r){
long long ans;
if(pl == l && pr == r) return tr[p];
pushDown(p,pl,pr);
int pm = (pl+pr)>>1;
int lc = L(p), rc = R(p);
if(r<=pm) return _query(lc,pl,pm,l,r);
else if(l>pm) return _query(rc,pm+1,pr,l,r);
else return _query(lc,pl,pm,l,pm) + _query(rc,pm+1,pr,pm+1,r);
}
public:
SegTree(int c,const long long a[]){
int i;
m = 1;
while(m<c) m<<=1;
tr = new long long[m<<1];
d = new int[m<<1];
fill(d,d+m+m,0);
for(i=m;i<m+c;i++) tr[i] = a[i-m];
fill(tr+m+c,tr+m+m,0);
for(i=(m+c-1)>>1;i>=1;i--) tr[i] = tr[L(i)]+tr[R(i)];
}
~SegTree(){
delete []tr;
delete []d;
}
void update(int l,int r,int x){
_update(1,1,m,max(l,1),min(r,m),x);
}
long long query(int l,int r){
if(l>m || r<1) return 0;
return _query(1,1,m,max(l,1),min(r,m));
}
};
int main(){
long long a[9]={0};
SegTree st(9,a);
st.update(1,3,2);
cout << st.query(3,5) << endl;
st.update(3,6,1);
cout << st.query(3,8) << endl;
cout << st.query(1,8) << endl;
return 0;
}