This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef double ld;
typedef complex<ld> point;
void debug_out(){cerr << endl;}
template<typename Head, typename... Tail>
void debug_out(Head H, Tail... T){
cerr << H << ' ';
debug_out(T...);
}
#define debug(...) cerr << "(" << #__VA_ARGS__ << "): ", debug_out(__VA_ARGS__)
#define F first
#define S second
#define all(x) x.begin(), x.end()
#define MP(x, y) make_pair(x, y)
const int maxn = 5e5 + 10;
int n, q, a[maxn];
pll seg[maxn << 2];
ll lazy[maxn << 2], ans[maxn];
vector<pii> Q[maxn], A[maxn];
pii operator +(pii a, pii b){
return MP(max(a.F, b.F), max(a.S, b.S));
}
void build(int v, int l, int r){
if (l + 1 == r){
seg[v] = {a[l], a[l]};
return;
}
int mid = (l + r) >> 1;
build(v << 1, l, mid);
build(v << 1 | 1, mid, r);
seg[v] = seg[v << 1] + seg[v << 1 | 1];
}
void shift(int v, int l, int r);
void change(int v, int l, int r, int ql, int qr, ll val){
if (qr <= l || r <= ql) return;
if (ql <= l && r <= qr){
seg[v].F = max(seg[v].F, seg[v].S + val);
lazy[v] = max(lazy[v], val);
return;
}
shift(v, l, r);
int mid = (l + r) >> 1;
change(v << 1, l, mid, ql, qr, val);
change(v << 1 | 1, mid, r, ql, qr, val);
seg[v] = seg[v << 1] + seg[v << 1 | 1];
}
ll get(int v, int l, int r, int ql, int qr){
if (qr <= l || r <= ql) return 0;
if (ql <= l && r <= qr) return seg[v].F;
shift(v, l, r);
int mid = (l + r) >> 1;
return max(get(v << 1, l, mid, ql, qr)
, get(v << 1 | 1, mid, r, ql, qr));
}
void shift(int v, int l, int r){
if (lazy[v] == 0) return;
int mid = (l + r) >> 1;
change(v << 1, l, mid, l, mid, lazy[v]);
change(v << 1 | 1, mid, r, mid, r, lazy[v]);
lazy[v] = 0;
}
int main(){
cin >> n;
for (int i = 1; i <= n; i++){
cin >> a[i];
}
build(1, 1, n+1);
cin >> q;
for (int i = 1; i <= q; i++){
int l, r; cin >> l >> r;
Q[l].push_back({r, i});
}
vector<int> v;
for (int i = 1; i <= n; i++){
while(!v.empty() && a[v.back()] < a[i]) v.pop_back();
if (!v.empty()){
A[v.back()].push_back({i + (i - v.back()), a[v.back()] + a[i]});
}
v.push_back(i);
}
v.clear();
for (int i = n; i; i--){
while(!v.empty() && a[v.back()] < a[i]) v.pop_back();
if (!v.empty()){
A[i].push_back({v.back() + (v.back() - i), a[v.back()] + a[i]});
}
v.push_back(i);
}
for (int i = n; i; i--){
for (auto [x, y]: A[i]){
change(1, 1, n+1, x, n+1, y);
}
for (auto [r, idx]: Q[i]){
ans[idx] = get(1, 1, n+1, i, r+1);
}
}
for (int i = 1; i <= q; i++) cout << ans[i] << '\n';
return 0;
}
# | 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... |