此题以洛谷 P3372 线段树1 为例
主要是记录模板,就不多加解释
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
struct arr{
int l,r,tag;ll sum;
}tree[500000];
int n,m,i,u;
inline int read(){
int x=0,w=1;char ch=0;
while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
if(ch=='-') w=-1,ch=getchar();
while(ch>='0'&&ch<='9')x=x*10+ch-48,ch=getchar();
return x*w;
}
void build(ll p,ll l,ll r){
tree[p].l=l;tree[p].r=r;
if(l!=r) {
int m=(l+r)>>1;
build(p<<1,l,m);
build((p<<1)+1,m+1,r);
}
}
inline void push_down(ll p){
if(tree[p].tag==0) return ;
tree[p<<1].sum+=tree[p].tag*(tree[p<<1].r-tree[p<<1].l+1);
tree[(p<<1)+1].sum+=tree[p].tag*(tree[(p<<1)+1].r-tree[(p<<1)+1].l+1);
tree[p<<1].tag+=tree[p].tag;
tree[(p<<1)+1].tag+=tree[p].tag;
tree[p].tag=0;
}
void change(ll p,ll l,ll r,ll data){
if(tree[p].l==l&&tree[p].r==r) {
tree[p].sum+=(r-l+1)*data;tree[p].tag+=data; return;
}
push_down(p);
int m=(tree[p].l+tree[p].r)>>1;
if(r<=m) change(p<<1,l,r,data);
else if(l>m) change((p<<1)+1,l,r,data);
else change(p<<1,l,m,data),change((p<<1)+1,m+1,r,data);
tree[p].sum=tree[p<<1].sum+tree[(p<<1)+1].sum;
}
ll getsum(ll p,ll l,ll r){
if(tree[p].l==l&&tree[p].r==r) return tree[p].sum;
push_down(p);
int m=(tree[p].l+tree[p].r)>>1;
if(r<=m) return getsum(p<<1,l,r);
else if(l>m) return getsum((p<<1)+1,l,r);
else return getsum(p<<1,l,m)+getsum((p<<1)+1,m+1,r);
}
int main(){
n=read();m=read();
build(1,1,n);
for(register int i=1;i<=n;i++) { int x=read();change(1,i,i,x); }
for(register int i=1;i<=m;i++){
int u=read();
if(u==1) { int x=read(),y=read(),k=read();change(1,x,y,k); }
if(u==2) { int x=read(),y=read();printf("%lld\n",getsum(1,x,y)); }
}
}