Submission #655544

#TimeUsernameProblemLanguageResultExecution timeMemory
655544piOOETriple Jump (JOI19_jumps)C++17
100 / 100
1223 ms45448 KiB
#include <bits/stdc++.h>

using namespace std;

struct Info {
    int add = 0, a = 0, ans = 0;
};

Info operator+(Info a, Info b) {
    return {max(a.add, b.add), max(a.a, b.a), max({a.ans, b.ans, a.add + b.a})};
}

int sz = 1;
vector<Info> t;

void init(int n, vector<int> a) {
    sz = 1 << (__lg(n) + bool(n & (n - 1)));
    t.assign(sz << 1, {});
    for (int i = 0; i < n; ++i) {
        t[i + sz].a = t[i + sz].ans = a[i];
    }
    for (int i = sz - 1; i > 0; --i) {
        t[i] = t[i << 1] + t[i << 1 | 1];
    }
}

Info rangeQuery(int l, int r, int x = 1, int lx = 0, int rx = sz) {
    if (l >= rx || lx >= r) {
        return {};
    }
    if (l <= lx && rx <= r) {
        return t[x];
    }
    int mid = (lx + rx) >> 1;
    return rangeQuery(l, r, x << 1, lx, mid) + rangeQuery(l, r, x << 1 | 1, mid, rx);
}

void modify(int i, int add) {
    i += sz;
    t[i].add = max(t[i].add, add);
    t[i].ans = t[i].add + t[i].a;
    while (i >>= 1) {
        t[i] = t[i << 1] + t[i << 1 | 1];
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    vector<int> a(n);
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
    }

    vector<array<int, 3>> events;

    auto relax = [&](int i, int j) {
        int r = j + (j - i);
        if (r < n) {
            events.push_back({i, j, -1});
        }
    };

    vector<int> stk;
    for (int i = 0; i < n; ++i) {
        while (!stk.empty() && a[stk.back()] <= a[i]) {
            relax(stk.back(), i);
            stk.pop_back();
        }
        if (!stk.empty()) {
            relax(stk.back(), i);
        }
        stk.push_back(i);
    }

    int q;
    cin >> q;

    for (int i = 0; i < q; ++i) {
        int l, r;
        cin >> l >> r;
        events.push_back({l - 1, r, i});
    }

    vector<int> ans(q);

    sort(events.begin(), events.end(), [&](array<int, 3> x, array<int, 3> y) {
        return x[0] != y[0] ? x[0] > y[0] : x[2] < y[2];
    });

    init(n, a);

    set<array<int, 3>> st;

    for (auto [i, j, tp]: events) {
        if (tp > -1) {
            ans[tp] = rangeQuery(i, j).ans;
        } else {
            int k = j + (j - i);
            int sum = a[i] + a[j];
            modify(k, sum);
        }
    }

    for (int i = 0; i < q; ++i) {
        cout << ans[i] << "\n";
    }
    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...