#include <cstdlib>
#include <vector>
#include <iostream>
using namespace std;
int main() {
int n, k; cin >> n >> k;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
int res = 0;
for (int i = 1; i < n; i++) {
int d = abs(a[i] - a[i - 1]);
if (d > k) {
res += d - k;
if (a[i] < a[i - 1]) a[i] += d - k;
else a[i - 1] += d - k;
}
}
for (int i = n - 1; i > 0; i--) {
int d = abs(a[i] - a[i - 1]);
if (d > k) {
res += d - k;
if (a[i] < a[i - 1]) a[i] += d - k;
else a[i - 1] += d - k;
}
}
// for (int i = 0; i < n; i++) cout << a[i] << ' ';
// cout << '\n';
cout << res << '\n';
return 0;
}
/*
4 2
7 3 0 2
6 2
0 3 4 8 2 1
*/
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 | #include <cstdlib> #include <vector> #include <iostream> using namespace std; int main() { int n, k; cin >> n >> k; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; int res = 0; for (int i = 1; i < n; i++) { int d = abs(a[i] - a[i - 1]); if (d > k) { res += d - k; if (a[i] < a[i - 1]) a[i] += d - k; else a[i - 1] += d - k; } } for (int i = n - 1; i > 0; i--) { int d = abs(a[i] - a[i - 1]); if (d > k) { res += d - k; if (a[i] < a[i - 1]) a[i] += d - k; else a[i - 1] += d - k; } } // for (int i = 0; i < n; i++) cout << a[i] << ' '; // cout << '\n'; cout << res << '\n'; return 0; } /* 4 2 7 3 0 2 6 2 0 3 4 8 2 1 */ |
English