A Simple Problem with Integers
POJ - 3468
code
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
typedef long long ll;
const int N = 100005 , INF = 0x3f3f3f3f ;
ll tree[ N << 2 ] ;
ll lazy[ N << 2 ] ;
#define ls(rt) (rt << 1)
#define rs(rt) (rt << 1 | 1)
void push_up ( int root) { tree[ root] = tree[ ls ( root) ] + tree[ rs ( root) ] ; }
void push_down ( int root, int len) {
if ( lazy[ root] ) {
lazy[ ls ( root) ] + = lazy[ root] ;
lazy[ rs ( root) ] + = lazy[ root] ;
tree[ ls ( root) ] + = lazy[ root] * ( len - ( len >> 1 ) ) ;
tree[ rs ( root) ] + = lazy[ root] * ( len >> 1 ) ;
lazy[ root] = 0 ;
}
}
void build_tree ( int l, int r, int root) {
lazy[ root] = 0 ;
if ( l == r) {
scanf ( "%lld" , & tree[ root] ) ;
return ;
}
int mid = ( l + r) >> 1 ;
build_tree ( l, mid, ls ( root) ) ;
build_tree ( mid + 1 , r, rs ( root) ) ;
push_up ( root) ;
}
void update ( int l, int r, int root, int L, int R, int val) {
if ( L <= l && r <= R) {
tree[ root] + = ( r - l + 1 ) * val;
lazy[ root] + = val;
return ;
}
push_down ( root, r - l + 1 ) ;
int mid = ( l + r) >> 1 ;
if ( L <= mid) update ( l, mid, ls ( root) , L, R, val) ;
if ( mid < R) update ( mid + 1 , r, rs ( root) , L, R, val) ;
push_up ( root) ;
}
ll query ( int l, int r, int root, int L, int R) {
if ( L <= l && r <= R) {
return tree[ root] ;
}
push_down ( root, r - l + 1 ) ;
ll res = 0 ;
int mid = ( l + r) >> 1 ;
if ( L <= mid) res + = query ( l, mid, ls ( root) , L, R) ;
if ( R > mid) res + = query ( mid + 1 , r, rs ( root) , L, R) ;
return res;
}
int main ( ) {
int n, q;
while ( scanf ( "%d%d" , & n, & q) != EOF ) {
build_tree ( 1 , n, 1 ) ;
while ( q-- ) {
char s[ 5 ] ;
int x, y, z;
scanf ( "%s" , s) ;
if ( s[ 0 ] == 'Q' ) {
scanf ( "%d%d" , & x, & y) ;
printf ( "%lld\n" , query ( 1 , n, 1 , x, y) ) ;
} else {
scanf ( "%d%d%d" , & x, & y, & z) ;
update ( 1 , n, 1 , x, y, z) ;
}
}
}
return 0 ;
}