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
PS:线段树的入门题吧,注意理解懒标记。
AC代码:
#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<map>
#include<queue>
#include<set>
#include<cmath>
#include<stack>
#include<string>
const int maxn=1e5+10;
const int mod=1e9+7;
const int inf=1e8;
#define me(a,b) memset(a,b,sizeof(a))
typedef long long ll;
using namespace std;
ll num[maxn<<2],add[maxn<<2];
void pushup(int rt)
{
num[rt]=num[rt<<1]+num[rt<<1|1];
}
void build(int l,int r,int rt)
{
if(l==r)
{
scanf("%lld",&num[rt]);
return ;
}
int m=(l+r)>>1;
build(l,m,rt<<1);
build(m+1,r,rt<<1|1);
pushup(rt);
}
void updata(int l,int r,int rt)
{
if(add[rt])
{
int m=(l+r)>>1;
add[rt<<1]+=add[rt];
add[rt<<1|1]+=add[rt];
num[rt<<1]+=add[rt]*(m-l+1);
num[rt<<1|1]+=add[rt]*(r-m);
add[rt]=0;
}
}
void pushdata(int L,int R,int c,int l,int r,int rt)
{
if(L<=l&&R>=r)
{
num[rt]+=(r-l+1)*c,add[rt]+=c;
return ;
}
int m=(l+r)>>1;
updata(l,r,rt);
if(L<=m)
pushdata(L,R,c,l,m,rt<<1);
if(R>m)
pushdata(L,R,c,m+1,r,rt<<1|1);
pushup(rt);
}
ll getsum(int L,int R,int l,int r,int rt)
{
if(L<=l&&R>=r)
return num[rt];
ll sum=0;
updata(l,r,rt);
int m=(l+r)>>1;
if(L<=m)
sum+=getsum(L,R,l,m,rt<<1);
if(R>m)
sum+=getsum(L,R,m+1,r,rt<<1|1);
return sum;
}
int main()
{
int m,n;
while(cin>>n>>m)
{
me(num,0),me(add,0);
build(1,n,1);
while(m--)
{
char s[5];
scanf("%s",s);
if(s[0]=='Q')
{
int x,y;scanf("%d%d",&x,&y);
cout<<getsum(x,y,1,n,1)<<endl;
}
else
{
int x,y,c;scanf("%d%d%d",&x,&y,&c);
pushdata(x,y,c,1,n,1);
}
}
}
return 0;
}