题目链接:https://cn.vjudge.net/problem/POJ-3468
题意:给你n个数,m个查询
有两种查询,一种是区间修改,给一个区间每个数都加上c
一种是区间查询,求这个区间的和。
需要lazy标记
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
const int maxn = 1e6 + 5;
#define ll long long
struct node
{
ll lazy, val, cnt;
}e[maxn];
ll a[maxn];
void pushup(int cur){
e[cur].val = e[cur<<1].val + e[cur<<1|1].val;
e[cur].cnt = e[cur<<1].cnt + e[cur<<1|1].cnt;
}
void build(int l, int r, int cur) {
e[cur].lazy= 0;
if(l == r) {
e[cur].cnt = 1;
e[cur].val = a[l];
return ;
}
int m = l + r >> 1;
build(l, m, cur<<1);
build(m + 1, r, cur<<1|1);
pushup(cur);
}
void pushdown(int cur) {
if(e[cur].lazy != 0) {
e[cur<<1].lazy += e[cur].lazy;
e[cur<<1|1].lazy += e[cur].lazy;
e[cur<<1].val += e[cur].lazy * e[cur<<1].cnt;
e[cur<<1|1].val += e[cur].lazy * e[cur<<1|1].cnt;
e[cur].lazy = 0;
}
}
void update(int cl, int cr, int cur, int l, int r, ll val) {
if(l <= cl && cr <= r)
{
e[cur].val += val * e[cur].cnt;
e[cur].lazy += val;
return ;
}
pushdown(cur);
int m = cl + cr >> 1;
if(l <= m)update(cl, m, cur<<1, l, r, val);
if(m < r)update(m + 1, cr, cur<<1|1, l, r, val);
pushup(cur);
}
ll query(int cl, int cr, int cur, int l, int r) {
if(l <= cl && cr <= r)
return e[cur].val;
pushdown(cur);
ll ans = 0;
int m = cl + cr >> 1;
if(l <= m) ans += query(cl, m, cur << 1, l, r);
if(m < r) ans += query(m + 1, cr, cur << 1 | 1, l, r);
return ans;
}
int main()
{
int n, l, r, m;
while(~scanf("%d%d", &n, &m)) {
for(int i = 1; i <= n; i++) {
scanf("%lld", &a[i]);
}
build(1, n, 1);
char s[2];
while(m--) {
scanf("%s%d%d", s, &l, &r);
if(s[0] == 'Q') {
printf("%lld\n", query(1, n, 1, l, r));
}
else {
ll c;
scanf("%lld", &c);
update(1, n, 1, l, r, c);
}
}
}
return 0;
}