此模板基于codevs 1082 线段树练习3
我就是神奇的传送门
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define sz(x) (tree[x].r-tree[x].l+1)
typedef long long LL;
using namespace std;
const int maxn=200000+15;
LL xl[maxn];
LL n,a,b,x,q,z,t,y;
struct haha
{
LL l,r,add,sum;
}tree[maxn<<2];
void update(LL p)
{
tree[p].sum=tree[L(p)].sum+tree[R(p)].sum;
return;
}
void build(LL l,LL r,LL p)
{
tree[p].l=l;
tree[p].r=r;
if(l==r)
{
tree[p].sum=xl[l];
return;
}
LL mid=(tree[p].l+tree[p].r)>>1;
build(l,mid,L(p));
build(mid+1,r,R(p));
update(p);
return;
}
void spread(LL p)
{
if(!tree[p].add)
return;
tree[L(p)].add+=tree[p].add;
tree[R(p)].add+=tree[p].add;
tree[L(p)].sum+=tree[p].add*sz(L(p));
tree[R(p)].sum+=tree[p].add*sz(R(p));
tree[p].add=0;
update(p);
return;
}
void change(LL l,LL r,LL p,LL v)
{
if(l<=tree[p].l&&tree[p].r<=r)
{
tree[p].add+=v;
tree[p].sum+=sz(p)*v;
return;
}
spread(p);
LL mid=(tree[p].l+tree[p].r)>>1;
if(l<=mid)
change(l,r,L(p),v);
if(mid<r)
change(l,r,R(p),v);
update(p);
return;
}
LL ask(LL l,LL r,LL p)
{
if(l<=tree[p].l&&tree[p].r<=r)
{
return tree[p].sum;
}
spread(p);
LL mid=(tree[p].l+tree[p].r)>>1;
LL ans=0;
if(l<=mid)
ans+=ask(l,r,L(p));
if(mid<r)
ans+=ask(l,r,R(p));
update(p);
return ans;
}
int main()
{
memset(xl,0,sizeof(xl));
scanf("%lld",&n);
for(LL i=1;i<=n;i++)
{
scanf("%lld",&xl[i]);
}
build(1,n,1);
scanf("%lld",&q);
for(LL i=1;i<=q;i++)
{
scanf("%lld",&t);
if(t==1)
{
scanf("%lld%lld%lld",&a,&b,&x);
change(a,b,1,x);
}
else if(t==2)
{
scanf("%lld%lld",&y,&z);
printf("%lld\n",ask(y,z,1));
}
}
return 0;
}
纯模板 不解释…