今天默了一遍线段树模板,发现连样例都过不去了,请各位大佬看看。
#include<cstdio>
#include<iostream>
using namespace std;
const int N=1e5+5;
int a[N];
struct Node{
int l,r;
int d,mark;
}t[N*4];
void pushdown(int root)
{
if(t[root].mark)
{
int l=root*2,r=root*2+1;
t[l].d+=t[root].mark;
t[r].d+=t[root].mark;
t[l].mark+=t[root].mark;
t[r].mark+=t[root].mark;
t[root].mark=0;
}
}
void build(int root,int l,int r)
{
t[root].l=l,t[root].r=r;
if(l==r)
{
t[root].d=a[l];
return;
}
int mid=(l+r)>>1;
build(root*2,l,mid);
build(root*2+1,mid+1,r);
t[root].d=t[root*2].d+t[root*2+1].d;
}
void modify(int root,int l,int r,int v)
{
if(t[root].l>=l&&t[root].r<=r)
{
t[root].mark+=v;
t[root].d+=v;
return;
}
pushdown(root);
int mid=(t[root].l+t[root].r)>>1;
if(l<=mid)modify(root*2,l,r,v);
if(r>mid)modify(root*2+1,l,r,v);
t[root].d=t[root*2].d+t[root*2+1].d;
}
int query(int root,int l,int r)
{
if(t[root].l>=l&&t[root].r<=r)
return t[root].d;
pushdown(root);
int ans=0;
int mid=(t[root].l+t[root].r)>>1;
if(l<=mid)ans+=query(root*2,l,r);
if(r>mid)ans+=query(root*2+1,l,r);
return ans;
}
int n,q;
int main()
{
cin>>n>>q;
for(int i=1;i<=n;i++)cin>>a[i];
build(1,1,n);
int cmd,l,r,v;
for(int i=1;i<=q;i++)
{
cin>>cmd>>l>>r;
if(cmd==1)
{
cin>>v;
modify(1,l,r,v);
}
else cout<<query(1,l,r)<<endl;
}
}