#include <iostream>
#include <vector>
#include <algorithm>
std::vector<int> v, max;
struct Greater {
bool operator()(const int& a, const int& b) const {
return v[a] > v[b];
}
};
int main() {
Greater greater;
std::ios::sync_with_stdio(false);
std::cin.tie();
int n, k, x, old, w = 0;
std::cin >> n >> k;
for (int i = 0; i < n; i++) {
std::cin >> x;
v.push_back(x);
max.push_back(i);
}
for (int i = 0; i < n - 1; i++) {
std::sort(max.begin() + i, max.end(), greater);
x = max[i];
if (x != n - 1) {
if (v[x] - v[x + 1] > k) {
w += v[x] - v[x + 1] - k;
v[x + 1] += v[x] - v[x + 1] - k;
}
}
if (x != 0) {
if (v[x] - v[x - 1] > k) {
w += v[x] - v[x - 1] - k;
v[x - 1] += v[x] - v[x - 1] - k;
}
}
}
std::cout << w;
return 0;
}
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 | #include <iostream> #include <vector> #include <algorithm> std::vector<int> v, max; struct Greater { bool operator()(const int& a, const int& b) const { return v[a] > v[b]; } }; int main() { Greater greater; std::ios::sync_with_stdio(false); std::cin.tie(); int n, k, x, old, w = 0; std::cin >> n >> k; for (int i = 0; i < n; i++) { std::cin >> x; v.push_back(x); max.push_back(i); } for (int i = 0; i < n - 1; i++) { std::sort(max.begin() + i, max.end(), greater); x = max[i]; if (x != n - 1) { if (v[x] - v[x + 1] > k) { w += v[x] - v[x + 1] - k; v[x + 1] += v[x] - v[x + 1] - k; } } if (x != 0) { if (v[x] - v[x - 1] > k) { w += v[x] - v[x - 1] - k; v[x - 1] += v[x] - v[x - 1] - k; } } } std::cout << w; return 0; } |
English