POJ 3468-A Simple Problem with Integers
#include < cstdio>
using namespace std;
const int maxn= 1e6 + 7 ;
typedef long long ll;
ll sumTree[ maxn<< 2 ] , len[ maxn<< 2 ] , lazy[ maxn<< 2 ] ;
void PushDown ( int pcur) {
if ( lazy[ pcur] == 0 ) return ;
lazy[ pcur<< 1 ] += lazy[ pcur] ;
lazy[ pcur<< 1 | 1 ] += lazy[ pcur] ;
sumTree[ pcur<< 1 ] += lazy[ pcur] * len[ pcur<< 1 ] ;
sumTree[ pcur<< 1 | 1 ] += lazy[ pcur] * len[ pcur<< 1 | 1 ] ;
lazy[ pcur] = 0 ;
}
void Build ( int pl, int pr, int pcur) {
len[ pcur] = pr- pl+ 1 ;
if ( pl== pr) {
scanf ( "%lld" , sumTree+ pcur) ;
return ;
}
int pm= ( pl+ pr) >> 1 ;
Build ( pl, pm, pcur<< 1 ) ;
Build ( pm+ 1 , pr, pcur<< 1 | 1 ) ;
sumTree[ pcur] = sumTree[ pcur<< 1 ] + sumTree[ pcur<< 1 | 1 ] ;
}
void UpdateArea ( int posl, int posr, int data, int pl, int pr, int pcur) {
if ( posl<= pl&& pr<= posr) {
sumTree[ pcur] += data* len[ pcur] ;
lazy[ pcur] += data;
return ;
}
PushDown ( pcur) ;
int pm= ( pl+ pr) >> 1 ;
if ( posl<= pm) UpdateArea ( posl, posr, data, pl, pm, pcur<< 1 ) ;
if ( posr> pm) UpdateArea ( posl, posr, data, pm+ 1 , pr, pcur<< 1 | 1 ) ;
sumTree[ pcur] = sumTree[ pcur<< 1 ] + sumTree[ pcur<< 1 | 1 ] ;
}
ll sumQuery ( int posl, int posr, int pl, int pr, int pcur) {
if ( posl<= pl&& pr<= posr)
return sumTree[ pcur] ;
PushDown ( pcur) ;
int pm= ( pl+ pr) >> 1 ;
ll ans= 0 ;
if ( posl<= pm) ans+= sumQuery ( posl, posr, pl, pm, pcur<< 1 ) ;
if ( posr> pm) ans+= sumQuery ( posl, posr, pm+ 1 , pr, pcur<< 1 | 1 ) ;
return ans;
}
int main ( ) {
int n, q, pl, pr, data;
char t;
scanf ( "%d %d" , & n, & q) ;
Build ( 1 , n, 1 ) ;
while ( q-- ) {
getchar ( ) ;
t= getchar ( ) ;
if ( t== 'Q' ) {
scanf ( "%d %d" , & pl, & pr) ;
printf ( "%lld\n" , sumQuery ( pl, pr, 1 , n, 1 ) ) ;
}
else {
scanf ( "%d %d %d" , & pl, & pr, & data) ;
UpdateArea ( pl, pr, data, 1 , n, 1 ) ;
}
}
return 0 ;
}