洛谷 小白逛公园 线段树 最大子序列

以前的普通做法是O(N^3)做法,同时也不会更新,这里用了线段树 + 单点更新。

题目链接

思路

用线段树维护一个子序列,同时进行更新。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

#include <set>
#include <map>
#include <ctime>
#include <queue>
#include <cmath>
#include <stack>
#include <bitset>
#include <vector>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define eps 1e-8
#define lc k * 2
#define rc k * 2 + 1
#define pi acos(-1.0)
#define ll long long
#define ull unsigned long long
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 500005;
struct Node
{
int sum, max_sum, max_post, max_pre;
}tree[maxn * 4];
int a[maxn];
void pushup(int node)
{
int ls = node << 1;
int rs = node << 1|1;
tree[node].sum = tree[ls].sum + tree[rs].sum;
tree[node].max_post = max(tree[rs].max_post, tree[ls].max_post + tree[rs].sum);
tree[node].max_pre = max(tree[ls].max_pre, tree[ls].sum + tree[rs].max_pre);
tree[node].max_sum = max(tree[ls].max_sum, max(tree[rs].max_sum, tree[ls].max_post + tree[rs].max_pre));
}

void build(int node, int l, int r)
{
if(l == r)
{
tree[node].max_post = tree[node].max_pre = a[l];
tree[node].max_sum = tree[node].sum = a[l];
return;
}
int mid = (l + r) >> 1;
build(node << 1, l, mid);
build(node << 1|1, mid + 1, r);
pushup(node);
}

void update(int node, int l, int r, int pos, int k)
{
if(l == r && l == pos)
{
tree[node].max_post = tree[node].max_pre =
tree[node].max_sum = tree[node].sum = k;
return;
}
int mid = (l + r) >> 1;
if(pos <= mid)
update(node << 1, l, mid, pos, k);
else
update(node << 1|1, mid + 1, r, pos, k);
pushup(node);
}



Node query(int node, int l, int r, int ql, int qr)
{
if(ql <= l && qr >= r)
{
return tree[node];
}
int mid = (l + r) >> 1;
if(qr <= mid)
return query(node << 1, l, mid, ql, qr);
else if(ql > mid)
return query(node <<1|1, mid + 1, r, ql, qr);
else
{
Node ans, ls, rs;
ls = query(node << 1, l, mid, ql, qr);
rs = query(node <<1|1, mid + 1, r, ql, qr);
ans.sum = ls.sum + rs.sum;
ans.max_post = max(rs.max_post, ls.max_post + rs.sum);
ans.max_pre = max(ls.max_pre, ls.sum + rs.max_pre);
ans.max_sum = max(ls.max_sum, max(rs.max_sum, ls.max_post + rs.max_pre));
return ans;
}

}
int main()
{
int n, m, k, p, s;
scanf("%d %d",&n,&m);
for(int i = 1; i <= n; ++i)
scanf("%d",&a[i]);
build(1, 1, n);
for(int i = 1; i <= m; ++i)
{
scanf("%d%d%d",&k,&p,&s);
if(k == 1)
{
if(p > s) swap(p,s);
Node ans = query(1, 1, n, p, s);
cout << ans.max_sum << '\n';
}
else
{
update(1,1,n, p, s);
}
}
}