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;
 
const int nx=5e5+5;
int n, a[nx], res[nx], q, l, r, id;
stack<int> s;
vector<int> d[nx];
vector<pair<int, int>> qrs[nx];
struct segtree
{
    int d[4*nx], lz[4*nx], omx[4*nx];
    void build(int l, int r, int i)
    {
        if (l==r) return d[i]=a[l], omx[i]=a[l], void();
        int md=(l+r)/2;
        build(l, md, 2*i);
        build(md+1, r, 2*i+1);
        d[i]=max(d[2*i], d[2*i+1]);
        omx[i]=max(omx[2*i], omx[2*i+1]);
    }
    void pushlz(int l, int r, int i)
    {
        if (lz[i]==0) return void();
        d[i]=max(d[i], omx[i]+lz[i]);
        if (l!=r) lz[2*i]=max(lz[2*i], lz[i]), lz[2*i+1]=max(lz[2*i+1], lz[i]);
    }
    void update(int l, int r, int i, int ql, int qr, int vl)
    {
        pushlz(l, r, i);
        if (qr<l||r<ql) return;
        if (ql<=l&&r<=qr) return lz[i]=vl, pushlz(l, r, i), void();
        int md=(l+r)/2;
        update(l, md, 2*i, ql, qr, vl);
        update(md+1, r ,2*i+1, ql, qr, vl);
        d[i]=max(d[2*i], d[2*i+1]);
    }
    int query(int l, int r, int i, int ql, int qr)
    {
        pushlz(l, r, i);
        if (qr<l||r<ql) return -1e9;
        if (ql<=l&&r<=qr) return (lz[i]==0)?-1e9:d[i];
        int md=(l+r)/2;
        return max(query(l, md, 2*i, ql, qr), query(md+1, r, 2*i+1, ql, qr));
    }
    void show(int l, int r, int i)
    {
        pushlz(l, r, i);
        cout<<l<<' '<<r<<' '<<d[i]<<'\n';
        if (l==r) return;
        int md=(l+r)/2;
        show(l, md, 2*i);
        show(md+1, r, 2*i+1);
    }
} st;
int main()
{
    cin.tie(NULL)->sync_with_stdio(false);
    cin>>n;
    id=n;
    for (int i=1; i<=n; i++) cin>>a[i];
    st.build(1, n, 1);
    for (int i=1; i<=n; i++)
    {
        while (!s.empty()&&a[s.top()]<=a[i]) d[s.top()].push_back(i), s.pop();
        if (!s.empty()) d[s.top()].push_back(i);
        s.push(i);
    }
    cin>>q;
    for (int i=1; i<=q; i++) cin>>l>>r, qrs[l].push_back({r, i});
    for (int i=n; i>=1; i--)
    {
        for (auto x:d[i]) if (2*x-i<=n) id=min(id, 2*x-i), st.update(1, n, 1, 2*x-i, n, a[x]+a[i]);// st.show(1, n, 1), cout<<'\n';
        for (auto [r, idx]:qrs[i]) res[idx]=st.query(1, n, 1, id, r);// cout<<"query "<<i<<' '<<r<<' '<<res[idx]<<'\n';
    }
    for (int i=1; i<=q; i++) cout<<res[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... |