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
45
#include <bits/stdc++.h>

using namespace std;
const int MX = 1009;
int h[MX];
struct cmp{
    bool operator()(pair<int, int> a, pair<int, int> b)const{
        if(a.first == b.first) return a.second < b.second;
        return a.first > b.first;
    }
};

set<pair<int, int>, cmp> S;
int main(){
    cin.tie(0)->sync_with_stdio(0);
    int n, k; cin >> n >> k;
    for(auto i = 1; i <= n; ++i){
        cin >> h[i];
        S.emplace(h[i], i);
    }
    if(n == 1){
        cout << 0;
        return 0;
    }
    int res = 0;
    while(S.size()){
        auto it = S.begin();
        auto [H, i] = *it; S.erase(it);
        if(i != n && h[i+1] < h[i]){
            auto ir = S.find({h[i+1], i+1}); S.erase(ir);
            int hr = h[i+1];
            h[i+1] += max(0, H-k-hr);
            res += max(0, H-k-hr);
            S.emplace(h[i+1], i+1);
        }
        if(i != 1 && h[i-1] < h[i]){
            auto il = S.find({h[i-1], i-1}); S.erase(il);
            int hl = h[i-1];
            h[i-1] += max(0, H-k-hl);
            res += max(0, H-k-hl);
            S.emplace(h[i-1], i-1);
        }
    }
    cout << res;
}