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
62
63
64
65
66
67
68
69
70
71
72
73
74
// PA 2024 2C - Dostawa zwiru
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Item {
	long long height;
	long long idx;
	
	Item(long long height, long long idx) {
		this->height = height;
		this->idx = idx;
	}
	
	bool operator>(const Item& A) const
    {
        return this->height > A.height;
    }
};

int main()
{
	ios_base::sync_with_stdio(0);
	long long n, k, a, idx, result;
	vector<long long> path;
	vector<Item> items;
	vector<bool> used;
	
	cin >> n;
	cin >> k;
	result = 0;
	
	for (long long i = 0; i < n; ++i) {
		cin >> a;
		path.push_back(a);
		items.push_back(Item(a, i));
		used.push_back(false);
	}
	
	sort(items.begin(), items.end(), greater<Item>());
	
	for (long long i = 0; i < n; ++i) {
		idx = items[i].idx;
		if (used[idx]) {
			continue;
		}
		
		used[idx] = true;
		for (long long j = idx - 1; j >= 0; --j) {
			if (path[j] < path[j + 1] - k) {
				result += path[j + 1] - k - path[j];
				path[j] = path[j + 1] - k;
				used[j] = true;
			} else {
				break;
			}
		}
		for (long long j = idx + 1; j < n; ++j) {
			if (path[j] < path[j - 1] - k) {
				result += path[j - 1] - k - path[j];
				path[j] = path[j - 1] - k;
				used[j] = true;
			} else {
				break;
			}
		}
	}
	
	cout << result << endl;
	
	return 0;
}