Submission #140569

#TimeUsernameProblemLanguageResultExecution timeMemory
140569ngot23Triple Jump (JOI19_jumps)C++11
100 / 100
1307 ms99236 KiB
#include <bits/stdc++.h>
#define rep(i, a, b) for(int i=(a) ; i<=(b) ; ++i)
#define mp make_pair
#define pii pair<int, int>
#define PB push_back
#define F first
#define S second
#define Task ""
using namespace std;
template <typename T > inline void MIN(T &a, T b) { if(a>b) a=b; }
template <typename T > inline void MAX(T &a, T b) { if(a<b) a=b; }

const int N=500005;
int n, a[N], Q, ans[N];
vector <pii > query[N];
vector <int > v[N];
stack <int > s;

struct node {
    int ab, c, sum;
    node(int AB=0, int C=0, int SUM=0) {
        ab=AB, c=C, sum=SUM;
    }
};

node Merge(node L, node R) {
    return node(max(L.ab, R.ab), max(L.c, R.c), max(max(L.sum, R.sum), L.ab+R.c));
}

node t[N*4];

void updateC(int l, int r, int id, int pos) {
    if(l==r) {
        t[id].c=a[pos];
        t[id].sum=a[pos];
        return;
    }
    int mid=(r+l)>>1;
    if(pos<=mid) updateC(l, mid, id*2, pos);
    else updateC(mid+1, r, id*2+1, pos);
    t[id]=Merge(t[id*2], t[id*2+1]);
}

void updateAB(int l, int r, int id, int pos, int val) {
    if(l==r) {
        t[id].ab=max(t[id].ab, val);
        t[id].sum=t[id].ab+t[id].c;
        return;
    }
    int mid=(r+l)>>1;
    if(pos<=mid) updateAB(l, mid, id*2, pos, val);
    else updateAB(mid+1, r, id*2+1, pos, val);
    t[id]=Merge(t[id*2], t[id*2+1]);
}

node get(int l, int r, int id, int u, int v) {
    if(r<u||v<l) return node();
    if(u<=l&&r<=v) return t[id];
    int mid=(r+l)>>1;
    node L=get(l, mid, id*2, u, v);
    node R=get(mid+1, r, id*2+1, u, v);
    return Merge(L, R);
}

void setup() {
    cin >> n;
    rep(i, 1, n) cin >> a[i];
    cin >> Q;
    rep(i, 1, Q) {
        int l, r; cin >> l >> r;
        query[l].PB(mp(r, i));
    }
}

void pre() {
    rep(i, 1, n) {
        while(!s.empty()&&a[i]>a[s.top()]) {
            v[s.top()].PB(i);
            s.pop();
        }
        if(s.size()) v[s.top()].PB(i);
        s.push(i);
    }
}

void calc() {
    for(int i=n ; i ; --i) {
        updateC(1, n, 1, i);
        for(auto val:v[i]) if(2*val-i<=n) updateAB(1, n, 1, 2*val-i, a[i]+a[val]);
        for(auto P:query[i]) {
            ans[P.S]=get(1, n, 1, i, P.F).sum;
        }
    }
    rep(i, 1, Q) cout << ans[i] << '\n';
}

int main() {
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    //freopen(Task".inp", "r", stdin);
    //freopen(Task".out", "w", stdout);
    setup();
    pre();
    calc();
    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...