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 4Sample Output
4 55 9 15Hint
The sums may exceed the range of 32-bit integers.
题目大意:对于一个区间有两种操作:
1.Q即访问,访问某个区间,求这个区间的最大值。
2.C即插入,在指定的区间每个元素都加一个值
思路:线段树最基本的操作,改变一个区间的值,求一个区间的和。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
long long sum[500000],lazy[500000];
void creat(int l,int r,int o)//建立线段树
{
if(l==r)
{
scanf("%lld",&sum[o]);
return;
}
int mid=(l+r)>>1;
creat(l,mid,o<<1);
creat(mid+1,r,o<<1|1);
sum[o]=sum[o<<1]+sum[o<<1|1];
}
void push(int o,int l)//更新左儿子和右儿子,下移操作
{
if(lazy[o])
{
lazy[o<<1]+=lazy[o];
lazy[o<<1|1]+=lazy[o];
sum[o<<1]+=lazy[o]*(l-(l>>1));
sum[o<<1|1]+=lazy[o]*(l>>1);
lazy[o]=0;//**********
}
}
void update(int x,int y,int l,int r,int o,int c)
{
if(l>=x&&r<=y)//****x和y为所要的区间。l-r为访问的区间
{
sum[o]+=c*(r-l+1);
lazy[o]+=c;
return;
}
push(o,r-l+1);
int mid=(r+l)>>1;
if(mid>=x)
update(x,y,l,mid,o<<1,c);
if(y>mid)
update(x,y,mid+1,r,o<<1|1,c);
sum[o]=sum[o<<1]+sum[o<<1|1];
}
long long ask(int x,int y,int l,int r,int o)
{
if(l>=x&&r<=y)
return sum[o];
push(o,r-l+1);
int mid=(r+l)>>1;
long long num=0;
if(mid>=x)
num+=ask(x,y,l,mid,o<<1);
if(y>mid)
num+=ask(x,y,mid+1,r,o<<1|1);
return num;
}
int main()
{
int n,q;
while(~scanf("%d%d",&n,&q))
{
memset(sum,0,sizeof(sum));
memset(lazy,0,sizeof(lazy));
creat(1,n,1);
while(q--)
{
char a[10];
int l,r,c;
scanf("%s",a);
if(a[0]=='Q')
{
scanf("%d%d",&l,&r);
printf("%lld\n",ask(l,r,1,n,1));
}
else
{
scanf("%d%d%d",&l,&r,&c);
update(l,r,1,n,1,c);
}
}
}
return 0;
}