#include <iostream>
#include <vector>
#include <algorithm>
#define f first
#define s second
using namespace std;
long long n, a[500010], test, ans[500010], pos;
pair<pair<int,int>,int> query[500010];
vector<pair<int,int>> stk, v;
struct {
struct {
int d, c, lz;
} node[2000010];
void build(int id, int x, int y) {
if (x == y) {
node[id].c = a[x];
return;
}
int mid = (x+y)/2;
build(id*2,x,mid);
build(id*2+1,mid+1,y);
node[id].c = max(node[id*2].c,node[id*2+1].c);
}
void split(int id) {
node[id*2].lz = max(node[id].lz,node[id*2].lz);
node[id*2+1].lz = max(node[id].lz,node[id*2+1].lz);
node[id].lz = 0;
if (node[id*2].lz) node[id*2].d = max(node[id*2].d,node[id*2].c+node[id*2].lz);
if (node[id*2+1].lz) node[id*2+1].d = max(node[id*2+1].d,node[id*2+1].c+node[id*2+1].lz);
}
void update(int id, int x, int y, int pos, int val) {
if (pos <= x) {
node[id].d = max(node[id].d,node[id].c+val);
node[id].lz = max(node[id].lz,val);
return;
}
if (y < pos) return;
int mid = (x+y)/2;
split(id);
update(id*2,x,mid,pos,val);
update(id*2+1,mid+1,y,pos,val);
node[id].d = max(node[id*2].d,node[id*2+1].d);
}
long long find(int id, int x, int y, int l, int r) {
if ((l <= x) && (y <= r)) return node[id].d;
if ((y < l) || (r < x)) return 0;
int mid = (x+y)/2;
split(id);
return max(find(id*2,x,mid,l,r),find(id*2+1,mid+1,y,l,r));
}
} seg;
int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= n; i++) {
while ((stk.size()) && (a[i] >= stk.back().f)) {
v.push_back({stk.back().s,i});
stk.pop_back();
}
if (stk.size()) v.push_back({stk.back().s,i});
stk.push_back({a[i],i});
}
sort(v.begin(),v.end(),greater<pair<int,int>>());
seg.build(1,1,n);
cin >> test;
for (int i = 1; i <= test; i++) {
cin >> query[i].f.f >> query[i].f.s;
query[i].s = i;
}
sort(query+1,query+test+1,greater<pair<pair<int,int>,int>>());
for (int i = 1; i <= test; i++) {
while ((pos < v.size()) && (query[i].f.f <= v[pos].f)) {
if (2*v[pos].s-v[pos].f <= n) seg.update(1,1,n,2*v[pos].s-v[pos].f,a[v[pos].f]+a[v[pos].s]);
pos++;
}
ans[query[i].s] = seg.find(1,1,n,query[i].f.f,query[i].f.s);
}
for (int i = 1; i <= test; i++) cout << ans[i] << "\n";
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |