Submission #1363082

#TimeUsernameProblemLanguageResultExecution timeMemory
1363082t6stksDeveloper (BOI25_dev)C++20
25 / 100
2095 ms3440 KiB
#include <bits/stdc++.h>
// #pragma GCC optimize("Ofast,unroll-loops")
#define F first
#define S second
#define SZ(x) ((int)(x).size())
#define ALL(x) x.begin(), x.end()
#define MP make_pair

using namespace std;
using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;
using vvi = vector<vi>;
using vvl = vector<vl>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using vii = vector<pii>;
using vll = vector<pll>;

const int maxn = 20000 + 5;
const ll INF = 0x3f3f3f3f3f3f3f3f;
ll dp[2][2 * maxn][2];
ll dp_pre[2 * maxn][2];
ll dp_suf[2 * maxn][2];
void sol() {
    int n;
    cin >> n;
    vi a(n + 1);
    vi pos;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
        pos.push_back(a[i] - 1);
        pos.push_back(a[i]);
    }
    sort(ALL(pos));
    pos.erase(unique(ALL(pos)), pos.end());
    int m = SZ(pos);
    for (int i = 0; i < m; i++) {
        dp[0][i][0] = dp[0][i][1] = 0;
    }
    for (int i = 1; i <= n; i++) {
        int now = i & 1;
        int pre = now ^ 1;
        for (int j = 0; j < m; j++) dp[now][j][0] = dp[now][j][1] = INF;
        for (int j = 0; j < m; j++) {
            dp[now][j][0] = min(dp[now][j][0], dp[pre][j][0] + abs(pos[j] - a[i]));
            if (j < m - 1) dp[now][j][0] = min(dp[now][j][0], dp_suf[j + 1][1] + abs(pos[j] - a[i]));

            dp[now][j][1] = min(dp[now][j][1], dp[pre][j][1] + abs(pos[j] - a[i]));
            if (j > 0) dp[now][j][1] = min(dp[now][j][1], dp_pre[j - 1][0] + abs(pos[j] - a[i]));
        }
        for (int c = 0; c < 2; c++) {
            dp_pre[0][c] = dp[now][0][c];
            for (int j = 1; j < m; j++) dp_pre[j][c] = min(dp_pre[j - 1][c], dp[now][j][c]);
            dp_suf[m - 1][c] = dp[now][m - 1][c];
            for (int j = m - 2; j >= 0; j--) dp_suf[j][c] = min(dp_suf[j + 1][c], dp[now][j][c]);
        }
    }
    ll ans = INF;
    for (int i = 0; i < m; i++) {
        for (int c = 0;c < 2; c++) {
            ans = min(ans, dp[n&1][i][c]);
        }
    }
    /*
    for (int i = 0; i < m; i++) {
        for (int c = 0;c < 2; c++) {
            if (ans == dp[n&1][i][c]) cerr << pos[i] << '\n';
        }
    }
    */
    cout << ans << '\n';
}

signed main() {
    cin.tie(0)->sync_with_stdio(0);
    sol();
}
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...