题意
对序列 a 进行两个操作,
1.输出区间 [ l ,r ] 的最大子段和;
2.将 a[[i] 的值改为 x ;
思路
线段树维护四个值,区间和 sum,包含该区间左端点的最大子段和 maxl,包含该区间右端点的最大子段和 maxr,该区间的最大字段和 mx;
线段树合并操作中,区间和等于两个子区间的区间和之和
tree[p].sum=tree[p<<1].sum+tree[p<<1|1].sum;
包含该区间左端点的最大子段和 maxl,为左儿子的 maxl 与右儿子的 sum + maxl 中的较大者
tree[p].maxl=max(tree[p<<1].maxl,tree[p<<1].sum+tree[p<<1|1].maxl);
包含该区间右端点的最大子段和 maxr 同理,为右儿子的 maxr 与左儿子的 sum + maxr 中的较大者
tree[p].maxr=max(tree[p<<1|1].maxr,tree[p<<1|1].sum+tree[p<<1].maxr);
该区间的最大字段和 mx,为左儿子的 mx ,右儿子的 mx 与左儿子的 maxr 与右儿子的 maxl 所拼接成的区间和中的较大者
tree[p].mx=max(max(tree[p<<1].mx,tree[p<<1|1].mx),tree[p<<1].maxr+tree[p<<1|1].maxl);
在查找操作中,不能直接返回区间最大字段和 mx 的值,因为最终结果可能由两个区间拼接而成,需要用到 maxl, maxr 等值,可返回结构体;
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct node{
int sum,maxl,maxr,mx;
}tree[500010<<2];
inline void pushup(int p){
tree[p].maxl=max(tree[p<<1].maxl,tree[p<<1].sum+tree[p<<1|1].maxl);
tree[p].maxr=max(tree[p<<1|1].maxr,tree[p<<1|1].sum+tree[p<<1].maxr);
tree[p].sum=tree[p<<1].sum+tree[p<<1|1].sum;
tree[p].mx=max(max(tree[p<<1].mx,tree[p<<1|1].mx),tree[p<<1].maxr+tree[p<<1|1].maxl);
}
void build(int p,int l,int r){
if(l==r){
cin>>tree[p].sum; tree[p].maxl=tree[p].maxr=tree[p].mx=tree[p].sum;
return ;
}
int mid=l+r>>1;
build(p<<1,l,mid);
build(p<<1|1,mid+1,r);
pushup(p);
}
void change(int p,int l,int r,int x,int k){
if(l==r){ tree[p].maxl=tree[p].maxr=tree[p].mx=tree[p].sum=k; return ;}
int mid=l+r>>1;
if(x<=mid) change(p<<1,l,mid,x,k);
else change(p<<1|1,mid+1,r,x,k);
pushup(p);
}
node find(int p,int l,int r,int x,int y){
if(x<=l&&r<=y) return tree[p];
int mid=l+r>>1;
node tmp1,tmp2,ans;
int xx=0,yy=0;
if(x<=mid){ tmp1=find(p<<1,l,mid,x,y); xx=1;}
if(y>mid){ tmp2=find(p<<1|1,mid+1,r,x,y); yy=1;}
if(xx&&yy){
ans.maxl=max(tmp1.maxl,tmp1.sum+tmp2.maxl);
ans.maxr=max(tmp2.maxr,tmp2.sum+tmp1.maxr);
ans.sum=tmp1.sum+tmp2.sum;
ans.mx=max(max(tmp1.mx,tmp2.mx),tmp1.maxr+tmp2.maxl);
}
else if(xx) ans=tmp1;
else if(yy) ans=tmp2;
return ans;
}
int main()
{
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n,m;
cin>>n>>m;
build(1,1,n);
int x,y,z;
while(m--){
cin>>z>>x>>y;
if(z==1){
if(x>y) swap(x,y);
node tmp=find(1,1,n,x,y);
cout<<tmp.mx<<"\n";
}
else change(1,1,n,x,y);
}
return 0;
}