A Simple Problem with Integers - 線段樹

You have N integers, A1A2, ... , 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 A1A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of AaAa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of AaAa+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<iostream>
#include<stdio.h>
using namespace std;
#define maxn 100007
long long  Sum[maxn<<2];
long long  A[maxn],add[maxn<<2];
void PushUp(int rt){
	Sum[rt]=Sum[rt<<1]+Sum[rt<<1|1];
}
void PushDown(int rt,int ln,int rn)
{
	if(add[rt])
	{
		add[rt<<1]+=add[rt];
		add[rt<<1|1]+=add[rt];
		Sum[rt<<1]+=add[rt]*ln;
		Sum[rt<<1|1]+=add[rt]*rn;
		add[rt]=0;
	}
}
void Build(int l,int r,int rt)
{
	if(l==r)
	{
		Sum[rt]=A[l];
		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 C,int l,int r,int rt)
{
	if(l==r)
	{
		Sum[rt]+=C;
		return ;
	}
	int m=(l+r)>>1;
	if(L<=m) 
		Updata(L,C,l,m,rt<<1);
	else
	{
		Updata(L,C,m+1,r,rt<<1|1);
	}
	PushUp(rt);
}
void Up(int L,int R,long long C,int l,int r,int rt)
{
	if(L<=l && r<=R)
	{
		Sum[rt]+=C*(r-l+1);
		add[rt]+=C;
		return ;
	}
	int m=(l+r)>>1;
	PushDown(rt,m-l+1,r-m);
	if(L<=m)
		Up(L,R,C,l,m,rt<<1);
	if(R>m)
		Up(L,R,C,m+1,r,rt<<1|1);
	PushUp(rt);
}
long long Query(int L,int R,int l,int r,int rt)
{
	if(L<=l && r<=R)
	{
		return Sum[rt];
	}
	int m=(l+r)>>1;
	PushDown(rt,m-l+1,r-m);
	long long ANS=0;
	if(L<=m) ANS+=Query(L,R,l,m,rt<<1);
	if(R>m) ANS+=Query(L,R,m+1,r,rt<<1|1);
	return ANS;
}
int main()
{
	int n,q,a,b;
	long long c;
	char cmd;
	cin>>n>>q;
	for(int i=1;i<=n;i++)
	{
		scanf("%lld",&A[i]);
	}
	Build(1,n,1);
	while(q>0)
	{
		q--;
		cin>>cmd;
		if(cmd=='Q')
		{
			cin>>a>>b;
			cout<<Query(a,b,1,n,1)<<endl;
		}
		else if(cmd=='C')
		{
			cin>>a>>b>>c;
			Up(a,b,c,1,n,1);
		}
	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章