CH4301 Can you answer on these queries 线段树维护最大连续子段和

题目描述
给定长度为N的数列A,以及M条指令,每条指令可能是以下两种之一:

1、“1 x y”,查询区间 [x,y] 中的最大连续子段和,即 maxx≤l≤r≤y{∑ri=lA[i]}。

2、“2 x y”,把 A[x] 改成 y。

对于每个查询指令,输出一个整数表示答案。

输入格式
第一行两个整数N,M。

第二行N个整数A[i]。

接下来M行每行3个整数k,x,y,k=1表示查询(此时如果x>y,请交换x,y),k=2表示修改。

输出格式
对于每个查询指令输出一个整数表示答案。

每个答案占一行。

数据范围
N≤500000,M≤100000

输入样例:
5 3
1 2 -3 4 5
1 2 3
2 2 -1
1 3 2
输出样例:
2
-1
思路

  • 用sum存区间和, lmax存左边的最大前缀和, rmax存右边的最大前缀和,dat存连续子序列的最大和

代码

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int inf = 0x3f3f3f3f;
const int N = 2000010;

struct node{
	int l, r, sum, lmax, rmax, value, dat;
}; 
node tree[N];
int a[N];
int n, m;
int x, y, z;

void init(node &t, int num)
{
	t.dat = t.sum = t.lmax = t.rmax = num;
}

void cacl(int node)
{
	tree[node].sum = tree[node * 2].sum + tree[node * 2 + 1].sum;
	tree[node].lmax = max(tree[node * 2].lmax, tree[node * 2].sum + tree[node * 2 + 1].lmax);
	tree[node].rmax = max(tree[node * 2 + 1].rmax, tree[node * 2 + 1].sum + tree[node * 2].rmax);
	tree[node].dat = max(max(tree[node * 2].dat, tree[node * 2 + 1].dat), tree[node * 2].rmax + tree[node * 2 + 1].lmax);
}

void build(int node, int l, int r)
{
	tree[node].l = l;
	tree[node].r = r;	
	if(l == r)
	{
	    init(tree[node], a[l]);
		return;
	}
	int mid = (l + r) >> 1;
	build(node * 2, l, mid);
	build(node * 2 + 1, mid + 1, r);
	cacl(node);
}

node get(int num)
{
	if(x <= tree[num].l && y >= tree[num].r)
		return tree[num];
	
	node a, b, c;
	init(a, -inf);
	init(b, -inf);
	int mid = (tree[num].l + tree[num].r) >> 1;
	c.sum = 0;
	if(x <= mid)
	{
		a = get(num * 2);
		c.sum += a.sum;
	}
	if(y > mid)
	{
		b = get(num * 2 + 1);
		c.sum += b.sum;
	}
	c.dat = max(max(a.dat, b.dat), a.rmax + b.lmax);
	c.lmax = max(a.lmax, b.lmax + a.sum);
	c.rmax = max(b.rmax, b.sum + a.rmax);
	if(x > mid)
		c.lmax = max(b.lmax, c.lmax);
	if(y <= mid)
		c.rmax = max(c.rmax, a.rmax);
	
	return c;
}

void updata(int num)
{
	if(tree[num].l == tree[num].r)
	{
		init(tree[num], y);
		return;
	}
	int mid = (tree[num].l + tree[num].r) >> 1;
	if(x <= mid)
		updata(num * 2);
	else 
		updata(num * 2 + 1);
	cacl(num);
	return;
}

int main()
{
	scanf("%d%d", &n, &m);
	for(int i = 1; i <= n; i++)
		scanf("%d", a + i);
	build(1, 1, n);
	while(m--)
	{
		scanf("%d%d%d", &z, &x, &y);
		if(z == 1)
		{
			if(x > y)
				swap(x, y);
			printf("%d\n", get(1).dat);
		}			
		else
		 updata(1);
	}
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值