题意
n个数m个操作
1~n的值
两种操作:
“Q a b ”查询区间[a,b]值的和
“C c a b”区间[a,b]每个值加c
输出每次查询的值
代码
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <map>
#include <vector>
#include <string.h>
#include <string>
#include <queue>
#include <set>
//ios_base::sync_with_stdio(false);
//#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
typedef long long ll;
const int N = 1e5+10;
ll sum[N<<2],add[N<<2];
struct Node {
int l,r;
int mid() {
return (l+r)>>1;
}
}tree[N<<2];
void PushUp(int rt) //回溯时把左右孩子的值带上来
{
sum[rt] = sum[rt<<1]+sum[rt<<1|1];
}
void PushDown(int rt, int m) //只传递给左右孩子
{
//参数m是区间的长度
if(add[rt]) { //当有延迟标记时
add[rt<<1] += add[rt];
add[rt<<1|1] += add[rt];
sum[rt<<1] +=add[rt]*(m-(m>>1));
sum[rt<<1|1] += add[rt]*(m>>1);
add[rt] = 0;//更新完后取消标记
}
}
void build(int l, int r, int rt)
{
tree[rt].l = l;
tree[rt].r = r;
add[rt] = 0;
if(l == r) {
scanf("%I64d",&sum[rt]);//小技巧,输入叶子的值
return;
}
int m = tree[rt].mid();
build(lson);
build(rson);
PushUp(rt);
}
void update(int c, int l, int r, int rt)
{
if(tree[rt].l == l && tree[rt].r == r) {
add[rt] += c;
sum[rt] += (ll)c*(r-l+1);
return;
}
if(tree[rt].l == tree[rt].r) return;
PushDown(rt,tree[rt].r-tree[rt].l+1);
int m = tree[rt].mid();
if(r <= m) update(c,l,r,rt<<1);
else if(l > m) update(c,l,r,rt<<1|1);
else {
update(c,l,m,rt<<1);
update(c,m+1,r,rt<<1|1);
}
PushUp(rt);
}
ll query(int l, int r, int rt)
{
if(l == tree[rt].l&&r == tree[rt].r) return sum[rt];
PushDown(rt,tree[rt].r-tree[rt].l+1);
int m = tree[rt].mid();
ll res = 0;
if(r <= m) res+=query(l, r, rt<<1);
else if(l > m) res+=query(l, r, rt <<1|1);
else {
res+=query(lson);
res+=query(rson);
}
return res;
}
int main()
{
int n, m;
while(scanf("%d%d",&n,&m)!=EOF)
{
build(1,n,1);
while(m--)
{
char ch[2];
scanf("%s",ch);
int a, b, c;
if(ch[0] == 'Q') {
scanf("%d%d",&a,&b);
printf("%I64d\n",query(a,b,1));
}
else {
scanf("%d%d%d",&a,&b,&c);
update(c,a,b,1);
}
}
}
return 0;
}