Segment Tree

很早就懂线段树的思想,可是一直没去写过,今天写了一个,借鉴一点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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值