You have N integers, A1, A2, … , AN. You need to deal with two kinds of operations. One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval.
Input
The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000. The second line contains N numbers, the initial values of A1, A2, … , AN. -1000000000 ≤ Ai ≤ 1000000000. Each of the next Q lines represents an operation. “C a b c” means adding c to each of Aa, Aa+1, … , Ab. -10000 ≤ c ≤ 10000. “Q a b” means querying the sum of Aa, Aa+1, … , Ab.
Output
You need to answer all Q commands in order. One answer in a line.
Sample Input 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
Sample Output 4 55 9 15
The sums may exceed the range of 32-bit integers.
题目大意:一个有n个数的序列支持两种操作:C:对区间[l,r]中的每一个数都加一个值val;Q:询问区间[l,r]的和。
思路:线段树模板。区间修改,区间询问。
#include<cstdio> #define ls o<<1 #define lr o<<1|1 using namespace std; typedef long long LL; const int maxn=100005; LL a[maxn]; int n,m; struct node { int l,r; LL sum; LL lazy; int len; }T[maxn<<2]; void pushup(int o) { T[o].sum=T[ls].sum+T[lr].sum; } void build(int o,int l,int r) { T[o].l=l; T[o].r=r; T[o].lazy=0;//设置延迟标记 T[o].len=r-l+1; if(l==r)//叶子节点 { T[o].sum=a[l]; return; } int mid=(l+r)>>1; build(ls,l,mid);//递归构造左子树 build(lr,mid+1,r);//递归构造右子树 pushup(o);//根据左右子树节点的值向上更新当前结点的值 } /*当前结点的标志向孩子结点传递*/ void pushdown(int o) { T[ls].sum+=T[o].lazy*T[ls].len; T[lr].sum+=T[o].lazy*T[lr].len; T[ls].lazy+=T[o].lazy; T[lr].lazy+=T[o].lazy; T[o].lazy=0;//传递后,当前结点标记清空 } void update(int o,int l,int r,int lazy) { if(T[o].l==l&&T[o].r==r) { T[o].sum+=T[o].len*lazy; T[o].lazy+=lazy; return; } if(T[o].lazy) pushdown(o); int mid=(T[o].l+T[o].r)>>1; if(mid>=r) update(ls,l,r,lazy); else if(mid<l) update(lr,l,r,lazy); else { update(ls,l,mid,lazy); update(lr,mid+1,r,lazy); } //根据左右子树的值回溯向上更新当前结点的值 pushup(o); } LL query(int o,int l,int r) { if(T[o].l==l&&T[o].r==r) return T[o].sum; if(T[o].lazy) pushdown(o); int mid=(T[o].l+T[o].r)>>1; if(mid>=r) return query(ls,l,r); else if(mid<l) return query(lr,l,r); else return query(ls,l,mid)+query(lr,mid+1,r); } int main() { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) scanf("%lld",a+i); build(1,1,n); while(m--) { char op[3]; scanf("%s",op); if(op[0]=='C') { int l,r,v; scanf("%d%d%d",&l,&r,&v); update(1,l,r,v); } else { int l,r; scanf("%d%d",&l,&r); printf("%lld\n",query(1,l,r)); } } return 0; }