243. A simple integer Question 2 ---- segment tree update interval + + + query interval lazy mark

Given a series of length N A, and M instructions, each instruction may be either of the following:

1, "C lrd", represents the A [l], A [l + 1], ..., A [r] are plus d.

2, "Q lr", represents the number of l ~ r and the column number of interrogation.

For each inquiry, output a integer answer.

Input format
of the first row two integers N, M.

The second row of the N integers A [i].

M represents M rows next instruction, each instruction format as shown in the subject description.

Output format
for each inquiry, output a integer answer.

Each answer per line.

Data range
1 ≦ N, M≤105,
| D | ≤ 10000,
| A [I] | ≤1000000000
Input Sample:
10. 5
. 1. 5. 4. 3 2. 6. 7. 8. 9 10
Q. 4. 4
Q 10. 1
Q 2. 4
C . 6. 3. 3
Q 2. 4
output sample:
. 4
55
. 9
15

Bare title. Whether or update query must pass under the lazy mark



#include<bits/stdc++.h>
using namespace std;
const int N=1e5+1000;
typedef long long ll;
ll tree[N<<4];
ll lazy[N<<4];
ll a[N];
int n,m,x,y,val;
void push_up(int root)
{
	tree[root]=tree[root<<1]+tree[root<<1|1];
}
void push_down(int root,int l,int r)
{
	if(lazy[root])
	{
		int mid=l+r>>1;
		lazy[root<<1]+=lazy[root];
		lazy[root<<1|1]+=lazy[root];
		tree[root<<1]+=(ll)(mid-l+1)*lazy[root];
		tree[root<<1|1]+=(ll)(r-mid)*lazy[root];
		lazy[root]=0;
	}
}
void build(int root,int l,int r)
{
	lazy[root]=0;
	if(l==r )
	{
		tree[root]=a[l];
		return ;
	}
	int mid=l+r>>1;
	build(root<<1,l,mid);
	build(root<<1|1,mid+1,r);
	push_up(root);
}
void update(int root,int l,int r,int ql,int qr,int val)
{
	if(ql<=l&&r<=qr)
	{
		tree[root]+=(r-l+1)*val;
		lazy[root]+=val;
		return ;
	}
	push_down(root,l,r);
	int mid=l+r>>1;
	if(ql<=mid) update(root<<1,l,mid,ql,qr,val);
	if(qr>mid) update(root<<1|1,mid+1,r,ql,qr,val);
	push_up(root);
}
ll query(int root,int l,int r,int ql,int qr)
{
	ll res=0;
	if(ql<=l&&r<=qr) return tree[root];
	int mid=l+r>>1;
	push_down(root,l,r);
	if(ql<=mid) res+=query(root<<1,l,mid,ql,qr);
	if(qr>mid) res+=query(root<<1|1,mid+1,r,ql,qr);
	return res;
	
}
int main()
{
	scanf("%d %d",&n,&m);
	for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
	build(1,1,n);
	char op;
	while(m--)
	{
		cin>>op;
		if(op=='Q')
		{
			cin>>x>>y;
			cout<<query(1,1,n,x,y)<<endl;
		}
		else if(op=='C')
		{
			cin>>x>>y>>val;
			update(1,1,n,x,y,val);
		}	
	}
}

Published 309 original articles · won praise 6 · views 5260

Guess you like

Origin blog.csdn.net/qq_43690454/article/details/104078293