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
40
41
42
43
44
#include <bits/stdc++.h>

using namespace std;

int main() {

    cin.tie(nullptr); ios_base::sync_with_stdio(false);

    int len, diff; cin >> len >> diff;

    vector<int> h(len);
    set<pair<int, int>> heights;
    for(int i = 0; i < len; i++) {
        cin >> h[i];
        heights.insert({-h[i], i});
    }
    
    long long result = 0;
    pair<int, int> pr;
    while(!heights.empty()) {
        pr = *heights.begin();
        heights.erase(heights.begin());
        if(pr.second > 0) {
            if(h[pr.second-1] < h[pr.second] - diff) {
                heights.erase(heights.find({-h[pr.second-1], pr.second-1}));
                result += h[pr.second]-diff-h[pr.second-1];
                h[pr.second-1] = h[pr.second]-diff;
                heights.insert({-h[pr.second-1], pr.second-1});
            }
        }
        if(pr.second < len-1) {
            if(h[pr.second+1] < h[pr.second] - diff) {
                heights.erase(heights.find({-h[pr.second+1], pr.second+1}));
                result += h[pr.second]-diff-h[pr.second+1];
                h[pr.second+1] = h[pr.second]-diff;
                heights.insert({-h[pr.second+1], pr.second+1});
            }
        }
    }

    cout << result << '\n';

    return 0;
}