#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, k, tmp;
cin >> n >> k;
vector <int> a(n);
int res = 0;
for (int i = 0; i < n; ++i) { cin >> a[i]; }
for (int i = 0; i < n; ++i) {
if (i != n - 1) {
if (a[i] - a[i + 1] > k) {
tmp = a[i + 1];
a[i + 1] = a[i] - k;
res += a[i + 1] - tmp;
} else if (a[i + 1] - a[i] > k) {
int j = i;
while (a[j + 1] - a[j] > k && j >= 0) {
tmp = a[j];
a[j] = a[j + 1] - k;
res += a[j] - tmp;
--j;
}
}
}
}
cout << res << '\n';
}
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 | #include <iostream> #include <vector> using namespace std; int main() { int n, k, tmp; cin >> n >> k; vector <int> a(n); int res = 0; for (int i = 0; i < n; ++i) { cin >> a[i]; } for (int i = 0; i < n; ++i) { if (i != n - 1) { if (a[i] - a[i + 1] > k) { tmp = a[i + 1]; a[i + 1] = a[i] - k; res += a[i + 1] - tmp; } else if (a[i + 1] - a[i] > k) { int j = i; while (a[j + 1] - a[j] > k && j >= 0) { tmp = a[j]; a[j] = a[j + 1] - k; res += a[j] - tmp; --j; } } } } cout << res << '\n'; } |
English