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
#include <bits/stdc++.h>
using namespace std;

int main(){
    int n, k;
    cin >> n >> k;
    int tab[n];
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    for(int i = 0; i < n; i++){
        cin >> tab[i];
        pq.push({tab[i], i});
    }

    long long wynik = 0;

    while(!pq.empty()){
        int i = pq.top().second;
        pq.pop();
        if(i > 0){
            if(tab[i]-tab[i-1]-k > 0) pq.push({tab[i]-tab[i-1]-k, i-1});
            wynik += max(0, tab[i]-tab[i-1]-k);
            tab[i-1] += max(0, tab[i]-tab[i-1]-k);
        }if(i < n-1){
            if(tab[i]-tab[i+1]-k > 0) pq.push({tab[i]-tab[i+1]-k, i+1});
            wynik += max(0, tab[i]-tab[i+1]-k);
            tab[i+1] += max(0, tab[i]-tab[i+1]-k);
        }
    }
    cout << wynik;
}