D - Tail of Snake Editorial by en_translator
For the sake of explanation, we assume \(A, B\), and \(C\) are 0-indexed. All other sequences below are also 0-indexed.
Take the cumulative sums of \(A, B\), and \(C\). In other words, define sequences \(D, E\), and \(F\) as \(\displaystyle D_i = \sum_{j = 0}^{i - 1} A_j, E_i = \sum_{j = 0}^{i - 1} B_j\), and \(F_i = \sum_{j = 0}^{i-1} C_j\).
The value we want to maximize, \(\displaystyle \sum_{i = 0} ^ {x - 1} A_i + \sum_{i = x}^{y - 1} B_i +\sum_ {i =y}^{N - 1} C_i\), can be written using \(D, E\), and \(F\) as \(D_x - E_x + E_y - F_y + F_N\).
Since \(F_N\) is a constant independent of the choice of \(x\) and \(y\), the objective is to maximize \(D_x - E_x + E_y - F_y\).
If we define sequences \(G\) and \(H\) as \(G_i = D_i - E_i\) and \(H_i = E_i - F_i\), it is reduced to maximizing \(G_x + H_y\). This can be done by taking the cumulative max of the prefix while scanning \(y\). More specifically, if we define a sequence \(I\) as \(I_i = \displaystyle\max_{1 \leq j < i} G_j\), the maximum value for any fixed \(y\) is \(I_y + H_y\).
The time complexity is \(O(N)\). Note that \(x = 0, x = y, y = N\) is disallowed.
Sample code
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (ll i = 0; i < (n); i++)
const ll INF = 1000000000000000010;
template<class T, class U> inline bool chmax(T& a, const U& b) { if (a < b) { a = b; return true; } return false; }
int main() {
ll n;
cin >> n;
vector<ll> a(n), b(n), c(n);
rep(i, n) cin >> a[i];
rep(i, n) cin >> b[i];
rep(i, n) cin >> c[i];
vector<ll> d(n + 1), e(n + 1), f(n + 1);
rep(i, n) {
d[i + 1] = d[i] + a[i];
e[i + 1] = e[i] + b[i];
f[i + 1] = f[i] + c[i];
}
vector<ll> g(n + 1), h(n + 1);
rep(i, n + 1) {
g[i] = d[i] - e[i];
h[i] = e[i] - f[i];
}
ll mx = -INF;
ll ans = 0;
for (int j = 1; j < n; j++) {
chmax(ans, mx + h[j] + f[n]);
chmax(mx, g[j]);
}
cout << ans << '\n';
}
posted:
last update: