链接
题目描述
给出数列a,现在有两种操作
1.给出a,b,求区间a~b的最大子区间和
2.给出a,b,把第a个数改成b
样例输入
5 3
1 2 -3 4 5
1 2 3
2 2 -1
1 2 3
样例输出
2
-1
思路
线段树
我们弄一个结构体tree[i]
其包含四个值
1.sum记录区间和
2.mx记录最大子区间和
3.lm记录包含区间左端点的最大区间和
4.rm记录包含区间右端点的最大区间和
那就很明朗了,最后的答案就是tree[a~b].mx
考虑转移
sum直接相加
mx可以分类讨论,一种是只有一边(两种情况),另一种就是左边的rm + 右边的lm
lm就左边lm或是左边sum+右边lm
rm就右边rm或右边sum+左边lm
也就是说
{
f
a
.
s
u
m
=
l
s
o
n
.
s
u
m
+
r
s
o
n
.
s
u
m
f
a
.
m
x
=
m
a
x
(
l
s
o
n
.
r
m
+
r
s
o
n
.
l
m
,
m
a
x
(
l
s
o
n
.
m
x
,
r
s
o
n
.
m
x
)
)
f
a
.
l
m
=
m
a
x
(
l
s
o
n
.
l
m
,
l
s
o
n
.
s
u
m
+
r
s
o
n
.
l
m
)
f
a
.
r
m
=
m
a
x
(
r
s
o
n
.
r
m
,
r
s
o
n
.
s
u
m
+
l
s
o
n
.
r
m
)
\left\{\begin{matrix} fa.sum = lson.sum+rson.sum\\ fa.mx = max(lson.rm + rson.lm, max(lson.mx, rson.mx))\\ fa.lm = max(lson.lm, lson.sum + rson.lm)\\ fa.rm = max(rson.rm, rson.sum + lson.rm) \end{matrix}\right.
⎩⎪⎪⎨⎪⎪⎧fa.sum=lson.sum+rson.sumfa.mx=max(lson.rm+rson.lm,max(lson.mx,rson.mx))fa.lm=max(lson.lm,lson.sum+rson.lm)fa.rm=max(rson.rm,rson.sum+lson.rm)
至于询问,那我们可以把询问操作当作一个结构体进去运算
最后输出求出的点的mx就可以了
代码
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#define ll long long
using namespace std;
struct tree
{
ll sum, lm, rm, mx;
}tr[2000001];
int n, m, a[500005];
ll read()
{
ll re = 0, pp = 1;
char c = getchar();
while(c < '0' || c > '9') {
if(c == '-') pp = -1;
c = getchar();
}
while(c >= '0' && c <= '9') {
re = re * 10 + c - 48;
c = getchar();
}
return re * pp;
}//快读(一开始还打错了,不愧是我
tree add(tree i, tree j)
{
tree c;
c.sum = i.sum + j.sum;
c.lm = max(i.lm, i.sum + j.lm);
c.rm = max(j.rm, j.sum + i.rm);
c.mx = max(i.rm + j.lm, max(j.mx, i.mx));
return c;
}//同思路中的式子
void build(int k, int l, int r)
{
if(l == r)
{
tr[k].sum = a[l];
tr[k].lm = a[l];
tr[k].rm = a[l];
tr[k].mx = a[l];
return;
}
int mid = (l + r) / 2;
build(k * 2, l, mid);
build(k * 2 + 1, mid + 1, r);
tr[k] = add(tr[k * 2], tr[k * 2 + 1]);
}
void change(int k, int l, int r, int x, ll v)
{
if(l == r)
{
tr[k].sum = v;
tr[k].lm = v;
tr[k].rm = v;
tr[k].mx = v;
return;
}
int mid = (l + r) / 2;
if(x <= mid) change(k * 2, l, mid, x, v);
if(mid + 1 <= x) change(k * 2 + 1, mid + 1, r, x, v);
tr[k] = add(tr[k * 2], tr[k * 2 + 1]);
}
tree ask(int k, int l, int r, int L, int R)
{
if(L <= l && r <= R) return tr[k];
int mid = (l + r) / 2;
if(R <= mid) return ask(k * 2, l, mid, L, R);
if(mid + 1 <= L) return ask(k * 2 + 1, mid + 1, r, L, R);
tree b, c, d;
b = ask(k * 2, l, mid, L, R);
c = ask(k * 2 + 1, mid + 1, r, L, R);
d = add(b, c);
return d;
}
int main()
{
n = read(); m = read();
for(int i = 1; i <= n; ++i)
a[i] = read();
build(1, 1, n);
for(int i = 1; i <= m; ++i)
{
int k, x, y;
k = read();
if(k == 1) {
x = read(); y = read();
if(x > y) {
int tot = x;
x = y;
y = tot;
}
tree tt = ask(1, 1, n, x, y);
printf("%lld\n", tt.mx);
}
else {
x = read(); y = read();
a[x] = y;
change(1, 1, n, x, y);
}
}
return 0;
}