HDU1556:线段树

HDU1556:区间更新,单点查询全部

(单点查询时,一次查询到底,用数组记录)

#include 
using namespace std;
int const N = 100000 + 10;
int n,a[N];
struct Node
{
	int l,r,sum,lazy;
	void updata(int val){
		lazy += val;
		sum += (r-l+1)*val;
	}
}node[N<<2];
void build(int id ,int l,int r){
	node[id].l = l,node[id].r = r;
	node[id].sum = node[id].lazy = 0;
	if(l == r)	return;
	else{
		int mid = (l + r) >> 1;
		build(id<<1,l,mid);
		build(id<<1|1,mid+1,r);
	}
}
void push_down(int id){
	int val = node[id].lazy;
	if(val){
		node[id<<1].updata(val);
		node[id<<1|1].updata(val);
		node[id].lazy = 0;
	}
}
void push_up(int id){
	node[id].sum = node[id<<1].sum + node[id<<1|1].sum;
}
void updata(int id,int L,int R){
	int l = node[id].l,	r = node[id].r;
	if(L <= l && r <= R){
		node[id].updata(1);
	}else{
		int mid = (l + r) >> 1;
		push_down(id);
		if(L <= mid)	updata(id<<1,L,R);
		if(mid < R)		updata(id<<1|1,L,R);
		push_up(id);
	}
}
void query(int id,int L,int R){
	int l = node[id].l,	r = node[id].r;
	if(l == r){
		a[l] = node[id].sum;
	}else{
		int mid = (l + r) >> 1;
		push_down(id);
		query(id<<1,L,R);
		query(id<<1|1,L,R);
		push_up(id);
	}
}
int main(){
	while(~scanf("%d",&n)&&n){
		build(1,1,n);
		for(int i=1;i<=n;i++){
			int x,y;
			scanf("%d%d",&x,&y);
			updata(1,x,y);
		}
		query(1,1,n);
		for(int i=1;i<=n;i++)
			printf("%d%c",a[i],i!=n?' ':'\n');
	}
	return 0;
}

/*
区间更新,每次区间加1
单点查询
*/

你可能感兴趣的:(线段树)