Submission #1331529

#TimeUsernameProblemLanguageResultExecution timeMemory
1331529kawhietSafety (NOI18_safety)C++20
35 / 100
1954 ms196424 KiB
#include <bits/stdc++.h>
using namespace std;

#define int long long

constexpr int inf = 1e18;

struct SegmentTree {
    int n;
    vector<int> t;

    SegmentTree(int _n) {
        n = _n;
        t.resize(4 * n);
    }

    int merge(int x, int y) {
        return min(x, y);
    }

    void build(int id, int tl, int tr, vector<int> &a) {
        if (tl == tr) {
            t[id] = a[tl];
            return;
        }
        int x = (id << 1) + 1, y = x + 1, tm = (tl + tr) >> 1;
        build(x, tl, tm, a);
        build(y, tm + 1, tr, a);
        t[id] = min(t[x], t[y]);
    }

    void update(int id, int tl, int tr, int i, int v) {
        if (tl == tr) {
            t[id] = v;
            return;
        }
        int x = (id << 1) + 1, y = x + 1, tm = (tl + tr) >> 1;
        if (i <= tm) {
            update(x, tl, tm, i, v);
        } else {
            update(y, tm + 1, tr, i, v);
        }
        t[id] = merge(t[x], t[y]);
    }

    int get(int id, int tl, int tr, int l, int r) {
        if (r < tl || tr < l) return inf;
        if (l <= tl && tr <= r) return t[id];
        int x = (id << 1) + 1, y = x + 1, tm = (tl + tr) >> 1;
        return merge(get(x, tl, tm, l, r), get(y, tm + 1, tr, l, r));
    }

    void build(vector<int> &a) { build(0, 0, n - 1, a); }
    void update(int i, int v) { update(0, 0, n - 1, i, v); }
    int get(int l, int r) { return get(0, 0, n - 1, l, r); }
};

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, h;
    cin >> n >> h;
    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    int m = ranges::max(a);
    vector<vector<int>> dp(n, vector<int>(m + 1, inf));
    for (int i = 0; i <= m; i++) {
        dp[0][i] = abs(i - a[0]);
    }
    SegmentTree t(m + 1);
    for (int i = 1; i < n; i++) {
        t.build(dp[i - 1]);
        for (int j = 0; j <= m; j++) {
            int l = max(0LL, j - h);
            int r = min(m, j + h);
            dp[i][j] = t.get(l, r) + abs(a[i] - j);
        }

    }
    int ans = ranges::min(dp[n - 1]);
    cout << ans << '\n';
    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...