Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 107324 | Accepted: 33474 | |
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
题目大意:
线段树区间更新,区间查询。
Ac代码:
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn=100000+10;
ll sum[maxn*4],add[maxn*4];
void pushUp(int k)
{
sum[k]=sum[k*2]+sum[k*2+1];
}
void pushDown(int k,int l,int r)
{
if(add[k])
{
int lc=k*2,rc=k*2+1,m=(l+r)/2;
add[lc]+=add[k];
add[rc]+=add[k];
sum[lc]+=add[k]*(m-l+1);
sum[rc]+=add[k]*(r-m);
add[k]=0;
}
}
void build(int k,int l,int r)
{
if(l==r)
{
scanf("%lld",&sum[k]);
add[k]=0;
return ;
}
int m=(l+r)/2;
build(k*2,l,m);
build(k*2+1,m+1,r);
pushUp(k);
}
void update(int a,int b,ll v,int k,int l,int r)
{
if(a<=l && r<=b)
{
add[k]+=v;
sum[k]+=v*(r-l+1);
return ;
}
pushDown(k,l,r);
int m=(l+r)/2;
if(a<=m)
update(a,b,v,k*2,l,m);
if(b>m)
update(a,b,v,k*2+1,m+1,r);
pushUp(k);
}
ll ask(int a,int b,int k,int l,int r)
{
if(a<=l && r<=b)
return sum[k];
pushDown(k,l,r);
int m=(l+r)/2;
ll res=0;
if(a<=m)
res+=ask(a,b,k*2,l,m);
if(b>m)
res+=ask(a,b,k*2+1,m+1,r);
pushUp(k);
return res;
}
int main()
{
int i,j,n,q,a,b;
char op[3];
scanf("%d%d",&n,&q);
build(1,1,n);
while(q--)
{
scanf("%s%d%d",op,&a,&b);
if(op[0]=='C')
{
ll v;
scanf("%lld",&v);
update(a,b,v,1,1,n);
}
else
{
printf("%lld\n",ask(a,b,1,1,n));
}
}
return 0;
}