A Simple Problem with Integers POJ – 3468(线段树的区间更新)

作者: qwq 分类: ACM 发布时间: 2017-09-08 19:31
Time Limit: 5000MS Memory Limit: 131072K
Total Submissions: 118228 Accepted: 36755
Case Time Limit: 2000MS

Description

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 abc” means adding c to each of AaAa+1, … , Ab. -10000 ≤ c ≤ 10000.
“Q ab” 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.
这道题是一道模板题,就是线段树的区间查询和区间更新,使用lazy数组即可完成。具体可以参考这篇文章
但是这道题坑的地方在于他的数据特别大,int存不下,只能用long long。所以得注意细节,我wa了好多发才发现是调用函数的时候把longlong写成了int。
哎。。粗心的毛病也改不了了。。。。
参考代码
#include<iostream>
#include<cstring>
typedef long long ll;
using namespace std;
ll aa[254299];
ll a[600007];
ll lazy[600007];
void build(int n,int l,int r){
	if(l==r){
		a[n]=aa[l];
		return;
	}
	build(n<<1,l,(l+r)/2);
	build(n<<1|1,(l+r)/2+1,r);
	a[n]=a[n<<1]+a[n<<1|1];
	

}

void update(int n,int l,int r,int L,int R ,ll N){
	if(L<=l&&R>=r){
		a[n]+=N*(r-l+1);
		lazy[n]+=N;
		return;
	}
	if(l==r){
		return;
	}
	if(lazy[n]!=0){
	update(n<<1,l,(l+r)/2,l,(l+r)/2,lazy[n]);
	update((n<<1)+1,(l+r)/2+1,r,(l+r)/2+1,r,lazy[n]);
	lazy[n]=0;	
	}

	if(L<=(l+r)/2){
	
	update(n<<1,l,(l+r)/2,L,R,N);
	}
	if(R>(l+r)/2){
	update(n<<1|1,(l+r)/2+1,r,L,R,N);
	}
	a[n]=a[n<<1]+a[n<<1|1];
}
ll query(int n,int l,int r,int x,int y){
//	cout<<l<<" "<<r<<endl;
if(x<=l&&y>=r){
	return a[n];
}

if(lazy[n]!=0){
	update(n<<1,l,(l+r)/2,l,(l+r)/2,lazy[n]);
	update(n<<1|1,(l+r)/2+1,r,(l+r)/2+1,r,lazy[n]);
	lazy[n]=0;		
	}

ll sum=0;
if(x<=(l+r)/2){
	sum+=query(n<<1,l,(l+r)/2,x,y);
}
if(y>(l+r)/2){
	sum+=query(n<<1|1,(l+r)/2+1,r,x,y);
}
	return sum;
	
	
}



int main(){
	ios::sync_with_stdio(0);

	int n,q;
	while(cin>>n>>q){
		int k=0;
		
	while((1<<k)<n){
			k++;
		}
		
		memset(aa,0,sizeof(aa));
		memset(a,0,sizeof(a));
		memset(lazy,0,sizeof(lazy));
		for(int i=1;i<=n;i++)
		cin>>aa[i];
	build(1,1,1<<k);
	

	char c;
	int x,y,z;
	for(int i=0;i<q;i++){	
		cin>>c;
		
		if(c=='Q'){
		cin>>x>>y;
		cout<<query(1,1,1<<k,x,y)<<endl;
		}else{
		cin>>x>>y>>z;
		update(1,1,1<<k,x,y,z);
		}
		
	}
	
		
	}
	
	
	
	return 0;
}

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注