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>
using namespace std;
typedef long long ll;
typedef array<int, 3> P;
const int N = 5050;
const ll INF = 1e18 + 10;
int n, a[N], p;
ll dp[2 * N][2 * N];
int main() {
cin.tie(0); ios_base::sync_with_stdio(0);
cin >> n;
for (int i = 1; i <= n; i++) {
int x; cin >> x;
if (p && a[p - 1] == x)
continue;
while (p >= 2 && (a[p - 2] < a[p - 1]) == (a[p - 1] < x))
--p;
a[p++] = x;
}
n = p;
for (int i = 0; i <= 2 * n - 2; i++)
for (int j = i; j <= 2 * n - 2; j++)
dp[i][j] = INF;
dp[0][2 * n - 2] = 0;
auto go = [&](int x, int y, int tx, int ty) {
int p = (x & 1) ? a[(y + 1) / 2] : a[x / 2];
int nx = (x & 1) ? (tx ? x + 1 : x - 1) : (tx ? x + 2 : x - 2);
int ny = (y & 1) ? (ty ? y - 1 : y + 1) : (ty ? y - 2 : y + 2);
bool dx = (tx ? a[nx / 2 - 1] : a[nx / 2 + 1]) < a[nx / 2]; // true if climbing
bool dy = (ty ? a[ny / 2 + 1] : a[ny / 2 - 1]) < a[ny / 2];
if (dx != dy)
return P{ -1, -1, 0 };
if (a[nx / 2] == a[ny / 2])
return P{ nx, ny, abs(a[nx / 2] - p) };
if (dx == (a[nx / 2] < a[ny / 2]))
return P{ nx, ty ? ny + 1 : ny - 1, abs(a[nx / 2] - p) };
else
return P{ tx ? nx - 1 : nx + 1, ny, abs(a[ny / 2] - p) };
};
for (int d = 2 * n - 2; d >= 1; d--) {
for (int l = 0; l + d <= 2 * n - 2; l++) {
int r = l + d;
if (dp[l][r] == INF)
continue;
auto [x, y, d] = go(l, r, 1, 1); // alice, bob goes forward
if (x != -1)
dp[x][y] = min(dp[x][y], dp[l][r] + d);
if (l != 0) {
auto [x, y, d] = go(l, r, 0, 1); // only bob goes forward
if (x != -1)
dp[x][y] = min(dp[x][y], dp[l][r] + d);
}
if (r != 2 * n - 2) {
auto [x, y, d] = go(l, r, 1, 0); // only alice goes forward
if (x != -1)
dp[x][y] = min(dp[x][y], dp[l][r] + d);
}
}
}
ll ans = INF;
for (int i = 0; i < n; i++)
ans = min(ans, dp[2 * i][2 * i]);
cout << ans;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |