线段树的模板题
题目链接:https://www.luogu.org/problemnew/show/P3372
update区间修改,query区间求和
#include <iostream>
#include <cstdio>
#include <algorithm>
#define ll long long
#define lson left, mid, rt<<1
#define rson mid+1, right, rt<<1|1
using namespace std;
const int maxn = ;
ll n, m, ans[maxn<<],lazy[maxn<<],tot=,re[maxn<<];
void PushUP(ll rt)
{
ans[rt] = ans[rt<<] + ans[rt<<|];
}
void build(ll left, ll right, ll rt)
{
if(left == right)
{
cin>>ans[rt];
return;
}
ll mid = (left + right)>>;
build(lson);
build(rson);
PushUP(rt);
} void PushDOWN(ll rt, ll mid, ll left, ll right)
{
if(lazy[rt])
{
lazy[rt<<]+=lazy[rt];
lazy[rt<<|]+=lazy[rt];
ans[rt<<]+=(mid-left+)*lazy[rt];
ans[rt<<|]+=(right-mid)*lazy[rt];
lazy[rt]=;
}
}
ll query(ll l, ll r, ll left, ll right, ll rt)
{
ll res = ;
if(l<=left&&r>=right)
{
return ans[rt];
}
ll mid = (left + right)>>;
PushDOWN(rt,mid,left,right);
if(l<=mid) res += query(l,r,lson);
if(r>mid) res += query(l,r,rson);
return res;
}
void update(ll l, ll r, ll add, ll left, ll right, ll rt)
{
if(l<=left&&r>=right)
{
lazy[rt]+=add;
ans[rt]+=add*(right-left+);
return;
}
ll mid = (left+right)>>;
PushDOWN(rt,mid,left,right);
if(l<=mid) update(l,r,add,lson);
if(r>mid) update(l,r,add,rson);
PushUP(rt);
} int main()
{
cin.sync_with_stdio(false);
cin>>n>>m;
ll p,x,y,k;
build(,n,);
while(m--)
{
cin>>p;
if(p==)
{
cin>>x>>y>>k; update(x,y,k,,n,);
}
if(p==)
{
tot++;
cin>>x>>y; cout<<query(x,y,,n,);
}
}
return ;
}