POJ3468 A Simple Problem with Integers【线段树 区间修改+区间求和】

A Simple Problem with Integers

http://poj.org/problem?id=3468

Time Limit: 5000MS   Memory Limit: 131072K
Total Submissions: 155601   Accepted: 48145
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 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.

Source

POJ Monthly--2007.11.25, Yang Yi

题意

输入 n, q表示初始有 n 个数, 接下来 q 行输入, Q x y 表示询问区间 [x, y]的和;C x y z 表示区间 [x, y] 内所有数加上 z ;

注意,要使用long long类型

思路

数列求和,线段树模板题

C++代码

#include

using namespace std;

#define ls l,m,rt<<1
#define rs m+1,r,rt<<1|1

typedef long long ll;
const int N=100010;


ll sum[N<<2],add[N<<2];

void pushup(int rt)
{
	sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}

void build(int l,int r,int rt)
{
	add[rt]=0; 
	if(l==r)
	{
		scanf("%lld",&sum[rt]);
		return;
	}
	int m=(l+r)>>1;
	build(ls);
	build(rs);
	pushup(rt);
}


//下堆惰性标记 
void pushdown(int rt,int ln,int rn)
{
	//ln、rn为左右子树的数量 
	if(add[rt])
	{
		//修改子节点的sum 
		sum[rt<<1]+=add[rt]*ln;
		sum[rt<<1|1]+=add[rt]*rn;
		//下推惰性标记 
		add[rt<<1]+=add[rt];
		add[rt<<1|1]+=add[rt];
		//清除本结点的标记 
		add[rt]=0;
	}
}

//区间修改 
void update(int L,int R,int C,int l,int r,int rt)
{
	if(L<=l&&r<=R)
	{
		sum[rt]+=(r-l+1)*C;
		add[rt]+=C;
		return;
	}
	int m=(l+r)>>1;
	pushdown(rt,m-l+1,r-m);//下推惰性标记
	if(L<=m)
	  update(L,R,C,ls);
	if(R>m)
	  update(L,R,C,rs);
	pushup(rt); 
}

//区间查询 
ll 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);
	ll ans=0;
	if(L<=m)
	  ans+=query(L,R,ls);
	if(R>m)
	  ans+=query(L,R,rs);
	return ans;
}

int main()
{
	int n,q;
	while(~scanf("%d%d",&n,&q))
	{
		build(1,n,1);
		while(q--)
		{
			char op;
			int L,R,C;
			scanf(" %c",&op);
			if(op=='Q')
			{
				scanf("%d%d",&L,&R);
				printf("%lld\n",query(L,R,1,n,1));
			}
			else
			{
				scanf("%d%d%d",&L,&R,&C);
				update(L,R,C,1,n,1);
			}
		}
	}
	return 0;
}

 

你可能感兴趣的:(数据结构)