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

typedef long long int LL;

const int MAX_N = 1005;

int n, k, a, res;
int heights[MAX_N];
set<pair<int, int>, greater<pair<int, int>>> heightsWithIdxs;

void fixNeighbour(const pair<int, int>& top, int plusIdx)
{
    int neighbourIdx = top.second+plusIdx;
    int diff = top.first - heights[neighbourIdx];

    if(diff > k)
    {
        int toAdd = diff - k;

        heightsWithIdxs.erase(make_pair(heights[neighbourIdx], neighbourIdx));
        heights[neighbourIdx] += toAdd;
        heightsWithIdxs.insert(make_pair(heights[neighbourIdx], neighbourIdx));

        res += toAdd;
    }
}

int main()
{
    ios::sync_with_stdio(0);

    cin >> n >> k;
    for(int i = 0; i < n; ++i)
    {
        cin >> heights[i];
        heightsWithIdxs.insert(make_pair(heights[i], i));
    }

    while(!heightsWithIdxs.empty())
    {
        pair<int, int> top = *heightsWithIdxs.begin();
        heightsWithIdxs.erase(heightsWithIdxs.begin());

        //cout << "top: " << top.first << " at " << top.second << endl;

        if(top.second > 0)
        {
            fixNeighbour(top, -1);
        }
        if(top.second < n-1)
        {
            fixNeighbour(top, 1);
        }
    }

    cout << res << endl;

    return 0;

}