给定一个长度为N的数列A,以及M条指令,每条指令可能是以下两种之一:
1、“C l r d”,表示把 A[l],A[l+1],…,A[r] 都加上 d。
2、“Q l r”,表示询问 数列中第 l~r 个数的和。
对于每个询问,输出一个整数表示答案。
输入格式
第一行两个整数N,M。
第二行N个整数A[i]。
接下来M行表示M条指令,每条指令的格式如题目描述所示。
输出格式
对于每个询问,输出一个整数表示答案。
每个答案占一行。
数据范围
1≤N,M≤105,
|d|≤10000,
|A[i]|≤1000000000
输入样例:
10 5
1 2 3 4 5 6 7 8 9 10
Q 4 4
Q 1 10
Q 2 4
C 3 6 3
Q 2 4
输出样例:
4
55
9
15
裸题。不管是更新还是查询都要下传懒惰标记
#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);
}
}
}