线段树求最大子段和。
对于一个区间,记录它的前缀最大子段和、后缀最大子段和、区间和、和区间最大子段和,对于每个节点,更新前缀和后缀最大子段和,则当前区间的最大子段和为左区间后缀最大值+右区间前缀最大值和左右区间最大子段和的最大值。
查询复杂度
O
(
l
o
g
n
)
O(logn)
O(logn)
#include<set>
#include<map>
#include<cmath>
#include<queue>
#include<stack>
#include<cstdio>
#include<vector>
#include<cstdlib>
#include<iomanip>
#include<cstring>
#include<string.h>
#include<iostream>
#include<algorithm>
#define ll long long
#define Max(a, b) ((a) > (b) ? (a) : (b))
const long long INF = 1e18;
const int mod = 1e9 + 7;
const int N = 5e4 + 10;
typedef std::pair<int, int> pii;
typedef std::pair<ll, ll> pll;
ll gcd(ll p, ll q) { return q == 0 ? p : gcd(q, p % q); }
using namespace std;
int n, a[N];
struct node {
int l, r;
ll s, v, pre, suf;
} tree[N << 2];
inline void pushup(int id) {
int l = id << 1, r = id << 1 | 1;
tree[id].s = tree[l].s + tree[r].s;
tree[id].v = max(max(tree[l].v, tree[r].v), tree[l].suf + tree[r].pre);
tree[id].pre = max(tree[l].pre, tree[l].s + tree[r].pre);
tree[id].suf = max(tree[r].suf, tree[l].suf + tree[r].s);
}
void build(int id, int l, int r) {
tree[id].l = l;
tree[id].r = r;
if (l == r) {
tree[id].v = tree[id].s = tree[id].pre = tree[id].suf = a[l];
return;
}
int mid = (l + r) >> 1;
build(id << 1, l, mid);
build(id << 1 | 1, mid + 1, r);
pushup(id);
}
node query(int id, int ql, int qr) {
int l = tree[id].l, r = tree[id].r;
if (ql <= l && qr >= r)
return tree[id];
int mid = (l + r) >> 1;
if (qr <= mid)
return query(id << 1, ql, qr);
else if (ql > mid)
return query(id << 1 | 1, ql, qr);
else {
node ans, ls = query(id << 1, ql, qr), rs = query(id << 1 | 1, ql, qr);
ans.s = ls.s + rs.s;
ans.v = max(max(ls.v, rs.v), ls.suf + rs.pre);
ans.pre = max(ls.pre, ls.s + rs.pre);
ans.suf = max(rs.suf, rs.s + ls.suf);
return ans;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
build(1,1,n);
int m, x, y;
cin >> m;
for (int i = 1; i <= m; i++) {
cin >> x >> y;
cout << query(1, x, y).v << endl;
}
return 0;
}