SP1043 GSS1 - Can you answer these queries I

题目描述

https://www.luogu.com.cn/problem/SP1043

Solution

我们只需要在线段树上维护最大子段和、最大前缀和、最大后缀和、区间总和

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
#include <iostream>
#include <cstdio>
#define maxn 50010
#define INF 1000000000
#define cS const Seg
using namespace std;

inline int max(int a, int b, int c) { return max(a, max(b, c)); }

int n, m, a[maxn];

#define lc i << 1
#define rc i << 1 | 1
struct Seg {
int l, r, s, v;

Seg() {}
Seg(int _l, int _r, int _s, int _v) { l = _l; r = _r; s = _s; v = _v; }
} T[maxn * 4];
inline Seg maintain(cS ls, cS rs) {
Seg o;
o.l = max(ls.s + rs.l, ls.l);
o.r = max(rs.s + ls.r, rs.r);
o.s = ls.s + rs.s;
o.v = max(ls.v, rs.v, ls.r + rs.l);
return o;
}

void build(int i, int l, int r) {
if (l == r) return (void) (T[i] = Seg(a[l], a[l], a[l], a[l]));
int m = l + r >> 1;
build(lc, l, m); build(rc, m + 1, r);
T[i] = maintain(T[lc], T[rc]);
}

void update(int i, int l, int r, int k, int v) {
if (l == r) return (void) (T[i] = Seg(a[l], a[l], a[l], a[l]));
int m = l + r >> 1;
if (k <= m) update(lc, l, m, k, v);
else update(rc, m + 1, r, k, v);
T[i] = maintain(T[lc], T[rc]);
}

Seg query(int i, int l, int r, int L, int R) {
if (l > R || r < L) return Seg(-INF, -INF, 0, -INF);
if (L <= l && r <= R) return T[i];
int m = l + r >> 1; Seg o, ls, rs;
ls = query(lc, l, m, L, R); rs = query(rc, m + 1, r, L, R);
o = maintain(ls, rs); return o;
}

int main() {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i];
cin >> m; build(1, 1, n);
for (int i = 1; i <= m; ++i) {
int x, y; cin >> x >> y;
cout << max(query(1, 1, n, x, y).v, 0) << endl;
}
return 0;
}