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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章