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<iostream>
#include<algorithm>
#include<numeric>
using namespace std;
typedef long long ll;
const int N = 5e5 + 5, N2 = 5000 + 3, inf = 1e9 + 7;
int n, lg[N];
int a[19][N];
void build() {
for (int j = 0; j < 18; ++j)
for (int i = 1; i + (2 << j) - 1 <= n; ++i)
a[j + 1][i] = max(a[j][i], a[j][i + (1 << j)]);
lg[1] = 0;
for (int i = 2; i <= n; ++i) lg[i] = lg[i >> 1] + 1;
}
int get(int l, int r) {
if (r < 1 || n < l || r < l) return -inf;
int k = lg[r - l + 1];
return max(a[k][l], a[k][r - (1 << k) + 1]);
}
int dp[N2][N2];
void subtask12() {
for (int i = 1; i <= n; ++i)
for (int k = i + 2; k <= n; ++k)
dp[i][k] = a[0][i] + get(i + 1, (i + k) >> 1) + a[0][k];
for (int len = 3; len <= n; ++len)
for (int i = 1, j = len; j <= n; ++i, ++j)
dp[i][j] = max({ dp[i][j - 1], dp[i + 1][j], a[0][i] + get(i + 1, (i + j) >> 1) + a[0][j] });
int q, l, r; cin >> q; while (q--) {
cin >> l >> r;
cout << dp[l][r] << '\n';
}
}
int calc(int p1, int p2) {
return max({ get(max(1, p1 * 2 - p2), p1 - 1), get(p1 + 1, (p1 + p2) >> 1), get(p2 * 2 - p1, n) });
}
int idx[N];
void subtask3() {
iota(idx + 1, idx + n + 1, 1);
sort(idx + 1, idx + n + 1, [](int i, int j) { return a[0][i] > a[0][j]; });
int ans(-inf);
for (int p = 1; p <= 20; ++p) {
int i = idx[p];
for (int j = 1; j < i; ++j)
ans = max(ans, a[0][j] + calc(j, i) + a[0][i]);
for (int j = i + 1; j <= n; ++j)
ans = max(ans, a[0][i] + calc(i, j) + a[0][j]);
}
cout << ans << '\n';
}
int main() {
cin.tie(NULL)->sync_with_stdio(false);
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[0][i];
build();
if (n <= 5000)
subtask12();
else subtask3();
}
/** /\_/\
* (= ._.)
* / >0 \>1
**/
# | 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... |