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>
#define f first
#define s second
#define int long long
using namespace std;
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int tt = 1;
//cin >> tt;
while (tt--) {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0;i < n;i++)
cin >> a[i];
int q;
cin >> q;
while (q--) {
int l, r;
cin >> l >> r;
--l, --r;
vector<int> ll(n), rr(n);
vector<int> st;
for (int i = l;i <= r;i++) {
while (!st.empty() && a[st.back()] <= a[i])
st.pop_back();
if (!st.empty())
ll[i] = st.back();
else
ll[i] = -1;
st.push_back(i);
}
st.clear();
for (int i = r;i >= l;i--) {
while (!st.empty() && a[st.back()] <= a[i])
st.pop_back();
if (!st.empty())
rr[i] = st.back();
else
rr[i] = -1;
st.push_back(i);
}
vector<int> p(n + 1);
for (int i = r;i >= l;i--)
p[i] = max(p[i + 1], a[i]);
int ans = 0;
for (int i = l;i <= r;i++) {
if (rr[i] == -1)
continue;
int x = rr[i] - i;
int j = rr[i] + x;
if (j <= r)
ans = max(ans, a[i] + a[rr[i]] + p[j]);
}
for (int i = l;i <= r;i++) {
if (ll[i] == -1)
continue;
int x = i - ll[i];
int j = i + x;
if (j <= r)
ans = max(ans, a[i] + a[ll[i]] + p[j]);
}
cout << ans << '\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... |