Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 93133 | Accepted: 28985 | |
Case Time Limit: 2000MS |
Description
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
Hint
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; typedef long long LL; const int maxn=100005; LL sum[4*maxn]; LL col[4*maxn]; void buildtree(int l,int r,int pos) { col[pos]=sum[pos]=0; if(l==r){scanf("%lld",&sum[pos]);return;} int mid=(l+r)>>1; buildtree(l,mid,pos<<1); buildtree(mid+1,r,pos<<1|1); sum[pos]=sum[pos<<1]+sum[pos<<1|1]; } void update(int l,int r,int pos,int resl,int resr,int value) { //不用怕前面积攒了很多,因为遍历到父亲的时候你已经更新了 if(l==r){sum[pos]+=value; return;} if(resl<=l&&r<=resr) { sum[pos]+=value*(r-l+1); col[pos]+=value;//儿子们需要增加的值 return; } int mid=(l+r)>>1; if(col[pos]) { col[pos<<1]+=col[pos]; col[pos<<1|1]+=col[pos]; sum[pos<<1]+=col[pos]*(mid-l+1); sum[pos<<1|1]+=col[pos]*(r-mid); col[pos]=0; } if(resl<=mid)update(l,mid,pos<<1,resl,resr,value); if(resr>mid)update(mid+1,r,pos<<1|1,resl,resr,value); sum[pos]=sum[pos<<1]+sum[pos<<1|1]; } LL query(int l,int r,int pos,int ql,int qr) { LL ans=0; if(ql<=l&&r<=qr){return sum[pos];} int mid=(l+r)>>1; if(col[pos]) { col[pos<<1]+=col[pos]; col[pos<<1|1]+=col[pos]; sum[pos<<1]+=col[pos]*(mid-l+1); sum[pos<<1|1]+=col[pos]*(r-mid); col[pos]=0;//儿子已经更新完毕 } if(ql<=mid)ans+=query(l,mid,pos<<1,ql,qr); if(qr>mid)ans+=query(mid+1,r,pos<<1|1,ql,qr); return ans; } int main() { int n,m,a,b,c; char q[10]; while(scanf("%d%d",&n,&m)==2) { buildtree(1,n,1); while(m--) { scanf("%s%d%d",&q,&a,&b); if(q[0]=='Q') { printf("%lld\n",query(1,n,1,a,b)); } else if(q[0]=='C') { scanf("%d",&c); update(1,n,1,a,b,c); } } } }