A Simple Problem with Integers
题目链接:POJ - 3468
题意:有N个数,Q个操作,两种操作:
一:区间[l, r]中的数都加同一个数c;
二:求区间[l, r]中所有数的和;
#include <stdio.h>
#include <algorithm>
using namespace std;
const int maxn=1e5+100;
struct node{
int l, r;
long long sum, lazy;
}tr[maxn<<2];
long long a[maxn];
void updown(int m){
tr[m].sum=tr[m<<1].sum+tr[m<<1|1].sum;
}
void build(int m, int l, int r){
tr[m].l=l;
tr[m].r=r;
tr[m].lazy=0;
if(l==r){
scanf("%lld", &tr[m].sum);
return;
}
int mid=(l+r)>>1;
build(m<<1, l, mid);
build(m<<1|1, mid+1, r);
updown(m);
}
void pushdown(int m){
if(tr[m].lazy){
tr[m].sum+=(tr[m].r-tr[m].l+1)*tr[m].lazy;
if(tr[m].l==tr[m].r){
tr[m].lazy=0;
return;
}
tr[m<<1].lazy+=tr[m].lazy;
tr[m<<1|1].lazy+=tr[m].lazy;
tr[m].lazy=0;
}
}
void updata(int m, int l, int r, long long val){
pushdown(m);
if(tr[m].l>r||tr[m].r<l) return;
if(tr[m].l>=l&&tr[m].r<=r){
tr[m].sum+=(tr[m].r-tr[m].l+1)*val;
if(tr[m].r==tr[m].l) return;
tr[m<<1].lazy+=val;
tr[m<<1|1].lazy+=val;
return;
}
updata(m<<1, l, r, val);
updata(m<<1|1, l, r, val);
updown(m);
}
long long query(int m, int l, int r){
pushdown(m);
if(tr[m].l>r||tr[m].r<l) return 0;
if(tr[m].l>=l&&tr[m].r<=r) return tr[m].sum;
return query(m<<1, l, r)+query(m<<1|1, l, r);
updown(m);
}
int main(){
int N, Q;
while(~scanf("%d%d", &N, &Q)){
build(1, 1, N);
//print(1);
while(Q--){
char op[5];
scanf("%s", op);
if(op[0]=='C'){
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
updata(1, a, b, c);
}
else{
int a, b;
scanf("%d%d", &a, &b);
printf("%lld\n", query(1, a, b));
}
//print(1);
}
}
return 0;
}