Problem 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
<p>The first line contains two numbers <i>N</i> and <i>Q</i>. 1 ≤ <i>N</i>,<i>Q</i> ≤ 100000.<br>The second line contains <i>N</i> numbers, the initial values of <i>A</i><sub>1</sub>, <i>A</i><sub>2</sub>, ... , <i>A<sub>N</sub></i>. -1000000000 ≤ <i>A<sub>i</sub></i> ≤ 1000000000.<br>Each of the next <i>Q</i> lines represents an operation.<br>"C <i>a</i> <i>b</i> <i>c</i>" means adding <i>c</i> to each of <i>A<sub>a</sub></i>, <i>A<sub>a</sub></i><sub>+1</sub>, ... , <i>A<sub>b</sub></i>. -10000 ≤ <i>c</i> ≤ 10000.<br>"Q <i>a</i> <i>b</i>" means querying the sum of <i>A<sub>a</sub></i>, <i>A<sub>a</sub></i><sub>+1</sub>, ... , <i>A<sub>b</sub></i>.</p>
Output
<p>You need to answer all <i>Q</i> commands in order. One answer in a line.</p>
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
这个题用树状数组老是超时,用线段树可以过,这个题目虽然不难,但却是做了很多次才过的题目,比较典型。
代码:
#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<queue>
#include<cstring>
#include<map>
using namespace std;
typedef long long ll;
#define M 100005
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
int n,q;
ll tree[M<<2];
ll col[M<<2];
inline void pushup(int rt)
{
tree[rt]=tree[rt<<1]+tree[rt<<1|1];
}
void build(int l,int r,int rt)
{
if(l==r)
{
col[rt]=0;
scanf("%I64d",&tree[rt]);
return;
}
int m=(l+r)>>1;
build(lson);
build(rson);
pushup(rt);
}
void pushdown(int rt,ll x)
{
if(col[rt])
{
col[rt<<1|1]+=col[rt];
col[rt<<1]+=col[rt];
tree[rt<<1]+=col[rt]*(x-(x>>1));
tree[rt<<1|1]+=col[rt]*(x>>1);
col[rt]=0;
}
}
void update(int L,int R,ll c,int l,int r,int rt)
{
if(L<=l&&r<=R)
{
col[rt]+=c;
tree[rt]+=(ll)(r-l+1)*c;
return;
}
pushdown(rt,r-l+1);
int m=(l+r)>>1;
if(L<=m) update(L,R,c,lson);
if(R>m) update(L,R,c,rson);
pushup(rt);
}
ll sum(int L,int R,int l,int r,int rt)
{
if(L<=l&&r<=R)
{
return tree[rt];
}
pushdown(rt,r-l+1);
int m=(l+r)>>1;
ll ret=0;
if(L<=m) ret+=sum(L,R,lson);
if(R>m) ret+=sum(L,R,rson);
pushup(rt);
return ret;
}
int main()
{
int a,b;
ll c;
char ch;
while(scanf("%d%d",&n,&q)!=EOF)
{
build(1,n,1);
while(q--)
{
getchar();
ch=getchar();
if(ch=='C')
{
scanf("%d%d%I64d",&a,&b,&c);
update(a,b,c,1,n,1);
}
else
{
scanf("%d%d",&a,&b);
printf("%I64d\n",sum(a,b,1,n,1));
}
}
}
return 0;
}