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
#include<bits/stdc++.h>
using namespace std;
#define int long long
typedef long long ll;
typedef double db;
typedef vector<int> vi;
typedef pair<int, int> pii;
#define all(x) (x).begin(), (x).end()

priority_queue <pii> pq;
int tab[1007];

void solve() {
    int n, k, i, j, a, b, ans=0;
    cin >> n >> k;
    tab[0]=1000000;
    tab[n+1]=1000000;
    for(i=1; i<=n; i++){
        cin >> tab[i];
        pq.push({tab[i], i});
    }
    while(!pq.empty()){
        auto v = pq.top();
        // cout << v.first << ' ' << v.second << ' ' << ans << '\n';
        pq.pop();
        if(tab[v.second]!=v.first) continue;
        // cout << "poszło\n";
        if(tab[v.second-1]+k<tab[v.second]){
            ans+=tab[v.second]-tab[v.second-1]-k;
            tab[v.second-1]=tab[v.second]-k;
            pq.push({tab[v.second-1], v.second-1});
        }
        if(tab[v.second+1]+k<tab[v.second]){
            ans+=tab[v.second]-tab[v.second+1]-k;
            tab[v.second+1]=tab[v.second]-k;
            pq.push({tab[v.second+1], v.second+1});
        }
    }
    cout << ans << '\n';
}

signed main () {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int t = 1;
    // cin >> t;
    while(t-- ) solve();
}