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
46
47
48
49
50
// clang-format off
#include<bits/stdc++.h>
using namespace std;
using LL=long long;
#define FOR(i,l,r) for(auto i=(l);i<=(r);++i)
#define REP(i,n) FOR(i,0,(n)-1)
#define ssize(x) int(x.size())
auto operator<<(ostream&o,auto p)->decltype(p.first,o){return o<<"("<<p.first<<", "<<p.second<<")";}
auto operator<<(ostream&o,auto x)->decltype(x.end(),o){o<<"{";int i=0;for(auto e:x)o<<(", ")+2*!i++<<e;return o<<"}";}
#ifdef DEBUG
#define debug(x...) cerr<<"["#x"]: ",[](auto...$){((cerr<<$<<"; "),...);}(x),cerr<<'\n'
#else
#define debug(...) {}
#endif
// clang-format on

int nguys, max_diff;
vector<int> heights;
set<pair<int, int>, greater<pair<int, int>>> pq;  // (height, id)

int
main()
{
    cin.tie(0)->sync_with_stdio(0);
    cin >> nguys >> max_diff;
    heights.resize(nguys);
    for (auto &height : heights) cin >> height;
    REP (i, nguys) pq.insert({heights[i], i});

    int score = 0;
    while (!pq.empty()) {
        auto [height, id] = *pq.begin();
        pq.erase(*pq.begin());

        auto update = [&](int neight)
        {
            if (heights[neight] + max_diff >= height) return;
            pq.erase({heights[neight], neight});
            score += (height - max_diff) - heights[neight];
            heights[neight] = height - max_diff;
            pq.insert({heights[neight], neight});
        };

        if (id > 0) update(id - 1);
        if (id + 1 < nguys) update(id + 1);
        debug(score, id, height, heights);
    }
    cout << score << "\n";
    return 0;
}