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
/* 2026
 * Maciej Szeptuch
 */

#include <cstdio>
#include <queue>

const int MAX_PARTS = 1024;

int parts;
int diff;
int height[MAX_PARTS];
std::priority_queue<std::pair<int, int>> order;
int result;

int main(void)
{
    scanf("%d %d", &parts, &diff);
    for(int p = 0; p < parts; ++p)
    {
        scanf("%d", &height[p]);
        order.push({height[p], p});
    }

    while(!order.empty())
    {
        auto current = order.top();
        order.pop();
        if(current.first != height[current.second])
            continue;

        if(current.second > 0 && current.first - height[current.second - 1] > diff)
        {
            result += (current.first - height[current.second - 1] - diff);
            height[current.second - 1] = current.first - diff;
            order.push({height[current.second - 1], current.second - 1});
        }

        if(current.second + 1 < parts && current.first - height[current.second + 1] > diff)
        {
            result += (current.first - height[current.second + 1] - diff);
            height[current.second + 1] = current.first - diff;
            order.push({height[current.second + 1], current.second + 1});
        }
    }

    printf("%d\n", result);
    return 0;
}