Time Limit: 5000MS Memory Limit: 131072K
Total Submissions: 63324 Accepted: 19458
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
The sums may exceed the range of 32-bit integers.
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
#define INF 0x3f3f3f3f
#define inf -0x3f3f3f3f
#define FOR(a,b) for(int i = a ; i < b ; i++)
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
#define FOPENIN(IN) freopen(IN, "r", stdin)
#define FOPENOUT(OUT) freopen(OUT, "w", stdout)
#define LL long long
const int maxn = 100000+1000;
LL add[maxn<<2];
LL sum[maxn<<2];
void pushUp(int cur){
sum[cur]=sum[cur<<1] + sum[cur<<1|1];
}
void pushDown(int cur ,int m){//维护结点cur,对应区间是cur<<1,cur<<1|1
if(add[cur]){//本结点有标记才传递。注意本题中add值为实数,所以0代表没有标记
add[cur<<1]+=add[cur]; //左子树点增加
add[cur<<1|1] += add[cur]; //右子树点增加
sum[cur<<1] += add[cur]*(m-(m>>1));//左子树区间段增加
sum[cur<<1|1] += add[cur]*(m>>1); //右子树区间段增加
add[cur] = 0; //清除本结点标记
}
}
void build(int l,int r,int cur){
add[cur]= 0;//建树时初始结点都未标记
if(l == r){
scanf("%lld",&sum[cur]); return ;
}
int mid = (l + r) >>1 ;
build(l,mid,cur<<1); //建立左子树
build(mid+1,r,cur<<1|1);//建立右子树
pushUp(cur);
}
void update(int ql,int qr,int v,int l,int r,int cur){
if(ql <= l && qr >= r){//递归边界
add[cur] += v; //累加边界的add值
sum[cur] += v*(r-l+1); //计算区间和
return ;
}
pushDown(cur,r-l+1);
int mid = (l + r) >>1 ;
if(ql <= mid ) update(ql,qr,v,l,mid,cur<<1);
if(qr > mid) update(ql,qr,v,mid+1,r,cur<<1|1);
pushUp(cur); //递归结束前重新计算本结点的附加信息
}
LL query(int ql,int qr ,int l,int r,int cur){
if(ql <= l && qr >= r){return sum[cur];}//递归边界
pushDown(cur,r-l+1); //用边界区间的附加信息更新答案
int mid = (l + r )>>1 ;
LL ans = 0 ;//递归统计,累加参数add
if(ql <= mid ) ans += query(ql,qr,l,mid,cur<<1);
if(qr > mid ) ans += query(ql,qr,mid+1,r,cur<<1|1);
return ans ;
}
int main()
{
int N,Q;
scanf("%d%d",&N,&Q);
build(1,N,1);
while(Q--){
char s[3];
int a,b,c;
scanf("%s",s);
if(s[0]=='Q'){
scanf("%d%d",&a,&b);
printf("%lld\n",query(a,b,1,N,1));
}
else if(s[0]=='C'){
scanf("%d%d%d",&a,&b,&c);
update(a,b,c,1,N,1);
}
}
// system("pause");
return 0;
}