Description
You are given a sequence A of N (N <= 50000) integers between -10000 and 10000. On this sequence you have to apply M (M <= 50000) operations:
modify the i-th element in the sequence or for given x y print max{Ai + Ai+1 + … + Aj | x<=i<=j<=y }.
Input
The first line of input contains an integer N. The following line contains N integers, representing the sequence A1…AN.
The third line contains an integer M. The next M lines contain the operations in following form:
0 x y: modify Ax into y (|y|<=10000).
1 x y: print max{Ai + Ai+1 + … + Aj | x<=i<=j<=y }.
Output
For each query, print an integer as the problem required.
Sample Input
4
1 2 3 4
4
1 1 3
0 3 -3
1 2 4
1 3 3
Sample Output
6
4
-3
题目大意:
给定一个n元素数组。
有m次操作,操作有两种:
1、0 x y:将Ax的值改为y
2、1 x y:输出区间 [ x , y ] 的最大连续子段和
核心思想:
线段树区间最大连续子段和模板题。
线段树维护区间的四个值:
1、最大连续子段和
2、最大左连续子段和
3、最大右连续子段和
4、区间和
pushup函数写法见代码。
代码如下:
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=5e4+20;
int n;
struct node{
int l,r,lmax,rmax,x,sum;
}tr[N<<2];
void pushup(int m)
{
tr[m].sum=tr[m<<1].sum+tr[m<<1|1].sum;
tr[m].x=max(tr[m<<1].rmax+tr[m<<1|1].lmax,max(tr[m<<1].x,tr[m<<1|1].x));
tr[m].lmax=max(tr[m<<1].lmax,tr[m<<1].sum+tr[m<<1|1].lmax);
tr[m].rmax=max(tr[m<<1|1].rmax,tr[m<<1|1].sum+tr[m<<1].rmax);
return;
}
void build(int m,int l,int r)
{
tr[m].l=l;
tr[m].r=r;
if(l==r)
{
scanf("%d",&tr[m].sum);
tr[m].x=tr[m].lmax=tr[m].rmax=tr[m].sum;
return;
}
int mid=(l+r)>>1;
build(m<<1,l,mid);
build(m<<1|1,mid+1,r);
pushup(m);
return;
}
void update(int m,int x,int y)
{
if(tr[m].l==x&&tr[m].r==x)
{
tr[m].sum=tr[m].x=tr[m].lmax=tr[m].rmax=y;
return;
}
int mid=(tr[m].l+tr[m].r)>>1;
if(x<=mid)
update(m<<1,x,y);
else
update(m<<1|1,x,y);
pushup(m);
return;
}
node query(int m,int l,int r)
{
if(tr[m].l==l&&tr[m].r==r)
return tr[m];
int mid=(tr[m].l+tr[m].r)>>1;
if(r<=mid)
return query(m<<1,l,r);
if(l>mid)
return query(m<<1|1,l,r);
node a=query(m<<1,l,mid);
node b=query(m<<1|1,mid+1,r);
node c;
c.sum=a.sum+b.sum;
c.x=max(a.rmax+b.lmax,max(a.x,b.x));
c.lmax=max(a.lmax,a.sum+b.lmax);
c.rmax=max(b.rmax,a.rmax+b.sum);
return c;
}
int main()
{
scanf("%d",&n);
build(1,1,n);
int m,q,x,y;
scanf("%d",&m);
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&q,&x,&y);
if(q)
printf("%d\n",query(1,x,y).x);
else
update(1,x,y);
}
return 0;
}