每一条边都记录这条边的总和 和这条边的单位增加量
#include<iostream> #include<cstdio> using namespace std; #define max1 100005 struct node { long long l,r,s,snum;///s单位表示增加数,snum表示总和 }tree[max1*4]; long long a[max1]; long long ans,cou; void build(long long i,long long l,long long r) { tree[i].l=l; tree[i].r=r;tree[i].s=0; if(tree[i].l==tree[i].r) { tree[i].snum=a[tree[i].l]; return ; } long long mid=(tree[i].l+tree[i].r)>>1; build(i*2,l,mid); build(i*2+1,mid+1,r); tree[i].snum=tree[i*2].snum+tree[i*2+1].snum; } void updata(long long i,long long l,long long r,long long s) { if(tree[i].l==l&&tree[i].r==r) { tree[i].snum+=(r-l+1)*s; tree[i].s+=s; return ; } else {///讲增加倍数向下传 tree[i*2].s+=tree[i].s; tree[i*2].snum=(tree[i*2].r-tree[i*2].l+1)*tree[i].s+tree[i*2].snum; tree[i*2+1].s+=tree[i].s; tree[i*2+1].snum=(tree[i*2+1].r-tree[i*2+1].l+1)*tree[i].s+tree[i*2+1].snum; tree[i].s=0; } long long mid=(tree[i].l+tree[i].r)>>1; if(mid>=r) updata(i*2,l,r,s); else if(mid<l) updata(i*2+1,l,r,s); else{ updata(i*2,l,mid,s); updata(i*2+1,mid+1,r,s); } tree[i].snum=tree[i*2].snum+tree[i*2+1].snum;///向上更新和 } void querry(long long i,long long l,long long r,long long m) { if(tree[i].l==l&&tree[i].r==r) { ans+=(r-l+1)*m+tree[i].snum; return ; } long long mid=(tree[i].l+tree[i].r)>>1; if(mid>=r) querry(i*2,l,r,m+tree[i].s); else if(mid<l) querry(i*2+1,l,r,m+tree[i].s); else{ querry(i*2,l,mid,m+tree[i].s); querry(i*2+1,mid+1,r,m+tree[i].s); } return ; } int main() { long long n,m,x,y,z; char s[2]; while(~scanf("%lld%lld",&n,&m)) { for(int i=1;i<=n;i++) scanf("%lld",&a[i]); build(1,1,n); while(m--) { scanf("%s",s); if(s[0]=='Q'){ ans=0;cou=0; scanf("%lld%lld",&x,&y); querry(1,x,y,0); printf("%lld\n",ans); } else{ scanf("%lld%lld%lld",&x,&y,&z); updata(1,x,y,z); } } } return 0; }