题目地址
线段树模板加维护。
在build 和 change 中要维护一些东西。
区间和sum,区间的最大连续子段和data,靠左最大连续区间和lmax和靠右最大连续和rmax.
怎么维护:
p = 父节点,l = 左节点,r = 右节点。
p的sum =l的sum + r的sum.
p靠左最大连续区间和 lmax = max(l的lmax,l的sum+r的lmax).
同理 p靠右的最大连续区间和 rmax = max(r的rmax,r的sum+l的rmax)
还有data
p的data = max(max(l的data,r的data),l的rmax + r 的 lmax)
应该可以理解。
主要在ask的时候,我们怎么提取数据。
对于给出区间,不一定恰好是我们分得的区间。
我们返回结构体,再类似于上面几个处理,就可以得到答案了。也不会把原来构建的线段树更改。
注意初始化还有不要define int long long .
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#include<bits/stdc++.h>
//#define int long long
using namespace std;
typedef pair<int,int> pii;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const double eps = 1e-4;
const int mod = 998244353;
const int N = 5e5+10;
int a[N];
struct SegmentTree{
int l,r,sum;
int data,lmax,rmax;
SegmentTree(){
l = r = sum = 0;
data = lmax = rmax = -INF;
}
}t[N*4];
void f(int p){
t[p].sum = t[p*2].sum + t[p*2+1].sum;
t[p].lmax = max(t[p*2].lmax,t[p*2].sum+t[p*2+1].lmax);
t[p].rmax = max(t[p*2+1].rmax,t[p*2+1].sum+t[p*2].rmax);
t[p].data = max(max(t[p*2].data,t[p*2+1].data),t[p*2].rmax+t[p*2+1].lmax);
}
void build(int p,int l,int r){
t[p].l = l,t[p].r = r;
if(l == r){
t[p].sum = t[p].data = a[l];
t[p].lmax = t[p].rmax = a[l];
return ;
}
int mid = (l+r)/2;
build(p*2,l,mid);
build(p*2+1,mid+1,r);
f(p);
}
void change(int p,int x,int v){
if(t[p].l == t[p].r){
t[p].sum = t[p].data = v;
t[p].lmax = t[p].rmax = v;
return ;
}
int mid = (t[p].l+t[p].r)/2;
if(x <= mid) change(p*2,x,v);
else change(p*2+1,x,v);
f(p);
}
SegmentTree ask(int p,int l,int r){
if(l <= t[p].l && r >= t[p].r) return t[p];
int mid = (t[p].l + t[p].r) / 2;
SegmentTree a,b,res;
if(l <= mid){
a = ask(p*2,l,r);
res.sum += a.sum;
}
if(r > mid){
b = ask(p*2+1,l,r);
res.sum += b.sum;
}
res.lmax = max(a.lmax,a.sum+b.lmax);
res.rmax = max(b.rmax,b.sum+a.rmax);
res.data = max(max(a.data,b.data),a.rmax+b.lmax);
return res;
}
signed main(){
IOS;
#ifdef ddgo
freopen("C:/Users/asus/Desktop/ddgoin.txt","r",stdin);
#endif
int n,q; cin>>n>>q;
for(int i=1;i<=n;i++) cin>>a[i];
build(1,1,n);
while(q --){
int a,b,c; cin>>a>>b>>c;
if(a == 1) cout<<ask(1,min(b,c),max(b,c)).data<<endl;
else change(1,b,c);
}
return 0;
}