描述
给定长度为N的数列A,以及M条指令 (N≤500000, M≤100000),每条指令可能是以下两种之一:
“2 x y”,把 A[x] 改成 y。
“1 x y”,查询区间 [x,y] 中的最大连续子段和,即 max(x≤l≤r≤y) { ∑(i=l~r) A[i] }。
对于每个询问,输出一个整数表示答案。
输入格式
第一行两个整数N,M
第二行N个整数Ai
接下来M行每行3个整数k,x,y,k=1表示查询(此时如果x>y,请交换x,y),k=2表示修改
输出格式
对于每个询问输出一个整数表示答案。
样例输入
5 3 1 2 -3 4 5 1 2 3 2 2 -1 1 3 2
样例输出
2 -1
数据范围与约定
- 对于100%的数据: N≤500000, M≤100000, |Ai|<=1000
最大子段和
合并时:
a,b区间合并成t的时候
t.sum=a.sum+b.sum;
t.lmax=max(a.lmax,a.sum +b.lmax);
t.rmax=max(b.rmax,b.sum+a.rmax);
t.smax=max(max(a.smax,b.smax),a.rmax+b.lmax);
自己在纸上画个树就能明白。
#include<bits/stdc++.h>
using namespace std;
const int M =500000+7;
int a[M];
struct node
{
int sum,lmax,rmax,smax;
}st[M<<2];
void pushup(int rt)
{
st[rt].sum=st[rt<<1].sum+st[rt<<1|1].sum;
st[rt].lmax=max(st[rt<<1].lmax,st[rt<<1].sum+st[rt<<1|1].lmax);
st[rt].rmax=max(st[rt<<1|1].rmax,st[rt<<1|1].sum+st[rt<<1].rmax);
st[rt].smax=max(max(st[rt<<1].smax,st[rt<<1|1].smax),st[rt<<1].rmax+st[rt<<1|1].lmax);
}
void merge(int l,int r)
{
}
void build(int l,int r,int rt)
{
if(l==r)
{
st[rt].lmax=a[l];
st[rt].rmax=a[l];
st[rt].smax=a[l];
st[rt].sum=a[l];
return ;
}
int mid=(l+r)/2;
build(l,mid,rt<<1);
build(mid+1,r,rt<<1|1);
pushup(rt);
}
void update(int l,int r,int rt,int x,int y)
{
if(l==r)
{
st[rt].lmax=y;
st[rt].rmax=y;
st[rt].smax=y;
st[rt].sum=y;
return ;
}
int mid=(l+r)/2;
if(x<=mid)
update(l,mid,rt<<1,x,y);
else
update(mid+1,r,rt<<1|1,x,y);
pushup(rt);
}
node query(int l,int r,int rt,int x,int y)
{
//printf("%d %d %d %d %d\n",rt,l,r,x,y);
if(x<=l&&r<=y)
{
return st[rt];
}
int mid=(l+r)/2;
int ma=0;
if(y<=mid) return query(l,mid,rt<<1,x,y);
else if(mid<x) return query(mid+1,r,rt<<1|1,x,y);
else
{
node a=query(l,mid,rt<<1,x,y);
node b=query(mid+1,r,rt<<1|1,x,y);
node t;
t.lmax=max(a.lmax,a.sum +b.lmax);
t.rmax=max(b.rmax,b.sum+a.rmax);
t.smax=max(max(a.smax,b.smax),a.rmax+b.lmax);
return t;
}
}
int main()
{
int n,m,k,x,y;
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++)
cin>>a[i];
build(1,n,1);
for(int i=1;i<=m;i++)
{
cin>>k>>x>>y;
if(k==1)
{
if(x>y)swap(x,y);
cout<<query(1,n,1,x,y).smax<<endl;
}
else
{
update(1,n,1,x,y);
}
}
return 0;
}