add为懒标记,表示区间内的数都要加上一个add,查询、修改的时候要更新add,先下传再做操作。
#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for(int i = a;i<n;i++)
#define per(i,a,n) for(int i = n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define eb emplace_back
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
#define yes cout<<"YES"<<'\n';
#define no cout<<"NO"<<'\n';
#define endl '\n';
#define R register
typedef vector<int> VI;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef double db;
mt19937 mrand(random_device{}());
const ll MOD=1000000007;
int rnd(int x) {return mrand() % x;}
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;};
ll lcm(int a,int b){return a*b/gcd(a,b);};
const int N=100010;
struct node{
int l,r;
ll sum,add;
}tr[N*4];
int a[N];
int n,m;
void pushup(int u){
tr[u].sum=tr[u<<1].sum+tr[u<<1].add*(tr[u<<1].r-tr[u<<1].l+1)+tr[u<<1|1].sum+tr[u<<1|1].add*(tr[u<<1|1].r-tr[u<<1|1].l+1);
}
void pushdown(int u){
if(tr[u].add){
tr[u].sum+=(tr[u].r+tr[u].l-1)*tr[u].add;
tr[u<<1].add+=tr[u].add;
tr[u<<1|1].add+=tr[u].add;
tr[u].add=0;
}
}
void build(int u,int l,int r){
tr[u]={l,r,0,0};
if(l==r){
tr[u].sum=a[l];
return;
}
int m=(l+r)>>1;
build(u<<1,l,m);
build(u<<1|1,m+1,r);
pushup(u);
}
void modify(int u,int l,int r,ll k){
if(l<=tr[u].l&&tr[u].r<=r){
tr[u].add+=k;
return;
}
pushdown(u);
int m=(tr[u].l+tr[u].r)>>1;
if(l<=m) modify(u<<1,l,r,k);
if(r>m) modify(u<<1|1,l,r,k);
pushup(u);
}
ll query(int u,int l,int r){
if(l<=tr[u].l&&tr[u].r<=r){
return tr[u].sum+tr[u].add*(tr[u].r-tr[u].l+1);
}
pushdown(u);
int m=(tr[u].l+tr[u].r)>>1;
ll sum=0;
if(l<=m) sum+=query(u<<1,l,r);
if(r>m) sum+=query(u<<1|1,l,r);
pushup(u);
return sum;
}
int main(){
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n>>m;
rep(i,1,n+1) cin>>a[i];
build(1,1,n);
while(m--){
char op;
int l,r;
ll d;
cin>>op>>l>>r;
if(op=='Q'){
cout<<query(1,l,r)<<endl;
}else{
cin>>d;
modify(1,l,r,d);
}
}
return 0;
}