Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 31956 | Accepted: 9089 | |
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
Source
#include <iostream>
#include <stdio.h>
#include <string.h>
#define lson l,m,k<<1
#define rson m+1,r,k<<1|1
#define N 100001
using namespace std;
struct node
{
long long sum,add;
};
node st[N<<2];
void up(int &k)
{
st[k].sum=st[k<<1].sum+st[k<<1|1].sum;
}
void down(int &k,int m)//将附加信心传递给孩子
{
st[k<<1].add+=st[k].add;
st[k<<1|1].add+=st[k].add;
st[k<<1].sum+=st[k].add*(m-(m>>1));//这里注意m>>1要加括号、估计是优先级比较低呀
st[k<<1|1].sum+=st[k].add*(m>>1);
st[k].add=0;
}
void build(int l,int r,int k)
{
st[k].add=0;
if(l==r)
{
scanf("%lld",&st[k].sum);
return ;
}
int m=(l+r)>>1;
build(lson);
build(rson);
up(k);
}
long long add;
void updata(int &L,int &R,int l,int r,int k)
{
if(L<=l&&R>=r)
{
st[k].add+=add;
st[k].sum+=add*(r-l+1);//这里要注意,开始s[k].sum=s[k].add*(r-l+1),当k是根时就会错的.
return ;
}
if(st[k].add)
down(k,r-l+1);
int m=(l+r)>>1;
if(L<=m) updata(L,R,lson);
if(R>m) updata(L,R,rson);
up(k);
}
long long query(int &L,int &R,int l,int r,int k)
{
if(L<=l&&R>=r)
{
return st[k].sum;
}
if(st[k].add)
down(k,r-l+1);
int m=(l+r)>>1;
long long t1=0,t2=0;
if(L<=m) t1=query(L,R,lson);
if(R>m) t2=query(L,R,rson);
up(k);
return t1+t2;
}
int main()
{
int n,p;
char c;
while(scanf("%d%d",&n,&p)!=EOF)
{
build(1,n,1);
int L,R;
while(p--)
{
getchar();
scanf("%c",&c);
if(c=='Q')
{
scanf("%d%d",&L,&R);
printf("%lld\n",query(L,R,1,n,1));
}
else
{
scanf("%d%d%lld",&L,&R,&add);
updata(L,R,1,n,1);
}
}
}
return 0;
}