z_y_w_ @ 2024-05-19 15:02:33
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int MAXN=1e5+5;
struct Tree
{
ll l, r, num;
}tree[MAXN*2];
ll lazy[MAXN*2];
ll n, m;
ll a[MAXN];
void push_up(ll i)
{
tree[i].num=tree[i*2].num+tree[i*2+1].num;
}
void make(ll l, ll r, ll i)
{
lazy[i]=0;
tree[i].l=l;
tree[i].r=r;
if(l==r)
{
tree[i].num=a[l];
return;
}
ll mid=(l+r)/2;
make(l, mid, i*2);
make(mid+1, r, i*2+1);
push_up(i);
}
void push_down(ll i, ll l, ll r)
{
if(lazy[i]!=0)
{
lazy[i*2]+=lazy[i];
lazy[i*2+1]+=lazy[i];
ll mid=(l+r)/2;
tree[i*2].num+=lazy[i]*(mid-tree[i*2].l+1);
tree[i*2+1].num+=lazy[i]*(tree[i*2+1].r-mid);
lazy[i]=0;
}
}
void add(ll l, ll r, ll k, ll i)
{
if(tree[i].l>=l&&tree[i].r<=r)
{
tree[i].num+=k*(tree[i].r-tree[i].l+1);
lazy[i]+=k;
return;
}
push_down(i, tree[i].l, tree[i].r);
if(tree[i*2].r>=l)
{
add(l, r, k, i*2);
}
if(tree[i*2+1].l<=r)
{
add(l, r, k, i*2+1);
}
push_up(i);
}
ll search(ll l, ll r, ll i)
{
ll cnt=0;
if(tree[i].l>=l&&tree[i].r<=r)
{
return tree[i].num;
}
push_down(i, tree[i].l, tree[i].r);
if(l<=tree[i].r) cnt+=search(l, r, i*2);
if(tree[i].l<=r) cnt+=search(l, r, i*2+1);
return cnt;
}
int main()
{
cin>>n>>m;
for(ll i=1; i<=n; i++)
{
cin>>a[i];
}
make(1, n, 1);
while(m--)
{
ll a, b, c, d;
cin>>a>>b>>c;
if(a==1)
{
cin>>d;
add(b, c, d, 1);
}
else
{
cout<<search(b, c, 1);
}
}
}
by YQD_Q @ 2024-05-19 15:06:24
@z_yw 线段树开四倍大
tree[MAXN*2];
改成
tree[MAXN*4];
by YQD_Q @ 2024-05-19 15:07:38
求关
by masonxiong @ 2024-05-19 15:09:27
@z_yw 您写的不是动态开点线段树,应该开 4 倍空间,即 tree[MAXN * 4]