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;
#define finish(x) return cout << x << endl, 0
#define ll long long
const int N = 500001;
struct item{
int mx_f, mx_a, mx;
};
int n, q;
vector <int> a, v[N];
vector <pair <int, int> > qu[N];
item tree[4 * N];
item merge(item a, item b){
item ret = a;
ret.mx_f = max(ret.mx_f, b.mx_f);
ret.mx_a = max(ret.mx_a, b.mx_a);
ret.mx = max(ret.mx, max(b.mx, a.mx_f + b.mx_a));
return ret;
}
void update(int l, int r, int node, int idx, item c){
if(r < l || r < idx || l > idx) return;
if(l == r){
tree[node].mx_f = max(tree[node].mx_f, c.mx_f);
tree[node].mx_a = max(tree[node].mx_a, c.mx_a);
tree[node].mx = tree[node].mx_f + tree[node].mx_a;
return;
}
int mid = (l + r) / 2;
update(l, mid, 2 * node, idx, c);
update(mid + 1, r, 2 * node + 1, idx, c);
tree[node] = merge(tree[2 * node], tree[2 * node + 1]);
}
item query(int l, int r, int node, int s, int e){
if(r < l || r < s || l > e) return {0, 0, 0};
if(s <= l && r <= e) return tree[node];
int mid = (l + r) / 2;
return merge(query(l, mid, 2 * node, s, e), query(mid + 1, r, 2 * node + 1, s, e));
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
a.resize(n);
for(auto &i : a) cin >> i;
vector <int> s;
for(int i = 0 ; i < n ; i++){
while(s.size() && a[i] >= a[s.back()]){
v[s.back()].push_back(i);
s.pop_back();
}
if(s.size()){
v[s.back()].push_back(i);
}
s.push_back(i);
}
cin >> q;
for(int i = 0 ; i < q ; i++){
int l, r;
cin >> l >> r;
l--; r--;
qu[l].push_back(make_pair(r, i));
}
for(int i = 0 ; i < n ; i++){
update(0, n - 1, 1, i, {0, a[i], 0});
}
vector <int> ans(q);
for(int l = n - 1 ; l >= 0 ; l--){
for(auto &r : v[l]){
update(0, n - 1, 1, 2 * r - l, {a[l] + a[r], 0, 0});
}
for(auto &i : qu[l]){
ans[i.second] = query(0, n - 1, 1, l, i.first).mx;
}
}
for(auto &i : ans) cout << 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... |