SPOJ GSS3-区间最大连续子段和-Can you answer these queries III

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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值