题目链接:http://poj.org/problem?id=3468
成段更新,和这题差不多 【 hdu 1698 Just a Hook】,但是这题的更新效果是叠加的,所以相应的lazy数组也是+=的。然后一个坑点就是注意一下数据量,超出int的范围了,要用long long, 别的代码和上面那题基本是一样的了。
还有一个地方要强调的是,lazy数组是因为爸爸自己懒得直接帮儿子更新,留给儿子的财产。
所以
lazy[rt] += val;
segTree[rt] += val * (LL)(end - begin + 1);
爸爸的更新是用的val去乘,lazy数组是留给儿子的。
lazy[rt<<1] += lazy[rt];
lazy[rt<<1|1] += lazy[rt];
segTree[rt<<1] += (LL)(mid - begin + 1) * lazy[rt];
segTree[rt<<1|1] += (LL)(end - mid) * lazy[rt];
儿子的更新用的是爸爸给的lazy[rt]去乘,而lazy[rt<<1]和lazy[rt<<1|1]是留给他们各自的儿子的。
因为上面那题的是覆盖,所以没有这个问题,这题就要强调一下。
#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include <queue>
using namespace std;
const int maxn = 100005;
const int oo = 0xfffffff;
#define L_CHILD rt<<1, begin, mid
#define R_CHILD rt<<1|1, mid + 1, end
#define LL long long
LL segTree[maxn<<2];
LL lazy[maxn<<2];
int n;
void pushUp(int rt) {
segTree[rt] = segTree[rt<<1] + segTree[rt<<1|1];
}
void pushDown(int rt, int begin, int end) {
if(lazy[rt] != 0) {
int mid = begin + end >> 1;
lazy[rt<<1] += lazy[rt];
lazy[rt<<1|1] += lazy[rt];
segTree[rt<<1] += (LL)(mid - begin + 1) * lazy[rt];
segTree[rt<<1|1] += (LL)(end - mid) * lazy[rt];
lazy[rt] = 0;
}
}
void build(int rt, int begin, int end) {
lazy[rt] = 0;
if(begin == end) {
scanf("%I64d", segTree + rt);
return ;
}
int mid = begin + end >> 1;
build(L_CHILD);
build(R_CHILD);
pushUp(rt);
}
void update(int rt, int begin, int end, int left, int right, LL val) {
if(left > end || right < begin) {
return ;
}
if(left <= begin && end <= right) {
lazy[rt] += val;
segTree[rt] += val * (LL)(end - begin + 1);
return ;
}
pushDown(rt, begin, end);
int mid = begin + end >> 1;
update(L_CHILD, left, right, val);
update(R_CHILD, left, right, val);
pushUp(rt);
}
LL query(int rt, int begin, int end, int left, int right) {
if(left > end || right < begin) {
return 0;
}
if(left <= begin && end <= right) {
return segTree[rt];
}
pushDown(rt, begin, end);
int mid = begin + end >> 1;
return query(L_CHILD, left, right) + query(R_CHILD, left, right);
}
int main() {
// freopen("test.txt", "w", stdout);
int n, q, x, y;
LL val;
char ch;
scanf("%d%d", &n, &q);
build(1, 1, n);
while (q --) {
scanf(" %c%d%d", &ch, &x, &y);
if(ch == 'Q') {
printf("%I64d\n", query(1, 1, n, x, y));
}
else {
scanf("%I64d", &val);
update(1, 1, n, x, y, val);
}
}
return 0;
}