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
51
52
53
54
55
56
57
58
59
60
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    int n, k;
    cin >> n >> k;
    vector<int> a(n);
    for(int i = 0; i < n; ++i) {
        cin >> a[i];
    }

    multiset<int, greater<int>> wys;
    for(int i = 0; i < n; ++i) {
        wys.insert(a[i]);
    }

    vector<bool> vis(n, false);
    int ans = 0;
    while(!wys.empty()) {
        int biggest = *wys.begin();
        int idx = 0;
        for(int i = 0; i < n; ++i) {
            if(a[i] == biggest && vis[i] == false) {
                idx = i;
                vis[idx] = true;
                break;
            }
        }

        int min_wys = max(0, biggest - k);

        if(idx > 0) {
            if(a[idx - 1] < min_wys) {
                ans += min_wys - a[idx - 1];
                auto it = wys.find(a[idx - 1]);
                wys.erase(it);
                wys.insert(min_wys);
                a[idx - 1] = min_wys;
            }
        }

        if(idx < n - 1) {
            if(a[idx + 1] < min_wys) {
                ans += min_wys - a[idx + 1];
                auto it = wys.find(a[idx + 1]);
                wys.erase(it);
                wys.insert(min_wys);
                a[idx + 1] = min_wys;
            }
        }

        auto it = wys.find(biggest);
        wys.erase(it);
    }

    cout << ans << '\n';
}