1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int main() {
    ios_base::sync_with_stdio(0); cin.tie(0);
    int n; LL k;
    cin >> n >> k;

    vector<LL> a(n), original_a(n);
    priority_queue<pair<LL, int>> pq;

    for (int i = 0; i < n; i++) {
        cin >> a[i];
        original_a[i] = a[i];
        pq.push({a[i], i});
    }

    while (!pq.empty()) {
        LL h = pq.top().first;
        int idx = pq.top().second;
        pq.pop();

        if (h < a[idx]) continue;

        for (int neighbor_idx : {idx - 1, idx + 1}) {
            if (neighbor_idx >= 0 && neighbor_idx < n) {
                if (a[idx] - a[neighbor_idx] > k) {
                    a[neighbor_idx] = a[idx] - k;
                    pq.push({a[neighbor_idx], neighbor_idx});
                }
            }
        }
    }

    LL ans = 0;
    for (int i = 0; i < n; i++) 
        ans += (a[i] - original_a[i]);
    cout << ans << '\n';
}