A Simple Problem with Integers

http://acm.hust.edu.cn/vjudge/contest/view.action?cid=34869#problem/C

线段树,区间更新,区间求和,延迟标记

// 3c.cpp : 定义控制台应用程序的入口点。
//

//#include "stdafx.h"
#include<iostream>

using namespace std;

#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
#define LL long long
const int maxn = 100005;
LL sum[ maxn << 2 ];
LL Add[ maxn << 2 ];

void PushUp( int rt ){
	sum[ rt ] = sum[ rt << 1 ] + sum[ rt << 1 | 1 ];
}
 
void PushDown( int rt, int m ){
	if( Add[ rt ] ){
		Add[ rt << 1 ] += Add[ rt ];
		Add[ rt << 1 | 1 ] += Add[ rt ];
		sum[ rt << 1 ] += Add[ rt ] * ( m - ( m >> 1 ) );
		sum[ rt << 1 | 1 ] += Add[ rt ] * ( m >> 1 );
		Add[ rt ] = 0;
	}
}
void Build( int l, int r, int rt ){
	Add[ rt ] = 0;
	if( l == r ){
		cin >> sum[ rt ];
		return;
	}
	int m = ( l + r ) / 2;
	Build( lson );
	Build( rson );
	PushUp( rt );
}

void Update( int L, int R, int num, int l, int r, int rt ){
	if( L <= l && r <= R ){
		Add[ rt ] += num;
		sum[ rt ] += ( LL )( r - l + 1 ) * num;
		return;
	}
	PushDown( rt, r - l + 1 );
	int m = ( l + r ) >> 1;
	if( L <= m )
		Update( L, R, num, lson );
	if( m < R )
		Update( L, R, num, rson );
	PushUp( rt );
}

LL Query( int L, int R, int l, int r, int rt ){
	if( L <= l && r <= R ){
		return sum[ rt ];
	}
	PushDown( rt, r - l + 1 );
	int m = ( l + r ) >> 1;
	LL ans = 0;
	if( L <= m )
		ans += Query( L, R, lson );
	if( m < R )
		ans += Query( L, R, rson );
	return ans;
}

//int _tmain(int argc, _TCHAR* argv[])
int main()
{
	int n, m, a, b, c;
	char str[ 10 ];
	while( cin >> n >> m ){
		//memset( Add, 0, sizeof( Add ) );
		Build( 1, n, 1 );
		while( m-- ){
			cin >> str;
			if( str[ 0 ] == 'Q' ){
				cin >> a >> b;
				cout << Query( a, b, 1, n, 1 ) << endl;
			}
			else{
				cin >> a >> b >> c;
				Update( a, b, c, 1, n, 1 );
			}
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值